diff --git a/dist/component-playground.js b/dist/component-playground.js
index d813d28..e623512 100644
--- a/dist/component-playground.js
+++ b/dist/component-playground.js
@@ -7,7 +7,7 @@
exports["ComponentPlayground"] = factory(require("react"), require("react-dom"));
else
root["ComponentPlayground"] = factory(root["React"], root["ReactDom"]);
-})(this, function(__WEBPACK_EXTERNAL_MODULE_298__, __WEBPACK_EXTERNAL_MODULE_310__) {
+})(this, function(__WEBPACK_EXTERNAL_MODULE_327__, __WEBPACK_EXTERNAL_MODULE_345__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
@@ -82,27 +82,27 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(2);
- var _react = __webpack_require__(298);
+ var _react = __webpack_require__(327);
var _react2 = _interopRequireDefault(_react);
- var _propTypes = __webpack_require__(299);
+ var _propTypes = __webpack_require__(328);
var _propTypes2 = _interopRequireDefault(_propTypes);
- var _editor = __webpack_require__(308);
+ var _editor = __webpack_require__(338);
var _editor2 = _interopRequireDefault(_editor);
- var _preview = __webpack_require__(323);
+ var _preview = __webpack_require__(344);
var _preview2 = _interopRequireDefault(_preview);
- var _es6Preview = __webpack_require__(494);
+ var _es6Preview = __webpack_require__(360);
var _es6Preview2 = _interopRequireDefault(_es6Preview);
- var _doc = __webpack_require__(495);
+ var _doc = __webpack_require__(361);
var _doc2 = _interopRequireDefault(_doc);
@@ -175,7 +175,8 @@ return /******/ (function(modules) { // webpackBootstrap
{ className: "playground" + (collapsableCode ? " collapsableCode" : "") },
docClass ? _react2.default.createElement(_doc2.default, {
componentClass: docClass,
- propDescriptionMap: propDescriptionMap }) : null,
+ propDescriptionMap: propDescriptionMap
+ }) : null,
_react2.default.createElement(
"div",
{ className: "playgroundCode" + (expandedCode ? " expandedCode" : "") },
@@ -185,7 +186,8 @@ return /******/ (function(modules) { // webpackBootstrap
external: external,
onChange: this._handleCodeChange,
selectedLines: selectedLines,
- theme: theme })
+ theme: theme
+ })
),
collapsableCode ? _react2.default.createElement(
"div",
@@ -201,12 +203,14 @@ return /******/ (function(modules) { // webpackBootstrap
{ className: "playgroundPreview" },
es6Console ? _react2.default.createElement(_es6Preview2.default, {
code: code,
- scope: scope }) : _react2.default.createElement(_preview2.default, {
+ scope: scope
+ }) : _react2.default.createElement(_preview2.default, {
context: context,
code: code,
scope: scope,
noRender: noRender,
- previewComponent: previewComponent })
+ previewComponent: previewComponent
+ })
)
);
}
@@ -245,9 +249,9 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(3);
- __webpack_require__(294);
+ __webpack_require__(323);
- __webpack_require__(295);
+ __webpack_require__(324);
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
@@ -276,11 +280,12 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(4);
+ __webpack_require__(52);
__webpack_require__(53);
__webpack_require__(54);
__webpack_require__(55);
- __webpack_require__(56);
- __webpack_require__(58);
+ __webpack_require__(57);
+ __webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(63);
@@ -289,35 +294,34 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(66);
__webpack_require__(67);
__webpack_require__(68);
- __webpack_require__(69);
- __webpack_require__(71);
- __webpack_require__(73);
- __webpack_require__(75);
- __webpack_require__(77);
+ __webpack_require__(70);
+ __webpack_require__(72);
+ __webpack_require__(74);
+ __webpack_require__(76);
+ __webpack_require__(79);
__webpack_require__(80);
__webpack_require__(81);
- __webpack_require__(82);
- __webpack_require__(86);
- __webpack_require__(88);
- __webpack_require__(90);
+ __webpack_require__(85);
+ __webpack_require__(87);
+ __webpack_require__(89);
+ __webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
- __webpack_require__(96);
+ __webpack_require__(97);
__webpack_require__(98);
__webpack_require__(99);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(102);
__webpack_require__(103);
- __webpack_require__(104);
+ __webpack_require__(105);
__webpack_require__(106);
__webpack_require__(107);
- __webpack_require__(108);
+ __webpack_require__(109);
__webpack_require__(110);
__webpack_require__(111);
- __webpack_require__(112);
- __webpack_require__(114);
+ __webpack_require__(113);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
@@ -352,50 +356,44 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(154);
__webpack_require__(155);
__webpack_require__(156);
- __webpack_require__(157);
__webpack_require__(158);
- __webpack_require__(160);
+ __webpack_require__(159);
__webpack_require__(161);
- __webpack_require__(167);
+ __webpack_require__(162);
__webpack_require__(168);
- __webpack_require__(170);
+ __webpack_require__(169);
__webpack_require__(171);
__webpack_require__(172);
- __webpack_require__(176);
+ __webpack_require__(173);
__webpack_require__(177);
__webpack_require__(178);
__webpack_require__(179);
__webpack_require__(180);
- __webpack_require__(182);
+ __webpack_require__(181);
__webpack_require__(183);
__webpack_require__(184);
__webpack_require__(185);
- __webpack_require__(188);
- __webpack_require__(190);
+ __webpack_require__(186);
+ __webpack_require__(189);
__webpack_require__(191);
__webpack_require__(192);
- __webpack_require__(194);
- __webpack_require__(196);
- __webpack_require__(198);
+ __webpack_require__(193);
+ __webpack_require__(195);
+ __webpack_require__(197);
__webpack_require__(199);
__webpack_require__(200);
- __webpack_require__(202);
+ __webpack_require__(201);
__webpack_require__(203);
__webpack_require__(204);
__webpack_require__(205);
- __webpack_require__(212);
- __webpack_require__(215);
+ __webpack_require__(206);
__webpack_require__(216);
- __webpack_require__(218);
- __webpack_require__(219);
- __webpack_require__(222);
+ __webpack_require__(220);
+ __webpack_require__(221);
__webpack_require__(223);
- __webpack_require__(225);
- __webpack_require__(226);
- __webpack_require__(227);
+ __webpack_require__(224);
__webpack_require__(228);
__webpack_require__(229);
- __webpack_require__(230);
__webpack_require__(231);
__webpack_require__(232);
__webpack_require__(233);
@@ -409,238 +407,265 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(241);
__webpack_require__(242);
__webpack_require__(243);
+ __webpack_require__(244);
__webpack_require__(245);
__webpack_require__(246);
__webpack_require__(247);
__webpack_require__(248);
__webpack_require__(249);
- __webpack_require__(250);
+ __webpack_require__(251);
__webpack_require__(252);
__webpack_require__(253);
__webpack_require__(254);
__webpack_require__(255);
- __webpack_require__(256);
__webpack_require__(257);
__webpack_require__(258);
__webpack_require__(259);
__webpack_require__(261);
__webpack_require__(262);
+ __webpack_require__(263);
__webpack_require__(264);
__webpack_require__(265);
__webpack_require__(266);
__webpack_require__(267);
+ __webpack_require__(268);
__webpack_require__(270);
__webpack_require__(271);
- __webpack_require__(272);
__webpack_require__(273);
__webpack_require__(274);
__webpack_require__(275);
__webpack_require__(276);
- __webpack_require__(277);
__webpack_require__(279);
__webpack_require__(280);
- __webpack_require__(281);
__webpack_require__(282);
__webpack_require__(283);
__webpack_require__(284);
__webpack_require__(285);
- __webpack_require__(286);
__webpack_require__(287);
__webpack_require__(288);
__webpack_require__(289);
+ __webpack_require__(290);
+ __webpack_require__(291);
__webpack_require__(292);
__webpack_require__(293);
+ __webpack_require__(294);
+ __webpack_require__(295);
+ __webpack_require__(296);
+ __webpack_require__(298);
+ __webpack_require__(299);
+ __webpack_require__(300);
+ __webpack_require__(301);
+ __webpack_require__(302);
+ __webpack_require__(303);
+ __webpack_require__(304);
+ __webpack_require__(305);
+ __webpack_require__(306);
+ __webpack_require__(307);
+ __webpack_require__(308);
+ __webpack_require__(310);
+ __webpack_require__(311);
+ __webpack_require__(312);
+ __webpack_require__(313);
+ __webpack_require__(314);
+ __webpack_require__(315);
+ __webpack_require__(316);
+ __webpack_require__(317);
+ __webpack_require__(318);
+ __webpack_require__(319);
+ __webpack_require__(320);
+ __webpack_require__(321);
+ __webpack_require__(322);
module.exports = __webpack_require__(10);
+
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
- var global = __webpack_require__(5)
- , has = __webpack_require__(6)
- , DESCRIPTORS = __webpack_require__(7)
- , $export = __webpack_require__(9)
- , redefine = __webpack_require__(19)
- , META = __webpack_require__(23).KEY
- , $fails = __webpack_require__(8)
- , shared = __webpack_require__(24)
- , setToStringTag = __webpack_require__(25)
- , uid = __webpack_require__(20)
- , wks = __webpack_require__(26)
- , wksExt = __webpack_require__(27)
- , wksDefine = __webpack_require__(28)
- , keyOf = __webpack_require__(30)
- , enumKeys = __webpack_require__(43)
- , isArray = __webpack_require__(46)
- , anObject = __webpack_require__(13)
- , toIObject = __webpack_require__(33)
- , toPrimitive = __webpack_require__(17)
- , createDesc = __webpack_require__(18)
- , _create = __webpack_require__(47)
- , gOPNExt = __webpack_require__(50)
- , $GOPD = __webpack_require__(52)
- , $DP = __webpack_require__(12)
- , $keys = __webpack_require__(31)
- , gOPD = $GOPD.f
- , dP = $DP.f
- , gOPN = gOPNExt.f
- , $Symbol = global.Symbol
- , $JSON = global.JSON
- , _stringify = $JSON && $JSON.stringify
- , PROTOTYPE = 'prototype'
- , HIDDEN = wks('_hidden')
- , TO_PRIMITIVE = wks('toPrimitive')
- , isEnum = {}.propertyIsEnumerable
- , SymbolRegistry = shared('symbol-registry')
- , AllSymbols = shared('symbols')
- , OPSymbols = shared('op-symbols')
- , ObjectProto = Object[PROTOTYPE]
- , USE_NATIVE = typeof $Symbol == 'function'
- , QObject = global.QObject;
+ var global = __webpack_require__(5);
+ var has = __webpack_require__(6);
+ var DESCRIPTORS = __webpack_require__(7);
+ var $export = __webpack_require__(9);
+ var redefine = __webpack_require__(19);
+ var META = __webpack_require__(23).KEY;
+ var $fails = __webpack_require__(8);
+ var shared = __webpack_require__(24);
+ var setToStringTag = __webpack_require__(25);
+ var uid = __webpack_require__(20);
+ var wks = __webpack_require__(26);
+ var wksExt = __webpack_require__(27);
+ var wksDefine = __webpack_require__(28);
+ var enumKeys = __webpack_require__(30);
+ var isArray = __webpack_require__(45);
+ var anObject = __webpack_require__(13);
+ var toIObject = __webpack_require__(33);
+ var toPrimitive = __webpack_require__(17);
+ var createDesc = __webpack_require__(18);
+ var _create = __webpack_require__(46);
+ var gOPNExt = __webpack_require__(49);
+ var $GOPD = __webpack_require__(51);
+ var $DP = __webpack_require__(12);
+ var $keys = __webpack_require__(31);
+ var gOPD = $GOPD.f;
+ var dP = $DP.f;
+ var gOPN = gOPNExt.f;
+ var $Symbol = global.Symbol;
+ var $JSON = global.JSON;
+ var _stringify = $JSON && $JSON.stringify;
+ var PROTOTYPE = 'prototype';
+ var HIDDEN = wks('_hidden');
+ var TO_PRIMITIVE = wks('toPrimitive');
+ var isEnum = {}.propertyIsEnumerable;
+ var SymbolRegistry = shared('symbol-registry');
+ var AllSymbols = shared('symbols');
+ var OPSymbols = shared('op-symbols');
+ var ObjectProto = Object[PROTOTYPE];
+ var USE_NATIVE = typeof $Symbol == 'function';
+ var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
- var setSymbolDesc = DESCRIPTORS && $fails(function(){
+ var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
- get: function(){ return dP(this, 'a', {value: 7}).a; }
+ get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
- }) ? function(it, key, D){
+ }) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
- if(protoDesc)delete ObjectProto[key];
+ if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
- if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
+ if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
- var wrap = function(tag){
+ var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
- var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
+ var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
- } : function(it){
+ } : function (it) {
return it instanceof $Symbol;
};
- var $defineProperty = function defineProperty(it, key, D){
- if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
+ var $defineProperty = function defineProperty(it, key, D) {
+ if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
- if(has(AllSymbols, key)){
- if(!D.enumerable){
- if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
+ if (has(AllSymbols, key)) {
+ if (!D.enumerable) {
+ if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
- if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
- D = _create(D, {enumerable: createDesc(0, false)});
+ if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
+ D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
- var $defineProperties = function defineProperties(it, P){
+ var $defineProperties = function defineProperties(it, P) {
anObject(it);
- var keys = enumKeys(P = toIObject(P))
- , i = 0
- , l = keys.length
- , key;
- while(l > i)$defineProperty(it, key = keys[i++], P[key]);
+ var keys = enumKeys(P = toIObject(P));
+ var i = 0;
+ var l = keys.length;
+ var key;
+ while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
- var $create = function create(it, P){
+ var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
- var $propertyIsEnumerable = function propertyIsEnumerable(key){
+ var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
- if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
+ if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
- var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
- it = toIObject(it);
+ var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
+ it = toIObject(it);
key = toPrimitive(key, true);
- if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
+ if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
- if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
+ if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
- var $getOwnPropertyNames = function getOwnPropertyNames(it){
- var names = gOPN(toIObject(it))
- , result = []
- , i = 0
- , key;
- while(names.length > i){
- if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
+ var $getOwnPropertyNames = function getOwnPropertyNames(it) {
+ var names = gOPN(toIObject(it));
+ var result = [];
+ var i = 0;
+ var key;
+ while (names.length > i) {
+ if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
- var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
- var IS_OP = it === ObjectProto
- , names = gOPN(IS_OP ? OPSymbols : toIObject(it))
- , result = []
- , i = 0
- , key;
- while(names.length > i){
- if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
+ var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
+ var IS_OP = it === ObjectProto;
+ var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
+ var result = [];
+ var i = 0;
+ var key;
+ while (names.length > i) {
+ if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
- if(!USE_NATIVE){
- $Symbol = function Symbol(){
- if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
+ if (!USE_NATIVE) {
+ $Symbol = function Symbol() {
+ if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
- var $set = function(value){
- if(this === ObjectProto)$set.call(OPSymbols, value);
- if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
+ var $set = function (value) {
+ if (this === ObjectProto) $set.call(OPSymbols, value);
+ if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
- if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
+ if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
- redefine($Symbol[PROTOTYPE], 'toString', function toString(){
+ redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
- $DP.f = $defineProperty;
- __webpack_require__(51).f = gOPNExt.f = $getOwnPropertyNames;
- __webpack_require__(45).f = $propertyIsEnumerable;
- __webpack_require__(44).f = $getOwnPropertySymbols;
+ $DP.f = $defineProperty;
+ __webpack_require__(50).f = gOPNExt.f = $getOwnPropertyNames;
+ __webpack_require__(44).f = $propertyIsEnumerable;
+ __webpack_require__(43).f = $getOwnPropertySymbols;
- if(DESCRIPTORS && !__webpack_require__(29)){
+ if (DESCRIPTORS && !__webpack_require__(29)) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
- wksExt.f = function(name){
+ wksExt.f = function (name) {
return wrap(wks(name));
- }
+ };
}
- $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
+ $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
- for(var symbols = (
+ for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
- ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
+ ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
- for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
+ for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
- 'for': function(key){
+ 'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
- keyFor: function keyFor(key){
- if(isSymbol(key))return keyOf(SymbolRegistry, key);
- throw TypeError(key + ' is not a symbol!');
+ keyFor: function keyFor(sym) {
+ if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
+ for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
- useSetter: function(){ setter = true; },
- useSimple: function(){ setter = false; }
+ useSetter: function () { setter = true; },
+ useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
@@ -659,24 +684,24 @@ return /******/ (function(modules) { // webpackBootstrap
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
- $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
+ $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
- return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
+ return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
- stringify: function stringify(it){
- if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
- var args = [it]
- , i = 1
- , replacer, $replacer;
- while(arguments.length > i)args.push(arguments[i++]);
+ stringify: function stringify(it) {
+ if (it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
+ var args = [it];
+ var i = 1;
+ var replacer, $replacer;
+ while (arguments.length > i) args.push(arguments[i++]);
replacer = args[1];
- if(typeof replacer == 'function')$replacer = replacer;
- if($replacer || !isArray(replacer))replacer = function(key, value){
- if($replacer)value = $replacer.call(this, key, value);
- if(!isSymbol(value))return value;
+ if (typeof replacer == 'function') $replacer = replacer;
+ if ($replacer || !isArray(replacer)) replacer = function (key, value) {
+ if ($replacer) value = $replacer.call(this, key, value);
+ if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
@@ -692,68 +717,75 @@ return /******/ (function(modules) { // webpackBootstrap
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
+
/***/ }),
/* 5 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
- ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
- if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
+ ? window : typeof self != 'undefined' && self.Math == Math ? self
+ // eslint-disable-next-line no-new-func
+ : Function('return this')();
+ if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
+
/***/ }),
/* 6 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
- module.exports = function(it, key){
+ module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
+
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
- module.exports = !__webpack_require__(8)(function(){
- return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
+ module.exports = !__webpack_require__(8)(function () {
+ return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
+
/***/ }),
/* 8 */
/***/ (function(module, exports) {
- module.exports = function(exec){
+ module.exports = function (exec) {
try {
return !!exec();
- } catch(e){
+ } catch (e) {
return true;
}
};
+
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , core = __webpack_require__(10)
- , hide = __webpack_require__(11)
- , redefine = __webpack_require__(19)
- , ctx = __webpack_require__(21)
- , PROTOTYPE = 'prototype';
-
- var $export = function(type, name, source){
- var IS_FORCED = type & $export.F
- , IS_GLOBAL = type & $export.G
- , IS_STATIC = type & $export.S
- , IS_PROTO = type & $export.P
- , IS_BIND = type & $export.B
- , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
- , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
- , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
- , key, own, out, exp;
- if(IS_GLOBAL)source = name;
- for(key in source){
+ var global = __webpack_require__(5);
+ var core = __webpack_require__(10);
+ var hide = __webpack_require__(11);
+ var redefine = __webpack_require__(19);
+ var ctx = __webpack_require__(21);
+ var PROTOTYPE = 'prototype';
+
+ var $export = function (type, name, source) {
+ var IS_FORCED = type & $export.F;
+ var IS_GLOBAL = type & $export.G;
+ var IS_STATIC = type & $export.S;
+ var IS_PROTO = type & $export.P;
+ var IS_BIND = type & $export.B;
+ var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
+ var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
+ var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
+ var key, own, out, exp;
+ if (IS_GLOBAL) source = name;
+ for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
@@ -761,10 +793,10 @@ return /******/ (function(modules) { // webpackBootstrap
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
- if(target)redefine(target, key, out, type & $export.U);
+ if (target) redefine(target, key, out, type & $export.U);
// export
- if(exports[key] != out)hide(exports, key, exp);
- if(IS_PROTO && expProto[key] != out)expProto[key] = out;
+ if (exports[key] != out) hide(exports, key, exp);
+ if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
@@ -776,88 +808,96 @@ return /******/ (function(modules) { // webpackBootstrap
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
- $export.R = 128; // real proto method for `library`
+ $export.R = 128; // real proto method for `library`
module.exports = $export;
+
/***/ }),
/* 10 */
/***/ (function(module, exports) {
- var core = module.exports = {version: '2.4.0'};
- if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
+ var core = module.exports = { version: '2.5.1' };
+ if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
+
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
- var dP = __webpack_require__(12)
- , createDesc = __webpack_require__(18);
- module.exports = __webpack_require__(7) ? function(object, key, value){
+ var dP = __webpack_require__(12);
+ var createDesc = __webpack_require__(18);
+ module.exports = __webpack_require__(7) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
- } : function(object, key, value){
+ } : function (object, key, value) {
object[key] = value;
return object;
};
+
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
- var anObject = __webpack_require__(13)
- , IE8_DOM_DEFINE = __webpack_require__(15)
- , toPrimitive = __webpack_require__(17)
- , dP = Object.defineProperty;
+ var anObject = __webpack_require__(13);
+ var IE8_DOM_DEFINE = __webpack_require__(15);
+ var toPrimitive = __webpack_require__(17);
+ var dP = Object.defineProperty;
- exports.f = __webpack_require__(7) ? Object.defineProperty : function defineProperty(O, P, Attributes){
+ exports.f = __webpack_require__(7) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
- if(IE8_DOM_DEFINE)try {
+ if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
- } catch(e){ /* empty */ }
- if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
- if('value' in Attributes)O[P] = Attributes.value;
+ } catch (e) { /* empty */ }
+ if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
+ if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
+
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(14);
- module.exports = function(it){
- if(!isObject(it))throw TypeError(it + ' is not an object!');
+ module.exports = function (it) {
+ if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
+
/***/ }),
/* 14 */
/***/ (function(module, exports) {
- module.exports = function(it){
+ module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
+
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
- module.exports = !__webpack_require__(7) && !__webpack_require__(8)(function(){
- return Object.defineProperty(__webpack_require__(16)('div'), 'a', {get: function(){ return 7; }}).a != 7;
+ module.exports = !__webpack_require__(7) && !__webpack_require__(8)(function () {
+ return Object.defineProperty(__webpack_require__(16)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
+
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
- var isObject = __webpack_require__(14)
- , document = __webpack_require__(5).document
- // in old IE typeof document.createElement is 'object'
- , is = isObject(document) && isObject(document.createElement);
- module.exports = function(it){
+ var isObject = __webpack_require__(14);
+ var document = __webpack_require__(5).document;
+ // typeof document.createElement is 'object' in old IE
+ var is = isObject(document) && isObject(document.createElement);
+ module.exports = function (it) {
return is ? document.createElement(it) : {};
};
+
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
@@ -866,392 +906,424 @@ return /******/ (function(modules) { // webpackBootstrap
var isObject = __webpack_require__(14);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
- module.exports = function(it, S){
- if(!isObject(it))return it;
+ module.exports = function (it, S) {
+ if (!isObject(it)) return it;
var fn, val;
- if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
- if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
- if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
+ if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
+ if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
+ if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
+
/***/ }),
/* 18 */
/***/ (function(module, exports) {
- module.exports = function(bitmap, value){
+ module.exports = function (bitmap, value) {
return {
- enumerable : !(bitmap & 1),
+ enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
- writable : !(bitmap & 4),
- value : value
+ writable: !(bitmap & 4),
+ value: value
};
};
+
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , hide = __webpack_require__(11)
- , has = __webpack_require__(6)
- , SRC = __webpack_require__(20)('src')
- , TO_STRING = 'toString'
- , $toString = Function[TO_STRING]
- , TPL = ('' + $toString).split(TO_STRING);
+ var global = __webpack_require__(5);
+ var hide = __webpack_require__(11);
+ var has = __webpack_require__(6);
+ var SRC = __webpack_require__(20)('src');
+ var TO_STRING = 'toString';
+ var $toString = Function[TO_STRING];
+ var TPL = ('' + $toString).split(TO_STRING);
- __webpack_require__(10).inspectSource = function(it){
+ __webpack_require__(10).inspectSource = function (it) {
return $toString.call(it);
};
- (module.exports = function(O, key, val, safe){
+ (module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
- if(isFunction)has(val, 'name') || hide(val, 'name', key);
- if(O[key] === val)return;
- if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
- if(O === global){
+ if (isFunction) has(val, 'name') || hide(val, 'name', key);
+ if (O[key] === val) return;
+ if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
+ if (O === global) {
+ O[key] = val;
+ } else if (!safe) {
+ delete O[key];
+ hide(O, key, val);
+ } else if (O[key]) {
O[key] = val;
} else {
- if(!safe){
- delete O[key];
- hide(O, key, val);
- } else {
- if(O[key])O[key] = val;
- else hide(O, key, val);
- }
+ hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
- })(Function.prototype, TO_STRING, function toString(){
+ })(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
+
/***/ }),
/* 20 */
/***/ (function(module, exports) {
- var id = 0
- , px = Math.random();
- module.exports = function(key){
+ var id = 0;
+ var px = Math.random();
+ module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
+
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(22);
- module.exports = function(fn, that, length){
+ module.exports = function (fn, that, length) {
aFunction(fn);
- if(that === undefined)return fn;
- switch(length){
- case 1: return function(a){
+ if (that === undefined) return fn;
+ switch (length) {
+ case 1: return function (a) {
return fn.call(that, a);
};
- case 2: return function(a, b){
+ case 2: return function (a, b) {
return fn.call(that, a, b);
};
- case 3: return function(a, b, c){
+ case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
- return function(/* ...args */){
+ return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
+
/***/ }),
/* 22 */
/***/ (function(module, exports) {
- module.exports = function(it){
- if(typeof it != 'function')throw TypeError(it + ' is not a function!');
+ module.exports = function (it) {
+ if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
+
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
- var META = __webpack_require__(20)('meta')
- , isObject = __webpack_require__(14)
- , has = __webpack_require__(6)
- , setDesc = __webpack_require__(12).f
- , id = 0;
- var isExtensible = Object.isExtensible || function(){
+ var META = __webpack_require__(20)('meta');
+ var isObject = __webpack_require__(14);
+ var has = __webpack_require__(6);
+ var setDesc = __webpack_require__(12).f;
+ var id = 0;
+ var isExtensible = Object.isExtensible || function () {
return true;
};
- var FREEZE = !__webpack_require__(8)(function(){
+ var FREEZE = !__webpack_require__(8)(function () {
return isExtensible(Object.preventExtensions({}));
});
- var setMeta = function(it){
- setDesc(it, META, {value: {
+ var setMeta = function (it) {
+ setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
- }});
+ } });
};
- var fastKey = function(it, create){
+ var fastKey = function (it, create) {
// return primitive with prefix
- if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
- if(!has(it, META)){
+ if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
+ if (!has(it, META)) {
// can't set metadata to uncaught frozen object
- if(!isExtensible(it))return 'F';
+ if (!isExtensible(it)) return 'F';
// not necessary to add metadata
- if(!create)return 'E';
+ if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
- var getWeak = function(it, create){
- if(!has(it, META)){
+ var getWeak = function (it, create) {
+ if (!has(it, META)) {
// can't set metadata to uncaught frozen object
- if(!isExtensible(it))return true;
+ if (!isExtensible(it)) return true;
// not necessary to add metadata
- if(!create)return false;
+ if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
- var onFreeze = function(it){
- if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
+ var onFreeze = function (it) {
+ if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
- KEY: META,
- NEED: false,
- fastKey: fastKey,
- getWeak: getWeak,
+ KEY: META,
+ NEED: false,
+ fastKey: fastKey,
+ getWeak: getWeak,
onFreeze: onFreeze
};
+
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , SHARED = '__core-js_shared__'
- , store = global[SHARED] || (global[SHARED] = {});
- module.exports = function(key){
+ var global = __webpack_require__(5);
+ var SHARED = '__core-js_shared__';
+ var store = global[SHARED] || (global[SHARED] = {});
+ module.exports = function (key) {
return store[key] || (store[key] = {});
};
+
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
- var def = __webpack_require__(12).f
- , has = __webpack_require__(6)
- , TAG = __webpack_require__(26)('toStringTag');
+ var def = __webpack_require__(12).f;
+ var has = __webpack_require__(6);
+ var TAG = __webpack_require__(26)('toStringTag');
- module.exports = function(it, tag, stat){
- if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
+ module.exports = function (it, tag, stat) {
+ if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
+
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
- var store = __webpack_require__(24)('wks')
- , uid = __webpack_require__(20)
- , Symbol = __webpack_require__(5).Symbol
- , USE_SYMBOL = typeof Symbol == 'function';
+ var store = __webpack_require__(24)('wks');
+ var uid = __webpack_require__(20);
+ var Symbol = __webpack_require__(5).Symbol;
+ var USE_SYMBOL = typeof Symbol == 'function';
- var $exports = module.exports = function(name){
+ var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
+
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(26);
+
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , core = __webpack_require__(10)
- , LIBRARY = __webpack_require__(29)
- , wksExt = __webpack_require__(27)
- , defineProperty = __webpack_require__(12).f;
- module.exports = function(name){
+ var global = __webpack_require__(5);
+ var core = __webpack_require__(10);
+ var LIBRARY = __webpack_require__(29);
+ var wksExt = __webpack_require__(27);
+ var defineProperty = __webpack_require__(12).f;
+ module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
- if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
+ if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
+
/***/ }),
/* 29 */
/***/ (function(module, exports) {
module.exports = false;
+
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
- var getKeys = __webpack_require__(31)
- , toIObject = __webpack_require__(33);
- module.exports = function(object, el){
- var O = toIObject(object)
- , keys = getKeys(O)
- , length = keys.length
- , index = 0
- , key;
- while(length > index)if(O[key = keys[index++]] === el)return key;
+ // all enumerable object keys, includes symbols
+ var getKeys = __webpack_require__(31);
+ var gOPS = __webpack_require__(43);
+ var pIE = __webpack_require__(44);
+ module.exports = function (it) {
+ var result = getKeys(it);
+ var getSymbols = gOPS.f;
+ if (getSymbols) {
+ var symbols = getSymbols(it);
+ var isEnum = pIE.f;
+ var i = 0;
+ var key;
+ while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
+ } return result;
};
+
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
- var $keys = __webpack_require__(32)
- , enumBugKeys = __webpack_require__(42);
+ var $keys = __webpack_require__(32);
+ var enumBugKeys = __webpack_require__(42);
- module.exports = Object.keys || function keys(O){
+ module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
+
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
- var has = __webpack_require__(6)
- , toIObject = __webpack_require__(33)
- , arrayIndexOf = __webpack_require__(37)(false)
- , IE_PROTO = __webpack_require__(41)('IE_PROTO');
-
- module.exports = function(object, names){
- var O = toIObject(object)
- , i = 0
- , result = []
- , key;
- for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
+ var has = __webpack_require__(6);
+ var toIObject = __webpack_require__(33);
+ var arrayIndexOf = __webpack_require__(37)(false);
+ var IE_PROTO = __webpack_require__(41)('IE_PROTO');
+
+ module.exports = function (object, names) {
+ var O = toIObject(object);
+ var i = 0;
+ var result = [];
+ var key;
+ for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
- while(names.length > i)if(has(O, key = names[i++])){
+ while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
+
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
- var IObject = __webpack_require__(34)
- , defined = __webpack_require__(36);
- module.exports = function(it){
+ var IObject = __webpack_require__(34);
+ var defined = __webpack_require__(36);
+ module.exports = function (it) {
return IObject(defined(it));
};
+
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(35);
- module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
+ // eslint-disable-next-line no-prototype-builtins
+ module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
+
/***/ }),
/* 35 */
/***/ (function(module, exports) {
var toString = {}.toString;
- module.exports = function(it){
+ module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
+
/***/ }),
/* 36 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
- module.exports = function(it){
- if(it == undefined)throw TypeError("Can't call method on " + it);
+ module.exports = function (it) {
+ if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
+
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
- var toIObject = __webpack_require__(33)
- , toLength = __webpack_require__(38)
- , toIndex = __webpack_require__(40);
- module.exports = function(IS_INCLUDES){
- return function($this, el, fromIndex){
- var O = toIObject($this)
- , length = toLength(O.length)
- , index = toIndex(fromIndex, length)
- , value;
+ var toIObject = __webpack_require__(33);
+ var toLength = __webpack_require__(38);
+ var toAbsoluteIndex = __webpack_require__(40);
+ module.exports = function (IS_INCLUDES) {
+ return function ($this, el, fromIndex) {
+ var O = toIObject($this);
+ var length = toLength(O.length);
+ var index = toAbsoluteIndex(fromIndex, length);
+ var value;
// Array#includes uses SameValueZero equality algorithm
- if(IS_INCLUDES && el != el)while(length > index){
+ // eslint-disable-next-line no-self-compare
+ if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
- if(value != value)return true;
- // Array#toIndex ignores holes, Array#includes - not
- } else for(;length > index; index++)if(IS_INCLUDES || index in O){
- if(O[index] === el)return IS_INCLUDES || index || 0;
+ // eslint-disable-next-line no-self-compare
+ if (value != value) return true;
+ // Array#indexOf ignores holes, Array#includes - not
+ } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
+ if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
+
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
- var toInteger = __webpack_require__(39)
- , min = Math.min;
- module.exports = function(it){
+ var toInteger = __webpack_require__(39);
+ var min = Math.min;
+ module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
+
/***/ }),
/* 39 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
- var ceil = Math.ceil
- , floor = Math.floor;
- module.exports = function(it){
+ var ceil = Math.ceil;
+ var floor = Math.floor;
+ module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
+
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
- var toInteger = __webpack_require__(39)
- , max = Math.max
- , min = Math.min;
- module.exports = function(index, length){
+ var toInteger = __webpack_require__(39);
+ var max = Math.max;
+ var min = Math.min;
+ module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
+
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
- var shared = __webpack_require__(24)('keys')
- , uid = __webpack_require__(20);
- module.exports = function(key){
+ var shared = __webpack_require__(24)('keys');
+ var uid = __webpack_require__(20);
+ module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
+
/***/ }),
/* 42 */
/***/ (function(module, exports) {
@@ -1261,70 +1333,54 @@ return /******/ (function(modules) { // webpackBootstrap
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
-/***/ }),
-/* 43 */
-/***/ (function(module, exports, __webpack_require__) {
-
- // all enumerable object keys, includes symbols
- var getKeys = __webpack_require__(31)
- , gOPS = __webpack_require__(44)
- , pIE = __webpack_require__(45);
- module.exports = function(it){
- var result = getKeys(it)
- , getSymbols = gOPS.f;
- if(getSymbols){
- var symbols = getSymbols(it)
- , isEnum = pIE.f
- , i = 0
- , key;
- while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
- } return result;
- };
/***/ }),
-/* 44 */
+/* 43 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
+
/***/ }),
-/* 45 */
+/* 44 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
+
/***/ }),
-/* 46 */
+/* 45 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(35);
- module.exports = Array.isArray || function isArray(arg){
+ module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
+
/***/ }),
-/* 47 */
+/* 46 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
- var anObject = __webpack_require__(13)
- , dPs = __webpack_require__(48)
- , enumBugKeys = __webpack_require__(42)
- , IE_PROTO = __webpack_require__(41)('IE_PROTO')
- , Empty = function(){ /* empty */ }
- , PROTOTYPE = 'prototype';
+ var anObject = __webpack_require__(13);
+ var dPs = __webpack_require__(47);
+ var enumBugKeys = __webpack_require__(42);
+ var IE_PROTO = __webpack_require__(41)('IE_PROTO');
+ var Empty = function () { /* empty */ };
+ var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
- var createDict = function(){
+ var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
- var iframe = __webpack_require__(16)('iframe')
- , i = enumBugKeys.length
- , lt = '<'
- , gt = '>'
- , iframeDocument;
+ var iframe = __webpack_require__(16)('iframe');
+ var i = enumBugKeys.length;
+ var lt = '<';
+ var gt = '>';
+ var iframeDocument;
iframe.style.display = 'none';
- __webpack_require__(49).appendChild(iframe);
+ __webpack_require__(48).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
@@ -1333,15 +1389,15 @@ return /******/ (function(modules) { // webpackBootstrap
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
- while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
+ while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
- module.exports = Object.create || function create(O, Properties){
+ module.exports = Object.create || function create(O, Properties) {
var result;
- if(O !== null){
+ if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
- result = new Empty;
+ result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
@@ -1351,381 +1407,409 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 48 */
+/* 47 */
/***/ (function(module, exports, __webpack_require__) {
- var dP = __webpack_require__(12)
- , anObject = __webpack_require__(13)
- , getKeys = __webpack_require__(31);
+ var dP = __webpack_require__(12);
+ var anObject = __webpack_require__(13);
+ var getKeys = __webpack_require__(31);
- module.exports = __webpack_require__(7) ? Object.defineProperties : function defineProperties(O, Properties){
+ module.exports = __webpack_require__(7) ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
- var keys = getKeys(Properties)
- , length = keys.length
- , i = 0
- , P;
- while(length > i)dP.f(O, P = keys[i++], Properties[P]);
+ var keys = getKeys(Properties);
+ var length = keys.length;
+ var i = 0;
+ var P;
+ while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
+
/***/ }),
-/* 49 */
+/* 48 */
/***/ (function(module, exports, __webpack_require__) {
- module.exports = __webpack_require__(5).document && document.documentElement;
+ var document = __webpack_require__(5).document;
+ module.exports = document && document.documentElement;
+
/***/ }),
-/* 50 */
+/* 49 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
- var toIObject = __webpack_require__(33)
- , gOPN = __webpack_require__(51).f
- , toString = {}.toString;
+ var toIObject = __webpack_require__(33);
+ var gOPN = __webpack_require__(50).f;
+ var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
- var getWindowNames = function(it){
+ var getWindowNames = function (it) {
try {
return gOPN(it);
- } catch(e){
+ } catch (e) {
return windowNames.slice();
}
};
- module.exports.f = function getOwnPropertyNames(it){
+ module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
-/* 51 */
+/* 50 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
- var $keys = __webpack_require__(32)
- , hiddenKeys = __webpack_require__(42).concat('length', 'prototype');
+ var $keys = __webpack_require__(32);
+ var hiddenKeys = __webpack_require__(42).concat('length', 'prototype');
- exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
+ exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
+
/***/ }),
-/* 52 */
+/* 51 */
/***/ (function(module, exports, __webpack_require__) {
- var pIE = __webpack_require__(45)
- , createDesc = __webpack_require__(18)
- , toIObject = __webpack_require__(33)
- , toPrimitive = __webpack_require__(17)
- , has = __webpack_require__(6)
- , IE8_DOM_DEFINE = __webpack_require__(15)
- , gOPD = Object.getOwnPropertyDescriptor;
+ var pIE = __webpack_require__(44);
+ var createDesc = __webpack_require__(18);
+ var toIObject = __webpack_require__(33);
+ var toPrimitive = __webpack_require__(17);
+ var has = __webpack_require__(6);
+ var IE8_DOM_DEFINE = __webpack_require__(15);
+ var gOPD = Object.getOwnPropertyDescriptor;
- exports.f = __webpack_require__(7) ? gOPD : function getOwnPropertyDescriptor(O, P){
+ exports.f = __webpack_require__(7) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
- if(IE8_DOM_DEFINE)try {
+ if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
- } catch(e){ /* empty */ }
- if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
+ } catch (e) { /* empty */ }
+ if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
+
/***/ }),
-/* 53 */
+/* 52 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
+ var $export = __webpack_require__(9);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
- $export($export.S, 'Object', {create: __webpack_require__(47)});
+ $export($export.S, 'Object', { create: __webpack_require__(46) });
+
/***/ }),
-/* 54 */
+/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(9);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
- $export($export.S + $export.F * !__webpack_require__(7), 'Object', {defineProperty: __webpack_require__(12).f});
+ $export($export.S + $export.F * !__webpack_require__(7), 'Object', { defineProperty: __webpack_require__(12).f });
+
/***/ }),
-/* 55 */
+/* 54 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(9);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
- $export($export.S + $export.F * !__webpack_require__(7), 'Object', {defineProperties: __webpack_require__(48)});
+ $export($export.S + $export.F * !__webpack_require__(7), 'Object', { defineProperties: __webpack_require__(47) });
+
/***/ }),
-/* 56 */
+/* 55 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
- var toIObject = __webpack_require__(33)
- , $getOwnPropertyDescriptor = __webpack_require__(52).f;
+ var toIObject = __webpack_require__(33);
+ var $getOwnPropertyDescriptor = __webpack_require__(51).f;
- __webpack_require__(57)('getOwnPropertyDescriptor', function(){
- return function getOwnPropertyDescriptor(it, key){
+ __webpack_require__(56)('getOwnPropertyDescriptor', function () {
+ return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
+
/***/ }),
-/* 57 */
+/* 56 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
- var $export = __webpack_require__(9)
- , core = __webpack_require__(10)
- , fails = __webpack_require__(8);
- module.exports = function(KEY, exec){
- var fn = (core.Object || {})[KEY] || Object[KEY]
- , exp = {};
+ var $export = __webpack_require__(9);
+ var core = __webpack_require__(10);
+ var fails = __webpack_require__(8);
+ module.exports = function (KEY, exec) {
+ var fn = (core.Object || {})[KEY] || Object[KEY];
+ var exp = {};
exp[KEY] = exec(fn);
- $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
+ $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
+
/***/ }),
-/* 58 */
+/* 57 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
- var toObject = __webpack_require__(59)
- , $getPrototypeOf = __webpack_require__(60);
+ var toObject = __webpack_require__(58);
+ var $getPrototypeOf = __webpack_require__(59);
- __webpack_require__(57)('getPrototypeOf', function(){
- return function getPrototypeOf(it){
+ __webpack_require__(56)('getPrototypeOf', function () {
+ return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
+
/***/ }),
-/* 59 */
+/* 58 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(36);
- module.exports = function(it){
+ module.exports = function (it) {
return Object(defined(it));
};
+
/***/ }),
-/* 60 */
+/* 59 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
- var has = __webpack_require__(6)
- , toObject = __webpack_require__(59)
- , IE_PROTO = __webpack_require__(41)('IE_PROTO')
- , ObjectProto = Object.prototype;
+ var has = __webpack_require__(6);
+ var toObject = __webpack_require__(58);
+ var IE_PROTO = __webpack_require__(41)('IE_PROTO');
+ var ObjectProto = Object.prototype;
- module.exports = Object.getPrototypeOf || function(O){
+ module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
- if(has(O, IE_PROTO))return O[IE_PROTO];
- if(typeof O.constructor == 'function' && O instanceof O.constructor){
+ if (has(O, IE_PROTO)) return O[IE_PROTO];
+ if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
+
/***/ }),
-/* 61 */
+/* 60 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
- var toObject = __webpack_require__(59)
- , $keys = __webpack_require__(31);
+ var toObject = __webpack_require__(58);
+ var $keys = __webpack_require__(31);
- __webpack_require__(57)('keys', function(){
- return function keys(it){
+ __webpack_require__(56)('keys', function () {
+ return function keys(it) {
return $keys(toObject(it));
};
});
+
/***/ }),
-/* 62 */
+/* 61 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
- __webpack_require__(57)('getOwnPropertyNames', function(){
- return __webpack_require__(50).f;
+ __webpack_require__(56)('getOwnPropertyNames', function () {
+ return __webpack_require__(49).f;
});
+
/***/ }),
-/* 63 */
+/* 62 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
- var isObject = __webpack_require__(14)
- , meta = __webpack_require__(23).onFreeze;
+ var isObject = __webpack_require__(14);
+ var meta = __webpack_require__(23).onFreeze;
- __webpack_require__(57)('freeze', function($freeze){
- return function freeze(it){
+ __webpack_require__(56)('freeze', function ($freeze) {
+ return function freeze(it) {
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
+
/***/ }),
-/* 64 */
+/* 63 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
- var isObject = __webpack_require__(14)
- , meta = __webpack_require__(23).onFreeze;
+ var isObject = __webpack_require__(14);
+ var meta = __webpack_require__(23).onFreeze;
- __webpack_require__(57)('seal', function($seal){
- return function seal(it){
+ __webpack_require__(56)('seal', function ($seal) {
+ return function seal(it) {
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
+
/***/ }),
-/* 65 */
+/* 64 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
- var isObject = __webpack_require__(14)
- , meta = __webpack_require__(23).onFreeze;
+ var isObject = __webpack_require__(14);
+ var meta = __webpack_require__(23).onFreeze;
- __webpack_require__(57)('preventExtensions', function($preventExtensions){
- return function preventExtensions(it){
+ __webpack_require__(56)('preventExtensions', function ($preventExtensions) {
+ return function preventExtensions(it) {
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
+
/***/ }),
-/* 66 */
+/* 65 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(14);
- __webpack_require__(57)('isFrozen', function($isFrozen){
- return function isFrozen(it){
+ __webpack_require__(56)('isFrozen', function ($isFrozen) {
+ return function isFrozen(it) {
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
+
/***/ }),
-/* 67 */
+/* 66 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(14);
- __webpack_require__(57)('isSealed', function($isSealed){
- return function isSealed(it){
+ __webpack_require__(56)('isSealed', function ($isSealed) {
+ return function isSealed(it) {
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
+
/***/ }),
-/* 68 */
+/* 67 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(14);
- __webpack_require__(57)('isExtensible', function($isExtensible){
- return function isExtensible(it){
+ __webpack_require__(56)('isExtensible', function ($isExtensible) {
+ return function isExtensible(it) {
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
+
/***/ }),
-/* 69 */
+/* 68 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(9);
- $export($export.S + $export.F, 'Object', {assign: __webpack_require__(70)});
+ $export($export.S + $export.F, 'Object', { assign: __webpack_require__(69) });
+
/***/ }),
-/* 70 */
+/* 69 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
- var getKeys = __webpack_require__(31)
- , gOPS = __webpack_require__(44)
- , pIE = __webpack_require__(45)
- , toObject = __webpack_require__(59)
- , IObject = __webpack_require__(34)
- , $assign = Object.assign;
+ var getKeys = __webpack_require__(31);
+ var gOPS = __webpack_require__(43);
+ var pIE = __webpack_require__(44);
+ var toObject = __webpack_require__(58);
+ var IObject = __webpack_require__(34);
+ var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
- module.exports = !$assign || __webpack_require__(8)(function(){
- var A = {}
- , B = {}
- , S = Symbol()
- , K = 'abcdefghijklmnopqrst';
+ module.exports = !$assign || __webpack_require__(8)(function () {
+ var A = {};
+ var B = {};
+ // eslint-disable-next-line no-undef
+ var S = Symbol();
+ var K = 'abcdefghijklmnopqrst';
A[S] = 7;
- K.split('').forEach(function(k){ B[k] = k; });
+ K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
- }) ? function assign(target, source){ // eslint-disable-line no-unused-vars
- var T = toObject(target)
- , aLen = arguments.length
- , index = 1
- , getSymbols = gOPS.f
- , isEnum = pIE.f;
- while(aLen > index){
- var S = IObject(arguments[index++])
- , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
- , length = keys.length
- , j = 0
- , key;
- while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
+ }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
+ var T = toObject(target);
+ var aLen = arguments.length;
+ var index = 1;
+ var getSymbols = gOPS.f;
+ var isEnum = pIE.f;
+ while (aLen > index) {
+ var S = IObject(arguments[index++]);
+ var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
+ var length = keys.length;
+ var j = 0;
+ var key;
+ while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
+
/***/ }),
-/* 71 */
+/* 70 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(9);
- $export($export.S, 'Object', {is: __webpack_require__(72)});
+ $export($export.S, 'Object', { is: __webpack_require__(71) });
+
/***/ }),
-/* 72 */
+/* 71 */
/***/ (function(module, exports) {
// 7.2.9 SameValue(x, y)
- module.exports = Object.is || function is(x, y){
+ module.exports = Object.is || function is(x, y) {
+ // eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
+
/***/ }),
-/* 73 */
+/* 72 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(9);
- $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(74).set});
+ $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(73).set });
+
/***/ }),
-/* 74 */
+/* 73 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
- var isObject = __webpack_require__(14)
- , anObject = __webpack_require__(13);
- var check = function(O, proto){
+ var isObject = __webpack_require__(14);
+ var anObject = __webpack_require__(13);
+ var check = function (O, proto) {
anObject(O);
- if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
+ if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
- function(test, buggy, set){
+ function (test, buggy, set) {
try {
- set = __webpack_require__(21)(Function.call, __webpack_require__(52).f(Object.prototype, '__proto__').set, 2);
+ set = __webpack_require__(21)(Function.call, __webpack_require__(51).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
- } catch(e){ buggy = true; }
- return function setPrototypeOf(O, proto){
+ } catch (e) { buggy = true; }
+ return function setPrototypeOf(O, proto) {
check(O, proto);
- if(buggy)O.__proto__ = proto;
+ if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
@@ -1733,39 +1817,41 @@ return /******/ (function(modules) { // webpackBootstrap
check: check
};
+
/***/ }),
-/* 75 */
+/* 74 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
- var classof = __webpack_require__(76)
- , test = {};
+ var classof = __webpack_require__(75);
+ var test = {};
test[__webpack_require__(26)('toStringTag')] = 'z';
- if(test + '' != '[object z]'){
- __webpack_require__(19)(Object.prototype, 'toString', function toString(){
+ if (test + '' != '[object z]') {
+ __webpack_require__(19)(Object.prototype, 'toString', function toString() {
return '[object ' + classof(this) + ']';
}, true);
}
+
/***/ }),
-/* 76 */
+/* 75 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
- var cof = __webpack_require__(35)
- , TAG = __webpack_require__(26)('toStringTag')
- // ES3 wrong here
- , ARG = cof(function(){ return arguments; }()) == 'Arguments';
+ var cof = __webpack_require__(35);
+ var TAG = __webpack_require__(26)('toStringTag');
+ // ES3 wrong here
+ var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
- var tryGet = function(it, key){
+ var tryGet = function (it, key) {
try {
return it[key];
- } catch(e){ /* empty */ }
+ } catch (e) { /* empty */ }
};
- module.exports = function(it){
+ module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
@@ -1776,52 +1862,56 @@ return /******/ (function(modules) { // webpackBootstrap
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
+
/***/ }),
-/* 77 */
+/* 76 */
/***/ (function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(9);
- $export($export.P, 'Function', {bind: __webpack_require__(78)});
+ $export($export.P, 'Function', { bind: __webpack_require__(77) });
+
/***/ }),
-/* 78 */
+/* 77 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var aFunction = __webpack_require__(22)
- , isObject = __webpack_require__(14)
- , invoke = __webpack_require__(79)
- , arraySlice = [].slice
- , factories = {};
-
- var construct = function(F, len, args){
- if(!(len in factories)){
- for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
+ var aFunction = __webpack_require__(22);
+ var isObject = __webpack_require__(14);
+ var invoke = __webpack_require__(78);
+ var arraySlice = [].slice;
+ var factories = {};
+
+ var construct = function (F, len, args) {
+ if (!(len in factories)) {
+ for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
+ // eslint-disable-next-line no-new-func
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
- module.exports = Function.bind || function bind(that /*, args... */){
- var fn = aFunction(this)
- , partArgs = arraySlice.call(arguments, 1);
- var bound = function(/* args... */){
+ module.exports = Function.bind || function bind(that /* , ...args */) {
+ var fn = aFunction(this);
+ var partArgs = arraySlice.call(arguments, 1);
+ var bound = function (/* args... */) {
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
- if(isObject(fn.prototype))bound.prototype = fn.prototype;
+ if (isObject(fn.prototype)) bound.prototype = fn.prototype;
return bound;
};
+
/***/ }),
-/* 79 */
+/* 78 */
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
- module.exports = function(fn, args, that){
+ module.exports = function (fn, args, that) {
var un = that === undefined;
- switch(args.length){
+ switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
@@ -1832,210 +1922,210 @@ return /******/ (function(modules) { // webpackBootstrap
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
- } return fn.apply(that, args);
+ } return fn.apply(that, args);
};
+
/***/ }),
-/* 80 */
+/* 79 */
/***/ (function(module, exports, __webpack_require__) {
- var dP = __webpack_require__(12).f
- , createDesc = __webpack_require__(18)
- , has = __webpack_require__(6)
- , FProto = Function.prototype
- , nameRE = /^\s*function ([^ (]*)/
- , NAME = 'name';
-
- var isExtensible = Object.isExtensible || function(){
- return true;
- };
+ var dP = __webpack_require__(12).f;
+ var FProto = Function.prototype;
+ var nameRE = /^\s*function ([^ (]*)/;
+ var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || __webpack_require__(7) && dP(FProto, NAME, {
configurable: true,
- get: function(){
+ get: function () {
try {
- var that = this
- , name = ('' + that).match(nameRE)[1];
- has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
- return name;
- } catch(e){
+ return ('' + this).match(nameRE)[1];
+ } catch (e) {
return '';
}
}
});
+
/***/ }),
-/* 81 */
+/* 80 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var isObject = __webpack_require__(14)
- , getPrototypeOf = __webpack_require__(60)
- , HAS_INSTANCE = __webpack_require__(26)('hasInstance')
- , FunctionProto = Function.prototype;
+ var isObject = __webpack_require__(14);
+ var getPrototypeOf = __webpack_require__(59);
+ var HAS_INSTANCE = __webpack_require__(26)('hasInstance');
+ var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
- if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(12).f(FunctionProto, HAS_INSTANCE, {value: function(O){
- if(typeof this != 'function' || !isObject(O))return false;
- if(!isObject(this.prototype))return O instanceof this;
+ if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(12).f(FunctionProto, HAS_INSTANCE, { value: function (O) {
+ if (typeof this != 'function' || !isObject(O)) return false;
+ if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
- while(O = getPrototypeOf(O))if(this.prototype === O)return true;
+ while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
- }});
+ } });
+
/***/ }),
-/* 82 */
+/* 81 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , $parseInt = __webpack_require__(83);
+ var $export = __webpack_require__(9);
+ var $parseInt = __webpack_require__(82);
// 18.2.5 parseInt(string, radix)
- $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
+ $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt });
+
/***/ }),
-/* 83 */
+/* 82 */
/***/ (function(module, exports, __webpack_require__) {
- var $parseInt = __webpack_require__(5).parseInt
- , $trim = __webpack_require__(84).trim
- , ws = __webpack_require__(85)
- , hex = /^[\-+]?0[xX]/;
+ var $parseInt = __webpack_require__(5).parseInt;
+ var $trim = __webpack_require__(83).trim;
+ var ws = __webpack_require__(84);
+ var hex = /^[-+]?0[xX]/;
- module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
+ module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) {
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
+
/***/ }),
-/* 84 */
+/* 83 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , defined = __webpack_require__(36)
- , fails = __webpack_require__(8)
- , spaces = __webpack_require__(85)
- , space = '[' + spaces + ']'
- , non = '\u200b\u0085'
- , ltrim = RegExp('^' + space + space + '*')
- , rtrim = RegExp(space + space + '*$');
-
- var exporter = function(KEY, exec, ALIAS){
- var exp = {};
- var FORCE = fails(function(){
+ var $export = __webpack_require__(9);
+ var defined = __webpack_require__(36);
+ var fails = __webpack_require__(8);
+ var spaces = __webpack_require__(84);
+ var space = '[' + spaces + ']';
+ var non = '\u200b\u0085';
+ var ltrim = RegExp('^' + space + space + '*');
+ var rtrim = RegExp(space + space + '*$');
+
+ var exporter = function (KEY, exec, ALIAS) {
+ var exp = {};
+ var FORCE = fails(function () {
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
- if(ALIAS)exp[ALIAS] = fn;
+ if (ALIAS) exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
- var trim = exporter.trim = function(string, TYPE){
+ var trim = exporter.trim = function (string, TYPE) {
string = String(defined(string));
- if(TYPE & 1)string = string.replace(ltrim, '');
- if(TYPE & 2)string = string.replace(rtrim, '');
+ if (TYPE & 1) string = string.replace(ltrim, '');
+ if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
+
/***/ }),
-/* 85 */
+/* 84 */
/***/ (function(module, exports) {
module.exports = '\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';
+
/***/ }),
-/* 86 */
+/* 85 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , $parseFloat = __webpack_require__(87);
+ var $export = __webpack_require__(9);
+ var $parseFloat = __webpack_require__(86);
// 18.2.4 parseFloat(string)
- $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
+ $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat });
+
/***/ }),
-/* 87 */
+/* 86 */
/***/ (function(module, exports, __webpack_require__) {
- var $parseFloat = __webpack_require__(5).parseFloat
- , $trim = __webpack_require__(84).trim;
+ var $parseFloat = __webpack_require__(5).parseFloat;
+ var $trim = __webpack_require__(83).trim;
- module.exports = 1 / $parseFloat(__webpack_require__(85) + '-0') !== -Infinity ? function parseFloat(str){
- var string = $trim(String(str), 3)
- , result = $parseFloat(string);
+ module.exports = 1 / $parseFloat(__webpack_require__(84) + '-0') !== -Infinity ? function parseFloat(str) {
+ var string = $trim(String(str), 3);
+ var result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
+
/***/ }),
-/* 88 */
+/* 87 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var global = __webpack_require__(5)
- , has = __webpack_require__(6)
- , cof = __webpack_require__(35)
- , inheritIfRequired = __webpack_require__(89)
- , toPrimitive = __webpack_require__(17)
- , fails = __webpack_require__(8)
- , gOPN = __webpack_require__(51).f
- , gOPD = __webpack_require__(52).f
- , dP = __webpack_require__(12).f
- , $trim = __webpack_require__(84).trim
- , NUMBER = 'Number'
- , $Number = global[NUMBER]
- , Base = $Number
- , proto = $Number.prototype
- // Opera ~12 has broken Object#toString
- , BROKEN_COF = cof(__webpack_require__(47)(proto)) == NUMBER
- , TRIM = 'trim' in String.prototype;
+ var global = __webpack_require__(5);
+ var has = __webpack_require__(6);
+ var cof = __webpack_require__(35);
+ var inheritIfRequired = __webpack_require__(88);
+ var toPrimitive = __webpack_require__(17);
+ var fails = __webpack_require__(8);
+ var gOPN = __webpack_require__(50).f;
+ var gOPD = __webpack_require__(51).f;
+ var dP = __webpack_require__(12).f;
+ var $trim = __webpack_require__(83).trim;
+ var NUMBER = 'Number';
+ var $Number = global[NUMBER];
+ var Base = $Number;
+ var proto = $Number.prototype;
+ // Opera ~12 has broken Object#toString
+ var BROKEN_COF = cof(__webpack_require__(46)(proto)) == NUMBER;
+ var TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
- var toNumber = function(argument){
+ var toNumber = function (argument) {
var it = toPrimitive(argument, false);
- if(typeof it == 'string' && it.length > 2){
+ if (typeof it == 'string' && it.length > 2) {
it = TRIM ? it.trim() : $trim(it, 3);
- var first = it.charCodeAt(0)
- , third, radix, maxCode;
- if(first === 43 || first === 45){
+ var first = it.charCodeAt(0);
+ var third, radix, maxCode;
+ if (first === 43 || first === 45) {
third = it.charCodeAt(2);
- if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
- } else if(first === 48){
- switch(it.charCodeAt(1)){
- case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
- case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
- default : return +it;
+ if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
+ } else if (first === 48) {
+ switch (it.charCodeAt(1)) {
+ case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
+ case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
+ default: return +it;
}
- for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
+ for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) {
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
- if(code < 48 || code > maxCode)return NaN;
+ if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
- if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
- $Number = function Number(value){
- var it = arguments.length < 1 ? 0 : value
- , that = this;
+ if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) {
+ $Number = function Number(value) {
+ var it = arguments.length < 1 ? 0 : value;
+ var that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
- && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
+ && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
- for(var keys = __webpack_require__(7) ? gOPN(Base) : (
+ for (var keys = __webpack_require__(7) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
- ).split(','), j = 0, key; keys.length > j; j++){
- if(has(Base, key = keys[j]) && !has($Number, key)){
+ ).split(','), j = 0, key; keys.length > j; j++) {
+ if (has(Base, key = keys[j]) && !has($Number, key)) {
dP($Number, key, gOPD(Base, key));
}
}
@@ -2044,74 +2134,77 @@ return /******/ (function(modules) { // webpackBootstrap
__webpack_require__(19)(global, NUMBER, $Number);
}
+
/***/ }),
-/* 89 */
+/* 88 */
/***/ (function(module, exports, __webpack_require__) {
- var isObject = __webpack_require__(14)
- , setPrototypeOf = __webpack_require__(74).set;
- module.exports = function(that, target, C){
- var P, S = target.constructor;
- if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
+ var isObject = __webpack_require__(14);
+ var setPrototypeOf = __webpack_require__(73).set;
+ module.exports = function (that, target, C) {
+ var S = target.constructor;
+ var P;
+ if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
setPrototypeOf(that, P);
} return that;
};
+
/***/ }),
-/* 90 */
+/* 89 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toInteger = __webpack_require__(39)
- , aNumberValue = __webpack_require__(91)
- , repeat = __webpack_require__(92)
- , $toFixed = 1..toFixed
- , floor = Math.floor
- , data = [0, 0, 0, 0, 0, 0]
- , ERROR = 'Number.toFixed: incorrect invocation!'
- , ZERO = '0';
-
- var multiply = function(n, c){
- var i = -1
- , c2 = c;
- while(++i < 6){
+ var $export = __webpack_require__(9);
+ var toInteger = __webpack_require__(39);
+ var aNumberValue = __webpack_require__(90);
+ var repeat = __webpack_require__(91);
+ var $toFixed = 1.0.toFixed;
+ var floor = Math.floor;
+ var data = [0, 0, 0, 0, 0, 0];
+ var ERROR = 'Number.toFixed: incorrect invocation!';
+ var ZERO = '0';
+
+ var multiply = function (n, c) {
+ var i = -1;
+ var c2 = c;
+ while (++i < 6) {
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
- var divide = function(n){
- var i = 6
- , c = 0;
- while(--i >= 0){
+ var divide = function (n) {
+ var i = 6;
+ var c = 0;
+ while (--i >= 0) {
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
- var numToString = function(){
- var i = 6
- , s = '';
- while(--i >= 0){
- if(s !== '' || i === 0 || data[i] !== 0){
+ var numToString = function () {
+ var i = 6;
+ var s = '';
+ while (--i >= 0) {
+ if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
- var pow = function(x, n, acc){
+ var pow = function (x, n, acc) {
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
- var log = function(x){
- var n = 0
- , x2 = x;
- while(x2 >= 4096){
+ var log = function (x) {
+ var n = 0;
+ var x2 = x;
+ while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
- while(x2 >= 2){
- n += 1;
+ while (x2 >= 2) {
+ n += 1;
x2 /= 2;
} return n;
};
@@ -2120,39 +2213,40 @@ return /******/ (function(modules) { // webpackBootstrap
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
- 1000000000000000128..toFixed(0) !== '1000000000000000128'
- ) || !__webpack_require__(8)(function(){
+ 1000000000000000128.0.toFixed(0) !== '1000000000000000128'
+ ) || !__webpack_require__(8)(function () {
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
- toFixed: function toFixed(fractionDigits){
- var x = aNumberValue(this, ERROR)
- , f = toInteger(fractionDigits)
- , s = ''
- , m = ZERO
- , e, z, j, k;
- if(f < 0 || f > 20)throw RangeError(ERROR);
- if(x != x)return 'NaN';
- if(x <= -1e21 || x >= 1e21)return String(x);
- if(x < 0){
+ toFixed: function toFixed(fractionDigits) {
+ var x = aNumberValue(this, ERROR);
+ var f = toInteger(fractionDigits);
+ var s = '';
+ var m = ZERO;
+ var e, z, j, k;
+ if (f < 0 || f > 20) throw RangeError(ERROR);
+ // eslint-disable-next-line no-self-compare
+ if (x != x) return 'NaN';
+ if (x <= -1e21 || x >= 1e21) return String(x);
+ if (x < 0) {
s = '-';
x = -x;
}
- if(x > 1e-21){
+ if (x > 1e-21) {
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
- if(e > 0){
+ if (e > 0) {
multiply(0, z);
j = f;
- while(j >= 7){
+ while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
- while(j >= 23){
+ while (j >= 23) {
divide(1 << 23);
j -= 23;
}
@@ -2166,7 +2260,7 @@ return /******/ (function(modules) { // webpackBootstrap
m = numToString() + repeat.call(ZERO, f);
}
}
- if(f > 0){
+ if (f > 0) {
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
@@ -2175,287 +2269,312 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
+
/***/ }),
-/* 91 */
+/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var cof = __webpack_require__(35);
- module.exports = function(it, msg){
- if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
+ module.exports = function (it, msg) {
+ if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg);
return +it;
};
+
/***/ }),
-/* 92 */
+/* 91 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var toInteger = __webpack_require__(39)
- , defined = __webpack_require__(36);
-
- module.exports = function repeat(count){
- var str = String(defined(this))
- , res = ''
- , n = toInteger(count);
- if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
- for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
+ var toInteger = __webpack_require__(39);
+ var defined = __webpack_require__(36);
+
+ module.exports = function repeat(count) {
+ var str = String(defined(this));
+ var res = '';
+ var n = toInteger(count);
+ if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
+ for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
return res;
};
+
/***/ }),
-/* 93 */
+/* 92 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $fails = __webpack_require__(8)
- , aNumberValue = __webpack_require__(91)
- , $toPrecision = 1..toPrecision;
+ var $export = __webpack_require__(9);
+ var $fails = __webpack_require__(8);
+ var aNumberValue = __webpack_require__(90);
+ var $toPrecision = 1.0.toPrecision;
- $export($export.P + $export.F * ($fails(function(){
+ $export($export.P + $export.F * ($fails(function () {
// IE7-
return $toPrecision.call(1, undefined) !== '1';
- }) || !$fails(function(){
+ }) || !$fails(function () {
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
- toPrecision: function toPrecision(precision){
+ toPrecision: function toPrecision(precision) {
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
- return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
+ return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
+
/***/ }),
-/* 94 */
+/* 93 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(9);
- $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
+ $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });
+
/***/ }),
-/* 95 */
+/* 94 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
- var $export = __webpack_require__(9)
- , _isFinite = __webpack_require__(5).isFinite;
+ var $export = __webpack_require__(9);
+ var _isFinite = __webpack_require__(5).isFinite;
$export($export.S, 'Number', {
- isFinite: function isFinite(it){
+ isFinite: function isFinite(it) {
return typeof it == 'number' && _isFinite(it);
}
});
+
/***/ }),
-/* 96 */
+/* 95 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(9);
- $export($export.S, 'Number', {isInteger: __webpack_require__(97)});
+ $export($export.S, 'Number', { isInteger: __webpack_require__(96) });
+
/***/ }),
-/* 97 */
+/* 96 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
- var isObject = __webpack_require__(14)
- , floor = Math.floor;
- module.exports = function isInteger(it){
+ var isObject = __webpack_require__(14);
+ var floor = Math.floor;
+ module.exports = function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
+
/***/ }),
-/* 98 */
+/* 97 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(9);
$export($export.S, 'Number', {
- isNaN: function isNaN(number){
+ isNaN: function isNaN(number) {
+ // eslint-disable-next-line no-self-compare
return number != number;
}
});
+
/***/ }),
-/* 99 */
+/* 98 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
- var $export = __webpack_require__(9)
- , isInteger = __webpack_require__(97)
- , abs = Math.abs;
+ var $export = __webpack_require__(9);
+ var isInteger = __webpack_require__(96);
+ var abs = Math.abs;
$export($export.S, 'Number', {
- isSafeInteger: function isSafeInteger(number){
+ isSafeInteger: function isSafeInteger(number) {
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
+
/***/ }),
-/* 100 */
+/* 99 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(9);
- $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
+ $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });
+
/***/ }),
-/* 101 */
+/* 100 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(9);
- $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
+ $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });
+
/***/ }),
-/* 102 */
+/* 101 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , $parseFloat = __webpack_require__(87);
+ var $export = __webpack_require__(9);
+ var $parseFloat = __webpack_require__(86);
// 20.1.2.12 Number.parseFloat(string)
- $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
+ $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat });
+
/***/ }),
-/* 103 */
+/* 102 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , $parseInt = __webpack_require__(83);
+ var $export = __webpack_require__(9);
+ var $parseInt = __webpack_require__(82);
// 20.1.2.13 Number.parseInt(string, radix)
- $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
+ $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt });
+
/***/ }),
-/* 104 */
+/* 103 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
- var $export = __webpack_require__(9)
- , log1p = __webpack_require__(105)
- , sqrt = Math.sqrt
- , $acosh = Math.acosh;
+ var $export = __webpack_require__(9);
+ var log1p = __webpack_require__(104);
+ var sqrt = Math.sqrt;
+ var $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
- // Tor Browser bug: Math.acosh(Infinity) -> NaN
+ // Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
- acosh: function acosh(x){
+ acosh: function acosh(x) {
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
+
/***/ }),
-/* 105 */
+/* 104 */
/***/ (function(module, exports) {
// 20.2.2.20 Math.log1p(x)
- module.exports = Math.log1p || function log1p(x){
+ module.exports = Math.log1p || function log1p(x) {
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
+
/***/ }),
-/* 106 */
+/* 105 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
- var $export = __webpack_require__(9)
- , $asinh = Math.asinh;
+ var $export = __webpack_require__(9);
+ var $asinh = Math.asinh;
- function asinh(x){
+ function asinh(x) {
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
- // Tor Browser bug: Math.asinh(0) -> -0
- $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
+ // Tor Browser bug: Math.asinh(0) -> -0
+ $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh });
+
/***/ }),
-/* 107 */
+/* 106 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
- var $export = __webpack_require__(9)
- , $atanh = Math.atanh;
+ var $export = __webpack_require__(9);
+ var $atanh = Math.atanh;
- // Tor Browser bug: Math.atanh(-0) -> 0
+ // Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
- atanh: function atanh(x){
+ atanh: function atanh(x) {
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
+
/***/ }),
-/* 108 */
+/* 107 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
- var $export = __webpack_require__(9)
- , sign = __webpack_require__(109);
+ var $export = __webpack_require__(9);
+ var sign = __webpack_require__(108);
$export($export.S, 'Math', {
- cbrt: function cbrt(x){
+ cbrt: function cbrt(x) {
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
+
/***/ }),
-/* 109 */
+/* 108 */
/***/ (function(module, exports) {
// 20.2.2.28 Math.sign(x)
- module.exports = Math.sign || function sign(x){
+ module.exports = Math.sign || function sign(x) {
+ // eslint-disable-next-line no-self-compare
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
+
/***/ }),
-/* 110 */
+/* 109 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(9);
$export($export.S, 'Math', {
- clz32: function clz32(x){
+ clz32: function clz32(x) {
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
+
/***/ }),
-/* 111 */
+/* 110 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
- var $export = __webpack_require__(9)
- , exp = Math.exp;
+ var $export = __webpack_require__(9);
+ var exp = Math.exp;
$export($export.S, 'Math', {
- cosh: function cosh(x){
+ cosh: function cosh(x) {
return (exp(x = +x) + exp(-x)) / 2;
}
});
+
/***/ }),
-/* 112 */
+/* 111 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
- var $export = __webpack_require__(9)
- , $expm1 = __webpack_require__(113);
+ var $export = __webpack_require__(9);
+ var $expm1 = __webpack_require__(112);
- $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
+ $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 });
+
/***/ }),
-/* 113 */
+/* 112 */
/***/ (function(module, exports) {
// 20.2.2.14 Math.expm1(x)
@@ -2465,64 +2584,73 @@ return /******/ (function(modules) { // webpackBootstrap
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
- ) ? function expm1(x){
+ ) ? function expm1(x) {
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
+
+/***/ }),
+/* 113 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // 20.2.2.16 Math.fround(x)
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', { fround: __webpack_require__(114) });
+
+
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
- var $export = __webpack_require__(9)
- , sign = __webpack_require__(109)
- , pow = Math.pow
- , EPSILON = pow(2, -52)
- , EPSILON32 = pow(2, -23)
- , MAX32 = pow(2, 127) * (2 - EPSILON32)
- , MIN32 = pow(2, -126);
-
- var roundTiesToEven = function(n){
+ var sign = __webpack_require__(108);
+ var pow = Math.pow;
+ var EPSILON = pow(2, -52);
+ var EPSILON32 = pow(2, -23);
+ var MAX32 = pow(2, 127) * (2 - EPSILON32);
+ var MIN32 = pow(2, -126);
+
+ var roundTiesToEven = function (n) {
return n + 1 / EPSILON - 1 / EPSILON;
};
-
- $export($export.S, 'Math', {
- fround: function fround(x){
- var $abs = Math.abs(x)
- , $sign = sign(x)
- , a, result;
- if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
- a = (1 + EPSILON32 / EPSILON) * $abs;
- result = a - (a - $abs);
- if(result > MAX32 || result != result)return $sign * Infinity;
- return $sign * result;
- }
- });
+ module.exports = Math.fround || function fround(x) {
+ var $abs = Math.abs(x);
+ var $sign = sign(x);
+ var a, result;
+ if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
+ a = (1 + EPSILON32 / EPSILON) * $abs;
+ result = a - (a - $abs);
+ // eslint-disable-next-line no-self-compare
+ if (result > MAX32 || result != result) return $sign * Infinity;
+ return $sign * result;
+ };
+
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
- var $export = __webpack_require__(9)
- , abs = Math.abs;
+ var $export = __webpack_require__(9);
+ var abs = Math.abs;
$export($export.S, 'Math', {
- hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
- var sum = 0
- , i = 0
- , aLen = arguments.length
- , larg = 0
- , arg, div;
- while(i < aLen){
+ hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars
+ var sum = 0;
+ var i = 0;
+ var aLen = arguments.length;
+ var larg = 0;
+ var arg, div;
+ while (i < aLen) {
arg = abs(arguments[i++]);
- if(larg < arg){
- div = larg / arg;
- sum = sum * div * div + 1;
+ if (larg < arg) {
+ div = larg / arg;
+ sum = sum * div * div + 1;
larg = arg;
- } else if(arg > 0){
- div = arg / larg;
+ } else if (arg > 0) {
+ div = arg / larg;
sum += div * div;
} else sum += arg;
}
@@ -2530,28 +2658,30 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
+
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
- var $export = __webpack_require__(9)
- , $imul = Math.imul;
+ var $export = __webpack_require__(9);
+ var $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
- $export($export.S + $export.F * __webpack_require__(8)(function(){
+ $export($export.S + $export.F * __webpack_require__(8)(function () {
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
- imul: function imul(x, y){
- var UINT16 = 0xffff
- , xn = +x
- , yn = +y
- , xl = UINT16 & xn
- , yl = UINT16 & yn;
+ imul: function imul(x, y) {
+ var UINT16 = 0xffff;
+ var xn = +x;
+ var yn = +y;
+ var xl = UINT16 & xn;
+ var yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
+
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
@@ -2560,11 +2690,12 @@ return /******/ (function(modules) { // webpackBootstrap
var $export = __webpack_require__(9);
$export($export.S, 'Math', {
- log10: function log10(x){
- return Math.log(x) / Math.LN10;
+ log10: function log10(x) {
+ return Math.log(x) * Math.LOG10E;
}
});
+
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
@@ -2572,7 +2703,8 @@ return /******/ (function(modules) { // webpackBootstrap
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(9);
- $export($export.S, 'Math', {log1p: __webpack_require__(105)});
+ $export($export.S, 'Math', { log1p: __webpack_require__(104) });
+
/***/ }),
/* 119 */
@@ -2582,11 +2714,12 @@ return /******/ (function(modules) { // webpackBootstrap
var $export = __webpack_require__(9);
$export($export.S, 'Math', {
- log2: function log2(x){
+ log2: function log2(x) {
return Math.log(x) / Math.LN2;
}
});
+
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
@@ -2594,45 +2727,48 @@ return /******/ (function(modules) { // webpackBootstrap
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(9);
- $export($export.S, 'Math', {sign: __webpack_require__(109)});
+ $export($export.S, 'Math', { sign: __webpack_require__(108) });
+
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
- var $export = __webpack_require__(9)
- , expm1 = __webpack_require__(113)
- , exp = Math.exp;
+ var $export = __webpack_require__(9);
+ var expm1 = __webpack_require__(112);
+ var exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
- $export($export.S + $export.F * __webpack_require__(8)(function(){
+ $export($export.S + $export.F * __webpack_require__(8)(function () {
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
- sinh: function sinh(x){
+ sinh: function sinh(x) {
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
+
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
- var $export = __webpack_require__(9)
- , expm1 = __webpack_require__(113)
- , exp = Math.exp;
+ var $export = __webpack_require__(9);
+ var expm1 = __webpack_require__(112);
+ var exp = Math.exp;
$export($export.S, 'Math', {
- tanh: function tanh(x){
- var a = expm1(x = +x)
- , b = expm1(-x);
+ tanh: function tanh(x) {
+ var a = expm1(x = +x);
+ var b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
+
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
@@ -2641,31 +2777,32 @@ return /******/ (function(modules) { // webpackBootstrap
var $export = __webpack_require__(9);
$export($export.S, 'Math', {
- trunc: function trunc(it){
+ trunc: function trunc(it) {
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
+
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , toIndex = __webpack_require__(40)
- , fromCharCode = String.fromCharCode
- , $fromCodePoint = String.fromCodePoint;
+ var $export = __webpack_require__(9);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var fromCharCode = String.fromCharCode;
+ var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
- fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
- var res = []
- , aLen = arguments.length
- , i = 0
- , code;
- while(aLen > i){
+ fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
+ var res = [];
+ var aLen = arguments.length;
+ var i = 0;
+ var code;
+ while (aLen > i) {
code = +arguments[i++];
- if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
+ if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
@@ -2674,78 +2811,82 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
+
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , toIObject = __webpack_require__(33)
- , toLength = __webpack_require__(38);
+ var $export = __webpack_require__(9);
+ var toIObject = __webpack_require__(33);
+ var toLength = __webpack_require__(38);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
- raw: function raw(callSite){
- var tpl = toIObject(callSite.raw)
- , len = toLength(tpl.length)
- , aLen = arguments.length
- , res = []
- , i = 0;
- while(len > i){
+ raw: function raw(callSite) {
+ var tpl = toIObject(callSite.raw);
+ var len = toLength(tpl.length);
+ var aLen = arguments.length;
+ var res = [];
+ var i = 0;
+ while (len > i) {
res.push(String(tpl[i++]));
- if(i < aLen)res.push(String(arguments[i]));
+ if (i < aLen) res.push(String(arguments[i]));
} return res.join('');
}
});
+
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
- __webpack_require__(84)('trim', function($trim){
- return function trim(){
+ __webpack_require__(83)('trim', function ($trim) {
+ return function trim() {
return $trim(this, 3);
};
});
+
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $at = __webpack_require__(128)(true);
+ var $at = __webpack_require__(128)(true);
// 21.1.3.27 String.prototype[@@iterator]()
- __webpack_require__(129)(String, 'String', function(iterated){
+ __webpack_require__(129)(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
- }, function(){
- var O = this._t
- , index = this._i
- , point;
- if(index >= O.length)return {value: undefined, done: true};
+ }, function () {
+ var O = this._t;
+ var index = this._i;
+ var point;
+ if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
- return {value: point, done: false};
+ return { value: point, done: false };
});
+
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
- var toInteger = __webpack_require__(39)
- , defined = __webpack_require__(36);
+ var toInteger = __webpack_require__(39);
+ var defined = __webpack_require__(36);
// true -> String#at
// false -> String#codePointAt
- module.exports = function(TO_STRING){
- return function(that, pos){
- var s = String(defined(that))
- , i = toInteger(pos)
- , l = s.length
- , a, b;
- if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
+ module.exports = function (TO_STRING) {
+ return function (that, pos) {
+ var s = String(defined(that));
+ var i = toInteger(pos);
+ var l = s.length;
+ var a, b;
+ if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
@@ -2753,204 +2894,214 @@ return /******/ (function(modules) { // webpackBootstrap
};
};
+
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var LIBRARY = __webpack_require__(29)
- , $export = __webpack_require__(9)
- , redefine = __webpack_require__(19)
- , hide = __webpack_require__(11)
- , has = __webpack_require__(6)
- , Iterators = __webpack_require__(130)
- , $iterCreate = __webpack_require__(131)
- , setToStringTag = __webpack_require__(25)
- , getPrototypeOf = __webpack_require__(60)
- , ITERATOR = __webpack_require__(26)('iterator')
- , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
- , FF_ITERATOR = '@@iterator'
- , KEYS = 'keys'
- , VALUES = 'values';
-
- var returnThis = function(){ return this; };
-
- module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
+ var LIBRARY = __webpack_require__(29);
+ var $export = __webpack_require__(9);
+ var redefine = __webpack_require__(19);
+ var hide = __webpack_require__(11);
+ var has = __webpack_require__(6);
+ var Iterators = __webpack_require__(130);
+ var $iterCreate = __webpack_require__(131);
+ var setToStringTag = __webpack_require__(25);
+ var getPrototypeOf = __webpack_require__(59);
+ var ITERATOR = __webpack_require__(26)('iterator');
+ var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
+ var FF_ITERATOR = '@@iterator';
+ var KEYS = 'keys';
+ var VALUES = 'values';
+
+ var returnThis = function () { return this; };
+
+ module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
- var getMethod = function(kind){
- if(!BUGGY && kind in proto)return proto[kind];
- switch(kind){
- case KEYS: return function keys(){ return new Constructor(this, kind); };
- case VALUES: return function values(){ return new Constructor(this, kind); };
- } return function entries(){ return new Constructor(this, kind); };
+ var getMethod = function (kind) {
+ if (!BUGGY && kind in proto) return proto[kind];
+ switch (kind) {
+ case KEYS: return function keys() { return new Constructor(this, kind); };
+ case VALUES: return function values() { return new Constructor(this, kind); };
+ } return function entries() { return new Constructor(this, kind); };
};
- var TAG = NAME + ' Iterator'
- , DEF_VALUES = DEFAULT == VALUES
- , VALUES_BUG = false
- , proto = Base.prototype
- , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
- , $default = $native || getMethod(DEFAULT)
- , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
- , $anyNative = NAME == 'Array' ? proto.entries || $native : $native
- , methods, key, IteratorPrototype;
+ var TAG = NAME + ' Iterator';
+ var DEF_VALUES = DEFAULT == VALUES;
+ var VALUES_BUG = false;
+ var proto = Base.prototype;
+ var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
+ var $default = $native || getMethod(DEFAULT);
+ var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
+ var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
+ var methods, key, IteratorPrototype;
// Fix native
- if($anyNative){
- IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
- if(IteratorPrototype !== Object.prototype){
+ if ($anyNative) {
+ IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
+ if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
- if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
+ if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
- if(DEF_VALUES && $native && $native.name !== VALUES){
+ if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
- $default = function values(){ return $native.call(this); };
+ $default = function values() { return $native.call(this); };
}
// Define iterator
- if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
+ if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
- Iterators[TAG] = returnThis;
- if(DEFAULT){
+ Iterators[TAG] = returnThis;
+ if (DEFAULT) {
methods = {
- values: DEF_VALUES ? $default : getMethod(VALUES),
- keys: IS_SET ? $default : getMethod(KEYS),
+ values: DEF_VALUES ? $default : getMethod(VALUES),
+ keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
- if(FORCED)for(key in methods){
- if(!(key in proto))redefine(proto, key, methods[key]);
+ if (FORCED) for (key in methods) {
+ if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
+
/***/ }),
/* 130 */
/***/ (function(module, exports) {
module.exports = {};
+
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var create = __webpack_require__(47)
- , descriptor = __webpack_require__(18)
- , setToStringTag = __webpack_require__(25)
- , IteratorPrototype = {};
+ var create = __webpack_require__(46);
+ var descriptor = __webpack_require__(18);
+ var setToStringTag = __webpack_require__(25);
+ var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
- __webpack_require__(11)(IteratorPrototype, __webpack_require__(26)('iterator'), function(){ return this; });
+ __webpack_require__(11)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; });
- module.exports = function(Constructor, NAME, next){
- Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
+ module.exports = function (Constructor, NAME, next) {
+ Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
+
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $at = __webpack_require__(128)(false);
+ var $export = __webpack_require__(9);
+ var $at = __webpack_require__(128)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
- codePointAt: function codePointAt(pos){
+ codePointAt: function codePointAt(pos) {
return $at(this, pos);
}
});
+
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
- var $export = __webpack_require__(9)
- , toLength = __webpack_require__(38)
- , context = __webpack_require__(134)
- , ENDS_WITH = 'endsWith'
- , $endsWith = ''[ENDS_WITH];
+ var $export = __webpack_require__(9);
+ var toLength = __webpack_require__(38);
+ var context = __webpack_require__(134);
+ var ENDS_WITH = 'endsWith';
+ var $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(136)(ENDS_WITH), 'String', {
- endsWith: function endsWith(searchString /*, endPosition = @length */){
- var that = context(this, searchString, ENDS_WITH)
- , endPosition = arguments.length > 1 ? arguments[1] : undefined
- , len = toLength(that.length)
- , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
- , search = String(searchString);
+ endsWith: function endsWith(searchString /* , endPosition = @length */) {
+ var that = context(this, searchString, ENDS_WITH);
+ var endPosition = arguments.length > 1 ? arguments[1] : undefined;
+ var len = toLength(that.length);
+ var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
+ var search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
+
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
- var isRegExp = __webpack_require__(135)
- , defined = __webpack_require__(36);
+ var isRegExp = __webpack_require__(135);
+ var defined = __webpack_require__(36);
- module.exports = function(that, searchString, NAME){
- if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
+ module.exports = function (that, searchString, NAME) {
+ if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
+
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
- var isObject = __webpack_require__(14)
- , cof = __webpack_require__(35)
- , MATCH = __webpack_require__(26)('match');
- module.exports = function(it){
+ var isObject = __webpack_require__(14);
+ var cof = __webpack_require__(35);
+ var MATCH = __webpack_require__(26)('match');
+ module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
+
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(26)('match');
- module.exports = function(KEY){
+ module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
- } catch(e){
+ } catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
- } catch(f){ /* empty */ }
+ } catch (f) { /* empty */ }
} return true;
};
+
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
- var $export = __webpack_require__(9)
- , context = __webpack_require__(134)
- , INCLUDES = 'includes';
+ var $export = __webpack_require__(9);
+ var context = __webpack_require__(134);
+ var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(136)(INCLUDES), 'String', {
- includes: function includes(searchString /*, position = 0 */){
+ includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
+
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
@@ -2959,212 +3110,228 @@ return /******/ (function(modules) { // webpackBootstrap
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
- repeat: __webpack_require__(92)
+ repeat: __webpack_require__(91)
});
+
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
- var $export = __webpack_require__(9)
- , toLength = __webpack_require__(38)
- , context = __webpack_require__(134)
- , STARTS_WITH = 'startsWith'
- , $startsWith = ''[STARTS_WITH];
+ var $export = __webpack_require__(9);
+ var toLength = __webpack_require__(38);
+ var context = __webpack_require__(134);
+ var STARTS_WITH = 'startsWith';
+ var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(136)(STARTS_WITH), 'String', {
- startsWith: function startsWith(searchString /*, position = 0 */){
- var that = context(this, searchString, STARTS_WITH)
- , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
- , search = String(searchString);
+ startsWith: function startsWith(searchString /* , position = 0 */) {
+ var that = context(this, searchString, STARTS_WITH);
+ var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
+ var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
+
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
- __webpack_require__(141)('anchor', function(createHTML){
- return function anchor(name){
+ __webpack_require__(141)('anchor', function (createHTML) {
+ return function anchor(name) {
return createHTML(this, 'a', 'name', name);
- }
+ };
});
+
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , fails = __webpack_require__(8)
- , defined = __webpack_require__(36)
- , quot = /"/g;
+ var $export = __webpack_require__(9);
+ var fails = __webpack_require__(8);
+ var defined = __webpack_require__(36);
+ var quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
- var createHTML = function(string, tag, attribute, value) {
- var S = String(defined(string))
- , p1 = '<' + tag;
- if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
+ var createHTML = function (string, tag, attribute, value) {
+ var S = String(defined(string));
+ var p1 = '<' + tag;
+ if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '' + tag + '>';
};
- module.exports = function(NAME, exec){
+ module.exports = function (NAME, exec) {
var O = {};
O[NAME] = exec(createHTML);
- $export($export.P + $export.F * fails(function(){
+ $export($export.P + $export.F * fails(function () {
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
+
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
- __webpack_require__(141)('big', function(createHTML){
- return function big(){
+ __webpack_require__(141)('big', function (createHTML) {
+ return function big() {
return createHTML(this, 'big', '', '');
- }
+ };
});
+
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
- __webpack_require__(141)('blink', function(createHTML){
- return function blink(){
+ __webpack_require__(141)('blink', function (createHTML) {
+ return function blink() {
return createHTML(this, 'blink', '', '');
- }
+ };
});
+
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
- __webpack_require__(141)('bold', function(createHTML){
- return function bold(){
+ __webpack_require__(141)('bold', function (createHTML) {
+ return function bold() {
return createHTML(this, 'b', '', '');
- }
+ };
});
+
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
- __webpack_require__(141)('fixed', function(createHTML){
- return function fixed(){
+ __webpack_require__(141)('fixed', function (createHTML) {
+ return function fixed() {
return createHTML(this, 'tt', '', '');
- }
+ };
});
+
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
- __webpack_require__(141)('fontcolor', function(createHTML){
- return function fontcolor(color){
+ __webpack_require__(141)('fontcolor', function (createHTML) {
+ return function fontcolor(color) {
return createHTML(this, 'font', 'color', color);
- }
+ };
});
+
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
- __webpack_require__(141)('fontsize', function(createHTML){
- return function fontsize(size){
+ __webpack_require__(141)('fontsize', function (createHTML) {
+ return function fontsize(size) {
return createHTML(this, 'font', 'size', size);
- }
+ };
});
+
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
- __webpack_require__(141)('italics', function(createHTML){
- return function italics(){
+ __webpack_require__(141)('italics', function (createHTML) {
+ return function italics() {
return createHTML(this, 'i', '', '');
- }
+ };
});
+
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
- __webpack_require__(141)('link', function(createHTML){
- return function link(url){
+ __webpack_require__(141)('link', function (createHTML) {
+ return function link(url) {
return createHTML(this, 'a', 'href', url);
- }
+ };
});
+
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
- __webpack_require__(141)('small', function(createHTML){
- return function small(){
+ __webpack_require__(141)('small', function (createHTML) {
+ return function small() {
return createHTML(this, 'small', '', '');
- }
+ };
});
+
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
- __webpack_require__(141)('strike', function(createHTML){
- return function strike(){
+ __webpack_require__(141)('strike', function (createHTML) {
+ return function strike() {
return createHTML(this, 'strike', '', '');
- }
+ };
});
+
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
- __webpack_require__(141)('sub', function(createHTML){
- return function sub(){
+ __webpack_require__(141)('sub', function (createHTML) {
+ return function sub() {
return createHTML(this, 'sub', '', '');
- }
+ };
});
+
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
- __webpack_require__(141)('sup', function(createHTML){
- return function sup(){
+ __webpack_require__(141)('sup', function (createHTML) {
+ return function sup() {
return createHTML(this, 'sup', '', '');
- }
+ };
});
+
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
@@ -3172,142 +3339,164 @@ return /******/ (function(modules) { // webpackBootstrap
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(9);
- $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
+ $export($export.S, 'Date', { now: function () { return new Date().getTime(); } });
+
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , toPrimitive = __webpack_require__(17);
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var toPrimitive = __webpack_require__(17);
- $export($export.P + $export.F * __webpack_require__(8)(function(){
- return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
+ $export($export.P + $export.F * __webpack_require__(8)(function () {
+ return new Date(NaN).toJSON() !== null
+ || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1;
}), 'Date', {
- toJSON: function toJSON(key){
- var O = toObject(this)
- , pv = toPrimitive(O);
+ // eslint-disable-next-line no-unused-vars
+ toJSON: function toJSON(key) {
+ var O = toObject(this);
+ var pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
+
/***/ }),
/* 156 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
+ var $export = __webpack_require__(9);
+ var toISOString = __webpack_require__(157);
+
+ // PhantomJS / old WebKit has a broken implementations
+ $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', {
+ toISOString: toISOString
+ });
+
+
+/***/ }),
+/* 157 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
- var $export = __webpack_require__(9)
- , fails = __webpack_require__(8)
- , getTime = Date.prototype.getTime;
+ var fails = __webpack_require__(8);
+ var getTime = Date.prototype.getTime;
+ var $toISOString = Date.prototype.toISOString;
- var lz = function(num){
+ var lz = function (num) {
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
- $export($export.P + $export.F * (fails(function(){
- return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
- }) || !fails(function(){
- new Date(NaN).toISOString();
- })), 'Date', {
- toISOString: function toISOString(){
- if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
- var d = this
- , y = d.getUTCFullYear()
- , m = d.getUTCMilliseconds()
- , s = y < 0 ? '-' : y > 9999 ? '+' : '';
- return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
- '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
- 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
- ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
- }
- });
+ module.exports = (fails(function () {
+ return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
+ }) || !fails(function () {
+ $toISOString.call(new Date(NaN));
+ })) ? function toISOString() {
+ if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
+ var d = this;
+ var y = d.getUTCFullYear();
+ var m = d.getUTCMilliseconds();
+ var s = y < 0 ? '-' : y > 9999 ? '+' : '';
+ return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
+ '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
+ 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
+ ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
+ } : $toISOString;
+
/***/ }),
-/* 157 */
+/* 158 */
/***/ (function(module, exports, __webpack_require__) {
- var DateProto = Date.prototype
- , INVALID_DATE = 'Invalid Date'
- , TO_STRING = 'toString'
- , $toString = DateProto[TO_STRING]
- , getTime = DateProto.getTime;
- if(new Date(NaN) + '' != INVALID_DATE){
- __webpack_require__(19)(DateProto, TO_STRING, function toString(){
+ var DateProto = Date.prototype;
+ var INVALID_DATE = 'Invalid Date';
+ var TO_STRING = 'toString';
+ var $toString = DateProto[TO_STRING];
+ var getTime = DateProto.getTime;
+ if (new Date(NaN) + '' != INVALID_DATE) {
+ __webpack_require__(19)(DateProto, TO_STRING, function toString() {
var value = getTime.call(this);
+ // eslint-disable-next-line no-self-compare
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
+
/***/ }),
-/* 158 */
+/* 159 */
/***/ (function(module, exports, __webpack_require__) {
- var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive')
- , proto = Date.prototype;
+ var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive');
+ var proto = Date.prototype;
- if(!(TO_PRIMITIVE in proto))__webpack_require__(11)(proto, TO_PRIMITIVE, __webpack_require__(159));
+ if (!(TO_PRIMITIVE in proto)) __webpack_require__(11)(proto, TO_PRIMITIVE, __webpack_require__(160));
+
/***/ }),
-/* 159 */
+/* 160 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var anObject = __webpack_require__(13)
- , toPrimitive = __webpack_require__(17)
- , NUMBER = 'number';
+ var anObject = __webpack_require__(13);
+ var toPrimitive = __webpack_require__(17);
+ var NUMBER = 'number';
- module.exports = function(hint){
- if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
+ module.exports = function (hint) {
+ if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
+
/***/ }),
-/* 160 */
+/* 161 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(9);
- $export($export.S, 'Array', {isArray: __webpack_require__(46)});
+ $export($export.S, 'Array', { isArray: __webpack_require__(45) });
+
/***/ }),
-/* 161 */
+/* 162 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var ctx = __webpack_require__(21)
- , $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , call = __webpack_require__(162)
- , isArrayIter = __webpack_require__(163)
- , toLength = __webpack_require__(38)
- , createProperty = __webpack_require__(164)
- , getIterFn = __webpack_require__(165);
-
- $export($export.S + $export.F * !__webpack_require__(166)(function(iter){ Array.from(iter); }), 'Array', {
+ var ctx = __webpack_require__(21);
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var call = __webpack_require__(163);
+ var isArrayIter = __webpack_require__(164);
+ var toLength = __webpack_require__(38);
+ var createProperty = __webpack_require__(165);
+ var getIterFn = __webpack_require__(166);
+
+ $export($export.S + $export.F * !__webpack_require__(167)(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
- from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
- var O = toObject(arrayLike)
- , C = typeof this == 'function' ? this : Array
- , aLen = arguments.length
- , mapfn = aLen > 1 ? arguments[1] : undefined
- , mapping = mapfn !== undefined
- , index = 0
- , iterFn = getIterFn(O)
- , length, result, step, iterator;
- if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
+ from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
+ var O = toObject(arrayLike);
+ var C = typeof this == 'function' ? this : Array;
+ var aLen = arguments.length;
+ var mapfn = aLen > 1 ? arguments[1] : undefined;
+ var mapping = mapfn !== undefined;
+ var index = 0;
+ var iterFn = getIterFn(O);
+ var length, result, step, iterator;
+ if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
- if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
- for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
+ if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
+ for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
- for(result = new C(length); length > index; index++){
+ for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
@@ -3318,219 +3507,233 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 162 */
+/* 163 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(13);
- module.exports = function(iterator, fn, value, entries){
+ module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
- } catch(e){
+ } catch (e) {
var ret = iterator['return'];
- if(ret !== undefined)anObject(ret.call(iterator));
+ if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
+
/***/ }),
-/* 163 */
+/* 164 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
- var Iterators = __webpack_require__(130)
- , ITERATOR = __webpack_require__(26)('iterator')
- , ArrayProto = Array.prototype;
+ var Iterators = __webpack_require__(130);
+ var ITERATOR = __webpack_require__(26)('iterator');
+ var ArrayProto = Array.prototype;
- module.exports = function(it){
+ module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
+
/***/ }),
-/* 164 */
+/* 165 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $defineProperty = __webpack_require__(12)
- , createDesc = __webpack_require__(18);
+ var $defineProperty = __webpack_require__(12);
+ var createDesc = __webpack_require__(18);
- module.exports = function(object, index, value){
- if(index in object)$defineProperty.f(object, index, createDesc(0, value));
+ module.exports = function (object, index, value) {
+ if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
+
/***/ }),
-/* 165 */
+/* 166 */
/***/ (function(module, exports, __webpack_require__) {
- var classof = __webpack_require__(76)
- , ITERATOR = __webpack_require__(26)('iterator')
- , Iterators = __webpack_require__(130);
- module.exports = __webpack_require__(10).getIteratorMethod = function(it){
- if(it != undefined)return it[ITERATOR]
+ var classof = __webpack_require__(75);
+ var ITERATOR = __webpack_require__(26)('iterator');
+ var Iterators = __webpack_require__(130);
+ module.exports = __webpack_require__(10).getIteratorMethod = function (it) {
+ if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
+
/***/ }),
-/* 166 */
+/* 167 */
/***/ (function(module, exports, __webpack_require__) {
- var ITERATOR = __webpack_require__(26)('iterator')
- , SAFE_CLOSING = false;
+ var ITERATOR = __webpack_require__(26)('iterator');
+ var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
- riter['return'] = function(){ SAFE_CLOSING = true; };
- Array.from(riter, function(){ throw 2; });
- } catch(e){ /* empty */ }
+ riter['return'] = function () { SAFE_CLOSING = true; };
+ // eslint-disable-next-line no-throw-literal
+ Array.from(riter, function () { throw 2; });
+ } catch (e) { /* empty */ }
- module.exports = function(exec, skipClosing){
- if(!skipClosing && !SAFE_CLOSING)return false;
+ module.exports = function (exec, skipClosing) {
+ if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
- var arr = [7]
- , iter = arr[ITERATOR]();
- iter.next = function(){ return {done: safe = true}; };
- arr[ITERATOR] = function(){ return iter; };
+ var arr = [7];
+ var iter = arr[ITERATOR]();
+ iter.next = function () { return { done: safe = true }; };
+ arr[ITERATOR] = function () { return iter; };
exec(arr);
- } catch(e){ /* empty */ }
+ } catch (e) { /* empty */ }
return safe;
};
+
/***/ }),
-/* 167 */
+/* 168 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , createProperty = __webpack_require__(164);
+ var $export = __webpack_require__(9);
+ var createProperty = __webpack_require__(165);
// WebKit Array.of isn't generic
- $export($export.S + $export.F * __webpack_require__(8)(function(){
- function F(){}
+ $export($export.S + $export.F * __webpack_require__(8)(function () {
+ function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
- of: function of(/* ...args */){
- var index = 0
- , aLen = arguments.length
- , result = new (typeof this == 'function' ? this : Array)(aLen);
- while(aLen > index)createProperty(result, index, arguments[index++]);
+ of: function of(/* ...args */) {
+ var index = 0;
+ var aLen = arguments.length;
+ var result = new (typeof this == 'function' ? this : Array)(aLen);
+ while (aLen > index) createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
+
/***/ }),
-/* 168 */
+/* 169 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
- var $export = __webpack_require__(9)
- , toIObject = __webpack_require__(33)
- , arrayJoin = [].join;
+ var $export = __webpack_require__(9);
+ var toIObject = __webpack_require__(33);
+ var arrayJoin = [].join;
// fallback for not array-like strings
- $export($export.P + $export.F * (__webpack_require__(34) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', {
- join: function join(separator){
+ $export($export.P + $export.F * (__webpack_require__(34) != Object || !__webpack_require__(170)(arrayJoin)), 'Array', {
+ join: function join(separator) {
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
+
/***/ }),
-/* 169 */
+/* 170 */
/***/ (function(module, exports, __webpack_require__) {
+ 'use strict';
var fails = __webpack_require__(8);
- module.exports = function(method, arg){
- return !!method && fails(function(){
- arg ? method.call(null, function(){}, 1) : method.call(null);
+ module.exports = function (method, arg) {
+ return !!method && fails(function () {
+ // eslint-disable-next-line no-useless-call
+ arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);
});
};
+
/***/ }),
-/* 170 */
+/* 171 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , html = __webpack_require__(49)
- , cof = __webpack_require__(35)
- , toIndex = __webpack_require__(40)
- , toLength = __webpack_require__(38)
- , arraySlice = [].slice;
+ var $export = __webpack_require__(9);
+ var html = __webpack_require__(48);
+ var cof = __webpack_require__(35);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var toLength = __webpack_require__(38);
+ var arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
- $export($export.P + $export.F * __webpack_require__(8)(function(){
- if(html)arraySlice.call(html);
+ $export($export.P + $export.F * __webpack_require__(8)(function () {
+ if (html) arraySlice.call(html);
}), 'Array', {
- slice: function slice(begin, end){
- var len = toLength(this.length)
- , klass = cof(this);
+ slice: function slice(begin, end) {
+ var len = toLength(this.length);
+ var klass = cof(this);
end = end === undefined ? len : end;
- if(klass == 'Array')return arraySlice.call(this, begin, end);
- var start = toIndex(begin, len)
- , upTo = toIndex(end, len)
- , size = toLength(upTo - start)
- , cloned = Array(size)
- , i = 0;
- for(; i < size; i++)cloned[i] = klass == 'String'
+ if (klass == 'Array') return arraySlice.call(this, begin, end);
+ var start = toAbsoluteIndex(begin, len);
+ var upTo = toAbsoluteIndex(end, len);
+ var size = toLength(upTo - start);
+ var cloned = Array(size);
+ var i = 0;
+ for (; i < size; i++) cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
+
/***/ }),
-/* 171 */
+/* 172 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , aFunction = __webpack_require__(22)
- , toObject = __webpack_require__(59)
- , fails = __webpack_require__(8)
- , $sort = [].sort
- , test = [1, 2, 3];
-
- $export($export.P + $export.F * (fails(function(){
+ var $export = __webpack_require__(9);
+ var aFunction = __webpack_require__(22);
+ var toObject = __webpack_require__(58);
+ var fails = __webpack_require__(8);
+ var $sort = [].sort;
+ var test = [1, 2, 3];
+
+ $export($export.P + $export.F * (fails(function () {
// IE8-
test.sort(undefined);
- }) || !fails(function(){
+ }) || !fails(function () {
// V8 bug
test.sort(null);
// Old WebKit
- }) || !__webpack_require__(169)($sort)), 'Array', {
+ }) || !__webpack_require__(170)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
- sort: function sort(comparefn){
+ sort: function sort(comparefn) {
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
+
/***/ }),
-/* 172 */
+/* 173 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $forEach = __webpack_require__(173)(0)
- , STRICT = __webpack_require__(169)([].forEach, true);
+ var $export = __webpack_require__(9);
+ var $forEach = __webpack_require__(174)(0);
+ var STRICT = __webpack_require__(170)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
- forEach: function forEach(callbackfn /* , thisArg */){
+ forEach: function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments[1]);
}
});
+
/***/ }),
-/* 173 */
+/* 174 */
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
@@ -3540,212 +3743,222 @@ return /******/ (function(modules) { // webpackBootstrap
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
- var ctx = __webpack_require__(21)
- , IObject = __webpack_require__(34)
- , toObject = __webpack_require__(59)
- , toLength = __webpack_require__(38)
- , asc = __webpack_require__(174);
- module.exports = function(TYPE, $create){
- var IS_MAP = TYPE == 1
- , IS_FILTER = TYPE == 2
- , IS_SOME = TYPE == 3
- , IS_EVERY = TYPE == 4
- , IS_FIND_INDEX = TYPE == 6
- , NO_HOLES = TYPE == 5 || IS_FIND_INDEX
- , create = $create || asc;
- return function($this, callbackfn, that){
- var O = toObject($this)
- , self = IObject(O)
- , f = ctx(callbackfn, that, 3)
- , length = toLength(self.length)
- , index = 0
- , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
- , val, res;
- for(;length > index; index++)if(NO_HOLES || index in self){
+ var ctx = __webpack_require__(21);
+ var IObject = __webpack_require__(34);
+ var toObject = __webpack_require__(58);
+ var toLength = __webpack_require__(38);
+ var asc = __webpack_require__(175);
+ module.exports = function (TYPE, $create) {
+ var IS_MAP = TYPE == 1;
+ var IS_FILTER = TYPE == 2;
+ var IS_SOME = TYPE == 3;
+ var IS_EVERY = TYPE == 4;
+ var IS_FIND_INDEX = TYPE == 6;
+ var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
+ var create = $create || asc;
+ return function ($this, callbackfn, that) {
+ var O = toObject($this);
+ var self = IObject(O);
+ var f = ctx(callbackfn, that, 3);
+ var length = toLength(self.length);
+ var index = 0;
+ var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
+ var val, res;
+ for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
- if(TYPE){
- if(IS_MAP)result[index] = res; // map
- else if(res)switch(TYPE){
- case 3: return true; // some
- case 5: return val; // find
- case 6: return index; // findIndex
- case 2: result.push(val); // filter
- } else if(IS_EVERY)return false; // every
+ if (TYPE) {
+ if (IS_MAP) result[index] = res; // map
+ else if (res) switch (TYPE) {
+ case 3: return true; // some
+ case 5: return val; // find
+ case 6: return index; // findIndex
+ case 2: result.push(val); // filter
+ } else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
+
/***/ }),
-/* 174 */
+/* 175 */
/***/ (function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
- var speciesConstructor = __webpack_require__(175);
+ var speciesConstructor = __webpack_require__(176);
- module.exports = function(original, length){
+ module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
+
/***/ }),
-/* 175 */
+/* 176 */
/***/ (function(module, exports, __webpack_require__) {
- var isObject = __webpack_require__(14)
- , isArray = __webpack_require__(46)
- , SPECIES = __webpack_require__(26)('species');
+ var isObject = __webpack_require__(14);
+ var isArray = __webpack_require__(45);
+ var SPECIES = __webpack_require__(26)('species');
- module.exports = function(original){
+ module.exports = function (original) {
var C;
- if(isArray(original)){
+ if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
- if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
- if(isObject(C)){
+ if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
+ if (isObject(C)) {
C = C[SPECIES];
- if(C === null)C = undefined;
+ if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
+
/***/ }),
-/* 176 */
+/* 177 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $map = __webpack_require__(173)(1);
+ var $export = __webpack_require__(9);
+ var $map = __webpack_require__(174)(1);
- $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
- map: function map(callbackfn /* , thisArg */){
+ map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments[1]);
}
});
+
/***/ }),
-/* 177 */
+/* 178 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $filter = __webpack_require__(173)(2);
+ var $export = __webpack_require__(9);
+ var $filter = __webpack_require__(174)(2);
- $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
- filter: function filter(callbackfn /* , thisArg */){
+ filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments[1]);
}
});
+
/***/ }),
-/* 178 */
+/* 179 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $some = __webpack_require__(173)(3);
+ var $export = __webpack_require__(9);
+ var $some = __webpack_require__(174)(3);
- $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
- some: function some(callbackfn /* , thisArg */){
+ some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments[1]);
}
});
+
/***/ }),
-/* 179 */
+/* 180 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $every = __webpack_require__(173)(4);
+ var $export = __webpack_require__(9);
+ var $every = __webpack_require__(174)(4);
- $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
- every: function every(callbackfn /* , thisArg */){
+ every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments[1]);
}
});
+
/***/ }),
-/* 180 */
+/* 181 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $reduce = __webpack_require__(181);
+ var $export = __webpack_require__(9);
+ var $reduce = __webpack_require__(182);
- $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
- reduce: function reduce(callbackfn /* , initialValue */){
+ reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
+
/***/ }),
-/* 181 */
+/* 182 */
/***/ (function(module, exports, __webpack_require__) {
- var aFunction = __webpack_require__(22)
- , toObject = __webpack_require__(59)
- , IObject = __webpack_require__(34)
- , toLength = __webpack_require__(38);
+ var aFunction = __webpack_require__(22);
+ var toObject = __webpack_require__(58);
+ var IObject = __webpack_require__(34);
+ var toLength = __webpack_require__(38);
- module.exports = function(that, callbackfn, aLen, memo, isRight){
+ module.exports = function (that, callbackfn, aLen, memo, isRight) {
aFunction(callbackfn);
- var O = toObject(that)
- , self = IObject(O)
- , length = toLength(O.length)
- , index = isRight ? length - 1 : 0
- , i = isRight ? -1 : 1;
- if(aLen < 2)for(;;){
- if(index in self){
+ var O = toObject(that);
+ var self = IObject(O);
+ var length = toLength(O.length);
+ var index = isRight ? length - 1 : 0;
+ var i = isRight ? -1 : 1;
+ if (aLen < 2) for (;;) {
+ if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
- if(isRight ? index < 0 : length <= index){
+ if (isRight ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
- for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
+ for (;isRight ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
+
/***/ }),
-/* 182 */
+/* 183 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $reduce = __webpack_require__(181);
+ var $export = __webpack_require__(9);
+ var $reduce = __webpack_require__(182);
- $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', {
+ $export($export.P + $export.F * !__webpack_require__(170)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
- reduceRight: function reduceRight(callbackfn /* , initialValue */){
+ reduceRight: function reduceRight(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
+
/***/ }),
-/* 183 */
+/* 184 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $indexOf = __webpack_require__(37)(false)
- , $native = [].indexOf
- , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
+ var $export = __webpack_require__(9);
+ var $indexOf = __webpack_require__(37)(false);
+ var $native = [].indexOf;
+ var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
- $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', {
+ $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
- indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
+ indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
@@ -3753,209 +3966,220 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
+
/***/ }),
-/* 184 */
+/* 185 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toIObject = __webpack_require__(33)
- , toInteger = __webpack_require__(39)
- , toLength = __webpack_require__(38)
- , $native = [].lastIndexOf
- , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
-
- $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', {
+ var $export = __webpack_require__(9);
+ var toIObject = __webpack_require__(33);
+ var toInteger = __webpack_require__(39);
+ var toLength = __webpack_require__(38);
+ var $native = [].lastIndexOf;
+ var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
+
+ $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
- lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
+ lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
- if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
- var O = toIObject(this)
- , length = toLength(O.length)
- , index = length - 1;
- if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
- if(index < 0)index = length + index;
- for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
+ if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;
+ var O = toIObject(this);
+ var length = toLength(O.length);
+ var index = length - 1;
+ if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));
+ if (index < 0) index = length + index;
+ for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;
return -1;
}
});
+
/***/ }),
-/* 185 */
+/* 186 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(9);
- $export($export.P, 'Array', {copyWithin: __webpack_require__(186)});
+ $export($export.P, 'Array', { copyWithin: __webpack_require__(187) });
- __webpack_require__(187)('copyWithin');
+ __webpack_require__(188)('copyWithin');
+
/***/ }),
-/* 186 */
+/* 187 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
- var toObject = __webpack_require__(59)
- , toIndex = __webpack_require__(40)
- , toLength = __webpack_require__(38);
-
- module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
- var O = toObject(this)
- , len = toLength(O.length)
- , to = toIndex(target, len)
- , from = toIndex(start, len)
- , end = arguments.length > 2 ? arguments[2] : undefined
- , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
- , inc = 1;
- if(from < to && to < from + count){
- inc = -1;
+ var toObject = __webpack_require__(58);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var toLength = __webpack_require__(38);
+
+ module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
+ var O = toObject(this);
+ var len = toLength(O.length);
+ var to = toAbsoluteIndex(target, len);
+ var from = toAbsoluteIndex(start, len);
+ var end = arguments.length > 2 ? arguments[2] : undefined;
+ var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
+ var inc = 1;
+ if (from < to && to < from + count) {
+ inc = -1;
from += count - 1;
- to += count - 1;
+ to += count - 1;
}
- while(count-- > 0){
- if(from in O)O[to] = O[from];
+ while (count-- > 0) {
+ if (from in O) O[to] = O[from];
else delete O[to];
- to += inc;
+ to += inc;
from += inc;
} return O;
};
+
/***/ }),
-/* 187 */
+/* 188 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
- var UNSCOPABLES = __webpack_require__(26)('unscopables')
- , ArrayProto = Array.prototype;
- if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(11)(ArrayProto, UNSCOPABLES, {});
- module.exports = function(key){
+ var UNSCOPABLES = __webpack_require__(26)('unscopables');
+ var ArrayProto = Array.prototype;
+ if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(11)(ArrayProto, UNSCOPABLES, {});
+ module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
+
/***/ }),
-/* 188 */
+/* 189 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(9);
- $export($export.P, 'Array', {fill: __webpack_require__(189)});
+ $export($export.P, 'Array', { fill: __webpack_require__(190) });
- __webpack_require__(187)('fill');
+ __webpack_require__(188)('fill');
+
/***/ }),
-/* 189 */
+/* 190 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
- var toObject = __webpack_require__(59)
- , toIndex = __webpack_require__(40)
- , toLength = __webpack_require__(38);
- module.exports = function fill(value /*, start = 0, end = @length */){
- var O = toObject(this)
- , length = toLength(O.length)
- , aLen = arguments.length
- , index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
- , end = aLen > 2 ? arguments[2] : undefined
- , endPos = end === undefined ? length : toIndex(end, length);
- while(endPos > index)O[index++] = value;
+ var toObject = __webpack_require__(58);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var toLength = __webpack_require__(38);
+ module.exports = function fill(value /* , start = 0, end = @length */) {
+ var O = toObject(this);
+ var length = toLength(O.length);
+ var aLen = arguments.length;
+ var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
+ var end = aLen > 2 ? arguments[2] : undefined;
+ var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
+ while (endPos > index) O[index++] = value;
return O;
};
+
/***/ }),
-/* 190 */
+/* 191 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
- var $export = __webpack_require__(9)
- , $find = __webpack_require__(173)(5)
- , KEY = 'find'
- , forced = true;
+ var $export = __webpack_require__(9);
+ var $find = __webpack_require__(174)(5);
+ var KEY = 'find';
+ var forced = true;
// Shouldn't skip holes
- if(KEY in [])Array(1)[KEY](function(){ forced = false; });
+ if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
- find: function find(callbackfn/*, that = undefined */){
+ find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
- __webpack_require__(187)(KEY);
+ __webpack_require__(188)(KEY);
+
/***/ }),
-/* 191 */
+/* 192 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
- var $export = __webpack_require__(9)
- , $find = __webpack_require__(173)(6)
- , KEY = 'findIndex'
- , forced = true;
+ var $export = __webpack_require__(9);
+ var $find = __webpack_require__(174)(6);
+ var KEY = 'findIndex';
+ var forced = true;
// Shouldn't skip holes
- if(KEY in [])Array(1)[KEY](function(){ forced = false; });
+ if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
- findIndex: function findIndex(callbackfn/*, that = undefined */){
+ findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
- __webpack_require__(187)(KEY);
+ __webpack_require__(188)(KEY);
+
/***/ }),
-/* 192 */
+/* 193 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(193)('Array');
+ __webpack_require__(194)('Array');
+
/***/ }),
-/* 193 */
+/* 194 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var global = __webpack_require__(5)
- , dP = __webpack_require__(12)
- , DESCRIPTORS = __webpack_require__(7)
- , SPECIES = __webpack_require__(26)('species');
+ var global = __webpack_require__(5);
+ var dP = __webpack_require__(12);
+ var DESCRIPTORS = __webpack_require__(7);
+ var SPECIES = __webpack_require__(26)('species');
- module.exports = function(KEY){
+ module.exports = function (KEY) {
var C = global[KEY];
- if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
+ if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
- get: function(){ return this; }
+ get: function () { return this; }
});
};
+
/***/ }),
-/* 194 */
+/* 195 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var addToUnscopables = __webpack_require__(187)
- , step = __webpack_require__(195)
- , Iterators = __webpack_require__(130)
- , toIObject = __webpack_require__(33);
+ var addToUnscopables = __webpack_require__(188);
+ var step = __webpack_require__(196);
+ var Iterators = __webpack_require__(130);
+ var toIObject = __webpack_require__(33);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
- module.exports = __webpack_require__(129)(Array, 'Array', function(iterated, kind){
+ module.exports = __webpack_require__(129)(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
- }, function(){
- var O = this._t
- , kind = this._k
- , index = this._i++;
- if(!O || index >= O.length){
+ }, function () {
+ var O = this._t;
+ var kind = this._k;
+ var index = this._i++;
+ if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
- if(kind == 'keys' )return step(0, index);
- if(kind == 'values')return step(0, O[index]);
+ if (kind == 'keys') return step(0, index);
+ if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
@@ -3966,228 +4190,238 @@ return /******/ (function(modules) { // webpackBootstrap
addToUnscopables('values');
addToUnscopables('entries');
+
/***/ }),
-/* 195 */
+/* 196 */
/***/ (function(module, exports) {
- module.exports = function(done, value){
- return {value: value, done: !!done};
+ module.exports = function (done, value) {
+ return { value: value, done: !!done };
};
+
/***/ }),
-/* 196 */
+/* 197 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , inheritIfRequired = __webpack_require__(89)
- , dP = __webpack_require__(12).f
- , gOPN = __webpack_require__(51).f
- , isRegExp = __webpack_require__(135)
- , $flags = __webpack_require__(197)
- , $RegExp = global.RegExp
- , Base = $RegExp
- , proto = $RegExp.prototype
- , re1 = /a/g
- , re2 = /a/g
- // "new" creates a new object, old webkit buggy here
- , CORRECT_NEW = new $RegExp(re1) !== re1;
-
- if(__webpack_require__(7) && (!CORRECT_NEW || __webpack_require__(8)(function(){
+ var global = __webpack_require__(5);
+ var inheritIfRequired = __webpack_require__(88);
+ var dP = __webpack_require__(12).f;
+ var gOPN = __webpack_require__(50).f;
+ var isRegExp = __webpack_require__(135);
+ var $flags = __webpack_require__(198);
+ var $RegExp = global.RegExp;
+ var Base = $RegExp;
+ var proto = $RegExp.prototype;
+ var re1 = /a/g;
+ var re2 = /a/g;
+ // "new" creates a new object, old webkit buggy here
+ var CORRECT_NEW = new $RegExp(re1) !== re1;
+
+ if (__webpack_require__(7) && (!CORRECT_NEW || __webpack_require__(8)(function () {
re2[__webpack_require__(26)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
- }))){
- $RegExp = function RegExp(p, f){
- var tiRE = this instanceof $RegExp
- , piRE = isRegExp(p)
- , fiU = f === undefined;
+ }))) {
+ $RegExp = function RegExp(p, f) {
+ var tiRE = this instanceof $RegExp;
+ var piRE = isRegExp(p);
+ var fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
- var proxy = function(key){
+ var proxy = function (key) {
key in $RegExp || dP($RegExp, key, {
configurable: true,
- get: function(){ return Base[key]; },
- set: function(it){ Base[key] = it; }
+ get: function () { return Base[key]; },
+ set: function (it) { Base[key] = it; }
});
};
- for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
+ for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(19)(global, 'RegExp', $RegExp);
}
- __webpack_require__(193)('RegExp');
+ __webpack_require__(194)('RegExp');
+
/***/ }),
-/* 197 */
+/* 198 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(13);
- module.exports = function(){
- var that = anObject(this)
- , result = '';
- if(that.global) result += 'g';
- if(that.ignoreCase) result += 'i';
- if(that.multiline) result += 'm';
- if(that.unicode) result += 'u';
- if(that.sticky) result += 'y';
+ module.exports = function () {
+ var that = anObject(this);
+ var result = '';
+ if (that.global) result += 'g';
+ if (that.ignoreCase) result += 'i';
+ if (that.multiline) result += 'm';
+ if (that.unicode) result += 'u';
+ if (that.sticky) result += 'y';
return result;
};
+
/***/ }),
-/* 198 */
+/* 199 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- __webpack_require__(199);
- var anObject = __webpack_require__(13)
- , $flags = __webpack_require__(197)
- , DESCRIPTORS = __webpack_require__(7)
- , TO_STRING = 'toString'
- , $toString = /./[TO_STRING];
+ __webpack_require__(200);
+ var anObject = __webpack_require__(13);
+ var $flags = __webpack_require__(198);
+ var DESCRIPTORS = __webpack_require__(7);
+ var TO_STRING = 'toString';
+ var $toString = /./[TO_STRING];
- var define = function(fn){
+ var define = function (fn) {
__webpack_require__(19)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
- if(__webpack_require__(8)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
- define(function toString(){
+ if (__webpack_require__(8)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) {
+ define(function toString() {
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
- } else if($toString.name != TO_STRING){
- define(function toString(){
+ } else if ($toString.name != TO_STRING) {
+ define(function toString() {
return $toString.call(this);
});
}
+
/***/ }),
-/* 199 */
+/* 200 */
/***/ (function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
- if(__webpack_require__(7) && /./g.flags != 'g')__webpack_require__(12).f(RegExp.prototype, 'flags', {
+ if (__webpack_require__(7) && /./g.flags != 'g') __webpack_require__(12).f(RegExp.prototype, 'flags', {
configurable: true,
- get: __webpack_require__(197)
+ get: __webpack_require__(198)
});
+
/***/ }),
-/* 200 */
+/* 201 */
/***/ (function(module, exports, __webpack_require__) {
// @@match logic
- __webpack_require__(201)('match', 1, function(defined, MATCH, $match){
+ __webpack_require__(202)('match', 1, function (defined, MATCH, $match) {
// 21.1.3.11 String.prototype.match(regexp)
- return [function match(regexp){
+ return [function match(regexp) {
'use strict';
- var O = defined(this)
- , fn = regexp == undefined ? undefined : regexp[MATCH];
+ var O = defined(this);
+ var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
+
/***/ }),
-/* 201 */
+/* 202 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var hide = __webpack_require__(11)
- , redefine = __webpack_require__(19)
- , fails = __webpack_require__(8)
- , defined = __webpack_require__(36)
- , wks = __webpack_require__(26);
-
- module.exports = function(KEY, length, exec){
- var SYMBOL = wks(KEY)
- , fns = exec(defined, SYMBOL, ''[KEY])
- , strfn = fns[0]
- , rxfn = fns[1];
- if(fails(function(){
+ var hide = __webpack_require__(11);
+ var redefine = __webpack_require__(19);
+ var fails = __webpack_require__(8);
+ var defined = __webpack_require__(36);
+ var wks = __webpack_require__(26);
+
+ module.exports = function (KEY, length, exec) {
+ var SYMBOL = wks(KEY);
+ var fns = exec(defined, SYMBOL, ''[KEY]);
+ var strfn = fns[0];
+ var rxfn = fns[1];
+ if (fails(function () {
var O = {};
- O[SYMBOL] = function(){ return 7; };
+ O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
- })){
+ })) {
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
- ? function(string, arg){ return rxfn.call(string, this, arg); }
+ ? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
- : function(string){ return rxfn.call(string, this); }
+ : function (string) { return rxfn.call(string, this); }
);
}
};
+
/***/ }),
-/* 202 */
+/* 203 */
/***/ (function(module, exports, __webpack_require__) {
// @@replace logic
- __webpack_require__(201)('replace', 2, function(defined, REPLACE, $replace){
+ __webpack_require__(202)('replace', 2, function (defined, REPLACE, $replace) {
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
- return [function replace(searchValue, replaceValue){
+ return [function replace(searchValue, replaceValue) {
'use strict';
- var O = defined(this)
- , fn = searchValue == undefined ? undefined : searchValue[REPLACE];
+ var O = defined(this);
+ var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
+
/***/ }),
-/* 203 */
+/* 204 */
/***/ (function(module, exports, __webpack_require__) {
// @@search logic
- __webpack_require__(201)('search', 1, function(defined, SEARCH, $search){
+ __webpack_require__(202)('search', 1, function (defined, SEARCH, $search) {
// 21.1.3.15 String.prototype.search(regexp)
- return [function search(regexp){
+ return [function search(regexp) {
'use strict';
- var O = defined(this)
- , fn = regexp == undefined ? undefined : regexp[SEARCH];
+ var O = defined(this);
+ var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
+
/***/ }),
-/* 204 */
+/* 205 */
/***/ (function(module, exports, __webpack_require__) {
// @@split logic
- __webpack_require__(201)('split', 2, function(defined, SPLIT, $split){
+ __webpack_require__(202)('split', 2, function (defined, SPLIT, $split) {
'use strict';
- var isRegExp = __webpack_require__(135)
- , _split = $split
- , $push = [].push
- , $SPLIT = 'split'
- , LENGTH = 'length'
- , LAST_INDEX = 'lastIndex';
- if(
+ var isRegExp = __webpack_require__(135);
+ var _split = $split;
+ var $push = [].push;
+ var $SPLIT = 'split';
+ var LENGTH = 'length';
+ var LAST_INDEX = 'lastIndex';
+ if (
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
- ){
+ ) {
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
- $split = function(separator, limit){
+ $split = function (separator, limit) {
var string = String(this);
- if(separator === undefined && limit === 0)return [];
+ if (separator === undefined && limit === 0) return [];
// If `separator` is not a regex, use native split
- if(!isRegExp(separator))return _split.call(string, separator, limit);
+ if (!isRegExp(separator)) return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
@@ -4199,215 +4433,197 @@ return /******/ (function(modules) { // webpackBootstrap
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
- if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
- while(match = separatorCopy.exec(string)){
+ if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
+ while (match = separatorCopy.exec(string)) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
- if(lastIndex > lastLastIndex){
+ if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
- if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
- for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
+ // eslint-disable-next-line no-loop-func
+ if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () {
+ for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined;
});
- if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
+ if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
- if(output[LENGTH] >= splitLimit)break;
+ if (output[LENGTH] >= splitLimit) break;
}
- if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
+ if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
- if(lastLastIndex === string[LENGTH]){
- if(lastLength || !separatorCopy.test(''))output.push('');
+ if (lastLastIndex === string[LENGTH]) {
+ if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
- } else if('0'[$SPLIT](undefined, 0)[LENGTH]){
- $split = function(separator, limit){
+ } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
+ $split = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
- return [function split(separator, limit){
- var O = defined(this)
- , fn = separator == undefined ? undefined : separator[SPLIT];
+ return [function split(separator, limit) {
+ var O = defined(this);
+ var fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
+
/***/ }),
-/* 205 */
+/* 206 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var LIBRARY = __webpack_require__(29)
- , global = __webpack_require__(5)
- , ctx = __webpack_require__(21)
- , classof = __webpack_require__(76)
- , $export = __webpack_require__(9)
- , isObject = __webpack_require__(14)
- , aFunction = __webpack_require__(22)
- , anInstance = __webpack_require__(206)
- , forOf = __webpack_require__(207)
- , speciesConstructor = __webpack_require__(208)
- , task = __webpack_require__(209).set
- , microtask = __webpack_require__(210)()
- , PROMISE = 'Promise'
- , TypeError = global.TypeError
- , process = global.process
- , $Promise = global[PROMISE]
- , process = global.process
- , isNode = classof(process) == 'process'
- , empty = function(){ /* empty */ }
- , Internal, GenericPromiseCapability, Wrapper;
-
- var USE_NATIVE = !!function(){
+ var LIBRARY = __webpack_require__(29);
+ var global = __webpack_require__(5);
+ var ctx = __webpack_require__(21);
+ var classof = __webpack_require__(75);
+ var $export = __webpack_require__(9);
+ var isObject = __webpack_require__(14);
+ var aFunction = __webpack_require__(22);
+ var anInstance = __webpack_require__(207);
+ var forOf = __webpack_require__(208);
+ var speciesConstructor = __webpack_require__(209);
+ var task = __webpack_require__(210).set;
+ var microtask = __webpack_require__(211)();
+ var newPromiseCapabilityModule = __webpack_require__(212);
+ var perform = __webpack_require__(213);
+ var promiseResolve = __webpack_require__(214);
+ var PROMISE = 'Promise';
+ var TypeError = global.TypeError;
+ var process = global.process;
+ var $Promise = global[PROMISE];
+ var isNode = classof(process) == 'process';
+ var empty = function () { /* empty */ };
+ var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
+ var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
+
+ var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
- var promise = $Promise.resolve(1)
- , FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function(exec){ exec(empty, empty); };
+ var promise = $Promise.resolve(1);
+ var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) {
+ exec(empty, empty);
+ };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
- } catch(e){ /* empty */ }
+ } catch (e) { /* empty */ }
}();
// helpers
- var sameConstructor = function(a, b){
- // with library wrapper special case
- return a === b || a === $Promise && b === Wrapper;
- };
- var isThenable = function(it){
+ var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
- var newPromiseCapability = function(C){
- return sameConstructor($Promise, C)
- ? new PromiseCapability(C)
- : new GenericPromiseCapability(C);
- };
- var PromiseCapability = GenericPromiseCapability = function(C){
- var resolve, reject;
- this.promise = new C(function($$resolve, $$reject){
- if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
- resolve = $$resolve;
- reject = $$reject;
- });
- this.resolve = aFunction(resolve);
- this.reject = aFunction(reject);
- };
- var perform = function(exec){
- try {
- exec();
- } catch(e){
- return {error: e};
- }
- };
- var notify = function(promise, isReject){
- if(promise._n)return;
+ var notify = function (promise, isReject) {
+ if (promise._n) return;
promise._n = true;
var chain = promise._c;
- microtask(function(){
- var value = promise._v
- , ok = promise._s == 1
- , i = 0;
- var run = function(reaction){
- var handler = ok ? reaction.ok : reaction.fail
- , resolve = reaction.resolve
- , reject = reaction.reject
- , domain = reaction.domain
- , result, then;
+ microtask(function () {
+ var value = promise._v;
+ var ok = promise._s == 1;
+ var i = 0;
+ var run = function (reaction) {
+ var handler = ok ? reaction.ok : reaction.fail;
+ var resolve = reaction.resolve;
+ var reject = reaction.reject;
+ var domain = reaction.domain;
+ var result, then;
try {
- if(handler){
- if(!ok){
- if(promise._h == 2)onHandleUnhandled(promise);
+ if (handler) {
+ if (!ok) {
+ if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
- if(handler === true)result = value;
+ if (handler === true) result = value;
else {
- if(domain)domain.enter();
+ if (domain) domain.enter();
result = handler(value);
- if(domain)domain.exit();
+ if (domain) domain.exit();
}
- if(result === reaction.promise){
+ if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
- } else if(then = isThenable(result)){
+ } else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
- } catch(e){
+ } catch (e) {
reject(e);
}
};
- while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
+ while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
- if(isReject && !promise._h)onUnhandled(promise);
+ if (isReject && !promise._h) onUnhandled(promise);
});
};
- var onUnhandled = function(promise){
- task.call(global, function(){
- var value = promise._v
- , abrupt, handler, console;
- if(isUnhandled(promise)){
- abrupt = perform(function(){
- if(isNode){
+ var onUnhandled = function (promise) {
+ task.call(global, function () {
+ var value = promise._v;
+ var unhandled = isUnhandled(promise);
+ var result, handler, console;
+ if (unhandled) {
+ result = perform(function () {
+ if (isNode) {
process.emit('unhandledRejection', value, promise);
- } else if(handler = global.onunhandledrejection){
- handler({promise: promise, reason: value});
- } else if((console = global.console) && console.error){
+ } else if (handler = global.onunhandledrejection) {
+ handler({ promise: promise, reason: value });
+ } else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
- if(abrupt)throw abrupt.error;
+ if (unhandled && result.e) throw result.v;
});
};
- var isUnhandled = function(promise){
- if(promise._h == 1)return false;
- var chain = promise._a || promise._c
- , i = 0
- , reaction;
- while(chain.length > i){
+ var isUnhandled = function (promise) {
+ if (promise._h == 1) return false;
+ var chain = promise._a || promise._c;
+ var i = 0;
+ var reaction;
+ while (chain.length > i) {
reaction = chain[i++];
- if(reaction.fail || !isUnhandled(reaction.promise))return false;
+ if (reaction.fail || !isUnhandled(reaction.promise)) return false;
} return true;
};
- var onHandleUnhandled = function(promise){
- task.call(global, function(){
+ var onHandleUnhandled = function (promise) {
+ task.call(global, function () {
var handler;
- if(isNode){
+ if (isNode) {
process.emit('rejectionHandled', promise);
- } else if(handler = global.onrejectionhandled){
- handler({promise: promise, reason: promise._v});
+ } else if (handler = global.onrejectionhandled) {
+ handler({ promise: promise, reason: promise._v });
}
});
};
- var $reject = function(value){
+ var $reject = function (value) {
var promise = this;
- if(promise._d)return;
+ if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
- if(!promise._a)promise._a = promise._c.slice();
+ if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
- var $resolve = function(value){
- var promise = this
- , then;
- if(promise._d)return;
+ var $resolve = function (value) {
+ var promise = this;
+ var then;
+ if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
- if(promise === value)throw TypeError("Promise can't be resolved itself");
- if(then = isThenable(value)){
- microtask(function(){
- var wrapper = {_w: promise, _d: false}; // wrap
+ if (promise === value) throw TypeError("Promise can't be resolved itself");
+ if (then = isThenable(value)) {
+ microtask(function () {
+ var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
- } catch(e){
+ } catch (e) {
$reject.call(wrapper, e);
}
});
@@ -4416,25 +4632,26 @@ return /******/ (function(modules) { // webpackBootstrap
promise._s = 1;
notify(promise, false);
}
- } catch(e){
- $reject.call({_w: promise, _d: false}, e); // wrap
+ } catch (e) {
+ $reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
- if(!USE_NATIVE){
+ if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
- $Promise = function Promise(executor){
+ $Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
- } catch(err){
+ } catch (err) {
$reject.call(this, err);
}
};
- Internal = function Promise(executor){
+ // eslint-disable-next-line no-unused-vars
+ Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
@@ -4443,283 +4660,298 @@ return /******/ (function(modules) { // webpackBootstrap
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
- Internal.prototype = __webpack_require__(211)($Promise.prototype, {
+ Internal.prototype = __webpack_require__(215)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
- then: function then(onFulfilled, onRejected){
- var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
- reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
- reaction.fail = typeof onRejected == 'function' && onRejected;
+ then: function then(onFulfilled, onRejected) {
+ var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
+ reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
+ reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
- if(this._a)this._a.push(reaction);
- if(this._s)notify(this, false);
+ if (this._a) this._a.push(reaction);
+ if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
- 'catch': function(onRejected){
+ 'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
- PromiseCapability = function(){
- var promise = new Internal;
+ OwnPromiseCapability = function () {
+ var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
- this.reject = ctx($reject, promise, 1);
+ this.reject = ctx($reject, promise, 1);
+ };
+ newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
+ return C === $Promise || C === Wrapper
+ ? new OwnPromiseCapability(C)
+ : newGenericPromiseCapability(C);
};
}
- $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
+ $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(25)($Promise, PROMISE);
- __webpack_require__(193)(PROMISE);
+ __webpack_require__(194)(PROMISE);
Wrapper = __webpack_require__(10)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
- reject: function reject(r){
- var capability = newPromiseCapability(this)
- , $$reject = capability.reject;
+ reject: function reject(r) {
+ var capability = newPromiseCapability(this);
+ var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
- resolve: function resolve(x){
- // instanceof instead of internal slot check because we should fix it without replacement native Promise core
- if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
- var capability = newPromiseCapability(this)
- , $$resolve = capability.resolve;
- $$resolve(x);
- return capability.promise;
+ resolve: function resolve(x) {
+ return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
- $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function(iter){
+ $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(167)(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
- all: function all(iterable){
- var C = this
- , capability = newPromiseCapability(C)
- , resolve = capability.resolve
- , reject = capability.reject;
- var abrupt = perform(function(){
- var values = []
- , index = 0
- , remaining = 1;
- forOf(iterable, false, function(promise){
- var $index = index++
- , alreadyCalled = false;
+ all: function all(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var resolve = capability.resolve;
+ var reject = capability.reject;
+ var result = perform(function () {
+ var values = [];
+ var index = 0;
+ var remaining = 1;
+ forOf(iterable, false, function (promise) {
+ var $index = index++;
+ var alreadyCalled = false;
values.push(undefined);
remaining++;
- C.resolve(promise).then(function(value){
- if(alreadyCalled)return;
- alreadyCalled = true;
+ C.resolve(promise).then(function (value) {
+ if (alreadyCalled) return;
+ alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
- if(abrupt)reject(abrupt.error);
+ if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
- race: function race(iterable){
- var C = this
- , capability = newPromiseCapability(C)
- , reject = capability.reject;
- var abrupt = perform(function(){
- forOf(iterable, false, function(promise){
+ race: function race(iterable) {
+ var C = this;
+ var capability = newPromiseCapability(C);
+ var reject = capability.reject;
+ var result = perform(function () {
+ forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
- if(abrupt)reject(abrupt.error);
+ if (result.e) reject(result.v);
return capability.promise;
}
});
+
/***/ }),
-/* 206 */
+/* 207 */
/***/ (function(module, exports) {
- module.exports = function(it, Constructor, name, forbiddenField){
- if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
+ module.exports = function (it, Constructor, name, forbiddenField) {
+ if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
+
/***/ }),
-/* 207 */
+/* 208 */
/***/ (function(module, exports, __webpack_require__) {
- var ctx = __webpack_require__(21)
- , call = __webpack_require__(162)
- , isArrayIter = __webpack_require__(163)
- , anObject = __webpack_require__(13)
- , toLength = __webpack_require__(38)
- , getIterFn = __webpack_require__(165)
- , BREAK = {}
- , RETURN = {};
- var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
- var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
- , f = ctx(fn, that, entries ? 2 : 1)
- , index = 0
- , length, step, iterator, result;
- if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
+ var ctx = __webpack_require__(21);
+ var call = __webpack_require__(163);
+ var isArrayIter = __webpack_require__(164);
+ var anObject = __webpack_require__(13);
+ var toLength = __webpack_require__(38);
+ var getIterFn = __webpack_require__(166);
+ var BREAK = {};
+ var RETURN = {};
+ var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
+ var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
+ var f = ctx(fn, that, entries ? 2 : 1);
+ var index = 0;
+ var length, step, iterator, result;
+ if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
- if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
+ if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
- if(result === BREAK || result === RETURN)return result;
- } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
+ if (result === BREAK || result === RETURN) return result;
+ } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
- if(result === BREAK || result === RETURN)return result;
+ if (result === BREAK || result === RETURN) return result;
}
};
- exports.BREAK = BREAK;
+ exports.BREAK = BREAK;
exports.RETURN = RETURN;
+
/***/ }),
-/* 208 */
+/* 209 */
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
- var anObject = __webpack_require__(13)
- , aFunction = __webpack_require__(22)
- , SPECIES = __webpack_require__(26)('species');
- module.exports = function(O, D){
- var C = anObject(O).constructor, S;
+ var anObject = __webpack_require__(13);
+ var aFunction = __webpack_require__(22);
+ var SPECIES = __webpack_require__(26)('species');
+ module.exports = function (O, D) {
+ var C = anObject(O).constructor;
+ var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
+
/***/ }),
-/* 209 */
+/* 210 */
/***/ (function(module, exports, __webpack_require__) {
- var ctx = __webpack_require__(21)
- , invoke = __webpack_require__(79)
- , html = __webpack_require__(49)
- , cel = __webpack_require__(16)
- , global = __webpack_require__(5)
- , process = global.process
- , setTask = global.setImmediate
- , clearTask = global.clearImmediate
- , MessageChannel = global.MessageChannel
- , counter = 0
- , queue = {}
- , ONREADYSTATECHANGE = 'onreadystatechange'
- , defer, channel, port;
- var run = function(){
+ var ctx = __webpack_require__(21);
+ var invoke = __webpack_require__(78);
+ var html = __webpack_require__(48);
+ var cel = __webpack_require__(16);
+ var global = __webpack_require__(5);
+ var process = global.process;
+ var setTask = global.setImmediate;
+ var clearTask = global.clearImmediate;
+ var MessageChannel = global.MessageChannel;
+ var Dispatch = global.Dispatch;
+ var counter = 0;
+ var queue = {};
+ var ONREADYSTATECHANGE = 'onreadystatechange';
+ var defer, channel, port;
+ var run = function () {
var id = +this;
- if(queue.hasOwnProperty(id)){
+ // eslint-disable-next-line no-prototype-builtins
+ if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
- var listener = function(event){
+ var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
- if(!setTask || !clearTask){
- setTask = function setImmediate(fn){
- var args = [], i = 1;
- while(arguments.length > i)args.push(arguments[i++]);
- queue[++counter] = function(){
+ if (!setTask || !clearTask) {
+ setTask = function setImmediate(fn) {
+ var args = [];
+ var i = 1;
+ while (arguments.length > i) args.push(arguments[i++]);
+ queue[++counter] = function () {
+ // eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
- clearTask = function clearImmediate(id){
+ clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
- if(__webpack_require__(35)(process) == 'process'){
- defer = function(id){
+ if (__webpack_require__(35)(process) == 'process') {
+ defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
+ // Sphere (JS game engine) Dispatch API
+ } else if (Dispatch && Dispatch.now) {
+ defer = function (id) {
+ Dispatch.now(ctx(run, id, 1));
+ };
// Browsers with MessageChannel, includes WebWorkers
- } else if(MessageChannel){
- channel = new MessageChannel;
- port = channel.port2;
+ } else if (MessageChannel) {
+ channel = new MessageChannel();
+ port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
- } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
- defer = function(id){
+ } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
+ defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
- } else if(ONREADYSTATECHANGE in cel('script')){
- defer = function(id){
- html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
+ } else if (ONREADYSTATECHANGE in cel('script')) {
+ defer = function (id) {
+ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
- defer = function(id){
+ defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
- set: setTask,
+ set: setTask,
clear: clearTask
};
+
/***/ }),
-/* 210 */
+/* 211 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , macrotask = __webpack_require__(209).set
- , Observer = global.MutationObserver || global.WebKitMutationObserver
- , process = global.process
- , Promise = global.Promise
- , isNode = __webpack_require__(35)(process) == 'process';
+ var global = __webpack_require__(5);
+ var macrotask = __webpack_require__(210).set;
+ var Observer = global.MutationObserver || global.WebKitMutationObserver;
+ var process = global.process;
+ var Promise = global.Promise;
+ var isNode = __webpack_require__(35)(process) == 'process';
- module.exports = function(){
+ module.exports = function () {
var head, last, notify;
- var flush = function(){
+ var flush = function () {
var parent, fn;
- if(isNode && (parent = process.domain))parent.exit();
- while(head){
- fn = head.fn;
+ if (isNode && (parent = process.domain)) parent.exit();
+ while (head) {
+ fn = head.fn;
head = head.next;
try {
fn();
- } catch(e){
- if(head)notify();
+ } catch (e) {
+ if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
- if(parent)parent.enter();
+ if (parent) parent.enter();
};
// Node.js
- if(isNode){
- notify = function(){
+ if (isNode) {
+ notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver
- } else if(Observer){
- var toggle = true
- , node = document.createTextNode('');
- new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
- notify = function(){
+ } else if (Observer) {
+ var toggle = true;
+ var node = document.createTextNode('');
+ new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
+ notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
- } else if(Promise && Promise.resolve){
+ } else if (Promise && Promise.resolve) {
var promise = Promise.resolve();
- notify = function(){
+ notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
@@ -4729,100 +4961,162 @@ return /******/ (function(modules) { // webpackBootstrap
// - onreadystatechange
// - setTimeout
} else {
- notify = function(){
+ notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
- return function(fn){
- var task = {fn: fn, next: undefined};
- if(last)last.next = task;
- if(!head){
+ return function (fn) {
+ var task = { fn: fn, next: undefined };
+ if (last) last.next = task;
+ if (!head) {
head = task;
notify();
} last = task;
};
};
+
/***/ }),
-/* 211 */
+/* 212 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ 'use strict';
+ // 25.4.1.5 NewPromiseCapability(C)
+ var aFunction = __webpack_require__(22);
+
+ function PromiseCapability(C) {
+ var resolve, reject;
+ this.promise = new C(function ($$resolve, $$reject) {
+ if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
+ resolve = $$resolve;
+ reject = $$reject;
+ });
+ this.resolve = aFunction(resolve);
+ this.reject = aFunction(reject);
+ }
+
+ module.exports.f = function (C) {
+ return new PromiseCapability(C);
+ };
+
+
+/***/ }),
+/* 213 */
+/***/ (function(module, exports) {
+
+ module.exports = function (exec) {
+ try {
+ return { e: false, v: exec() };
+ } catch (e) {
+ return { e: true, v: e };
+ }
+ };
+
+
+/***/ }),
+/* 214 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ var anObject = __webpack_require__(13);
+ var isObject = __webpack_require__(14);
+ var newPromiseCapability = __webpack_require__(212);
+
+ module.exports = function (C, x) {
+ anObject(C);
+ if (isObject(x) && x.constructor === C) return x;
+ var promiseCapability = newPromiseCapability.f(C);
+ var resolve = promiseCapability.resolve;
+ resolve(x);
+ return promiseCapability.promise;
+ };
+
+
+/***/ }),
+/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(19);
- module.exports = function(target, src, safe){
- for(var key in src)redefine(target, key, src[key], safe);
+ module.exports = function (target, src, safe) {
+ for (var key in src) redefine(target, key, src[key], safe);
return target;
};
+
/***/ }),
-/* 212 */
+/* 216 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var strong = __webpack_require__(213);
+ var strong = __webpack_require__(217);
+ var validate = __webpack_require__(218);
+ var MAP = 'Map';
// 23.1 Map Objects
- module.exports = __webpack_require__(214)('Map', function(get){
- return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
+ module.exports = __webpack_require__(219)(MAP, function (get) {
+ return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
- get: function get(key){
- var entry = strong.getEntry(this, key);
+ get: function get(key) {
+ var entry = strong.getEntry(validate(this, MAP), key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
- set: function set(key, value){
- return strong.def(this, key === 0 ? 0 : key, value);
+ set: function set(key, value) {
+ return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
}
}, strong, true);
+
/***/ }),
-/* 213 */
+/* 217 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var dP = __webpack_require__(12).f
- , create = __webpack_require__(47)
- , redefineAll = __webpack_require__(211)
- , ctx = __webpack_require__(21)
- , anInstance = __webpack_require__(206)
- , defined = __webpack_require__(36)
- , forOf = __webpack_require__(207)
- , $iterDefine = __webpack_require__(129)
- , step = __webpack_require__(195)
- , setSpecies = __webpack_require__(193)
- , DESCRIPTORS = __webpack_require__(7)
- , fastKey = __webpack_require__(23).fastKey
- , SIZE = DESCRIPTORS ? '_s' : 'size';
-
- var getEntry = function(that, key){
+ var dP = __webpack_require__(12).f;
+ var create = __webpack_require__(46);
+ var redefineAll = __webpack_require__(215);
+ var ctx = __webpack_require__(21);
+ var anInstance = __webpack_require__(207);
+ var forOf = __webpack_require__(208);
+ var $iterDefine = __webpack_require__(129);
+ var step = __webpack_require__(196);
+ var setSpecies = __webpack_require__(194);
+ var DESCRIPTORS = __webpack_require__(7);
+ var fastKey = __webpack_require__(23).fastKey;
+ var validate = __webpack_require__(218);
+ var SIZE = DESCRIPTORS ? '_s' : 'size';
+
+ var getEntry = function (that, key) {
// fast case
- var index = fastKey(key), entry;
- if(index !== 'F')return that._i[index];
+ var index = fastKey(key);
+ var entry;
+ if (index !== 'F') return that._i[index];
// frozen object case
- for(entry = that._f; entry; entry = entry.n){
- if(entry.k == key)return entry;
+ for (entry = that._f; entry; entry = entry.n) {
+ if (entry.k == key) return entry;
}
};
module.exports = {
- getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
- var C = wrapper(function(that, iterable){
+ getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
+ var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
+ that._t = NAME; // collection type
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
- if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
+ if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
- clear: function clear(){
- for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
+ clear: function clear() {
+ for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
entry.r = true;
- if(entry.p)entry.p = entry.p.n = undefined;
+ if (entry.p) entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
@@ -4830,51 +5124,51 @@ return /******/ (function(modules) { // webpackBootstrap
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
- 'delete': function(key){
- var that = this
- , entry = getEntry(that, key);
- if(entry){
- var next = entry.n
- , prev = entry.p;
+ 'delete': function (key) {
+ var that = validate(this, NAME);
+ var entry = getEntry(that, key);
+ if (entry) {
+ var next = entry.n;
+ var prev = entry.p;
delete that._i[entry.i];
entry.r = true;
- if(prev)prev.n = next;
- if(next)next.p = prev;
- if(that._f == entry)that._f = next;
- if(that._l == entry)that._l = prev;
+ if (prev) prev.n = next;
+ if (next) next.p = prev;
+ if (that._f == entry) that._f = next;
+ if (that._l == entry) that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
- forEach: function forEach(callbackfn /*, that = undefined */){
- anInstance(this, C, 'forEach');
- var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
- , entry;
- while(entry = entry ? entry.n : this._f){
+ forEach: function forEach(callbackfn /* , that = undefined */) {
+ validate(this, NAME);
+ var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
+ var entry;
+ while (entry = entry ? entry.n : this._f) {
f(entry.v, entry.k, this);
// revert to the last existing entry
- while(entry && entry.r)entry = entry.p;
+ while (entry && entry.r) entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
- has: function has(key){
- return !!getEntry(this, key);
+ has: function has(key) {
+ return !!getEntry(validate(this, NAME), key);
}
});
- if(DESCRIPTORS)dP(C.prototype, 'size', {
- get: function(){
- return defined(this[SIZE]);
+ if (DESCRIPTORS) dP(C.prototype, 'size', {
+ get: function () {
+ return validate(this, NAME)[SIZE];
}
});
return C;
},
- def: function(that, key, value){
- var entry = getEntry(that, key)
- , prev, index;
+ def: function (that, key, value) {
+ var entry = getEntry(that, key);
+ var prev, index;
// change existing entry
- if(entry){
+ if (entry) {
entry.v = value;
// create new entry
} else {
@@ -4886,122 +5180,134 @@ return /******/ (function(modules) { // webpackBootstrap
n: undefined, // <- next entry
r: false // <- removed
};
- if(!that._f)that._f = entry;
- if(prev)prev.n = entry;
+ if (!that._f) that._f = entry;
+ if (prev) prev.n = entry;
that[SIZE]++;
// add to index
- if(index !== 'F')that._i[index] = entry;
+ if (index !== 'F') that._i[index] = entry;
} return that;
},
getEntry: getEntry,
- setStrong: function(C, NAME, IS_MAP){
+ setStrong: function (C, NAME, IS_MAP) {
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
- $iterDefine(C, NAME, function(iterated, kind){
- this._t = iterated; // target
- this._k = kind; // kind
- this._l = undefined; // previous
- }, function(){
- var that = this
- , kind = that._k
- , entry = that._l;
+ $iterDefine(C, NAME, function (iterated, kind) {
+ this._t = validate(iterated, NAME); // target
+ this._k = kind; // kind
+ this._l = undefined; // previous
+ }, function () {
+ var that = this;
+ var kind = that._k;
+ var entry = that._l;
// revert to the last existing entry
- while(entry && entry.r)entry = entry.p;
+ while (entry && entry.r) entry = entry.p;
// get next entry
- if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
+ if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
- if(kind == 'keys' )return step(0, entry.k);
- if(kind == 'values')return step(0, entry.v);
+ if (kind == 'keys') return step(0, entry.k);
+ if (kind == 'values') return step(0, entry.v);
return step(0, [entry.k, entry.v]);
- }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
+ }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
+
/***/ }),
-/* 214 */
+/* 218 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ var isObject = __webpack_require__(14);
+ module.exports = function (it, TYPE) {
+ if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
+ return it;
+ };
+
+
+/***/ }),
+/* 219 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var global = __webpack_require__(5)
- , $export = __webpack_require__(9)
- , redefine = __webpack_require__(19)
- , redefineAll = __webpack_require__(211)
- , meta = __webpack_require__(23)
- , forOf = __webpack_require__(207)
- , anInstance = __webpack_require__(206)
- , isObject = __webpack_require__(14)
- , fails = __webpack_require__(8)
- , $iterDetect = __webpack_require__(166)
- , setToStringTag = __webpack_require__(25)
- , inheritIfRequired = __webpack_require__(89);
-
- module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
- var Base = global[NAME]
- , C = Base
- , ADDER = IS_MAP ? 'set' : 'add'
- , proto = C && C.prototype
- , O = {};
- var fixMethod = function(KEY){
+ var global = __webpack_require__(5);
+ var $export = __webpack_require__(9);
+ var redefine = __webpack_require__(19);
+ var redefineAll = __webpack_require__(215);
+ var meta = __webpack_require__(23);
+ var forOf = __webpack_require__(208);
+ var anInstance = __webpack_require__(207);
+ var isObject = __webpack_require__(14);
+ var fails = __webpack_require__(8);
+ var $iterDetect = __webpack_require__(167);
+ var setToStringTag = __webpack_require__(25);
+ var inheritIfRequired = __webpack_require__(88);
+
+ module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
+ var Base = global[NAME];
+ var C = Base;
+ var ADDER = IS_MAP ? 'set' : 'add';
+ var proto = C && C.prototype;
+ var O = {};
+ var fixMethod = function (KEY) {
var fn = proto[KEY];
redefine(proto, KEY,
- KEY == 'delete' ? function(a){
+ KEY == 'delete' ? function (a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
- } : KEY == 'has' ? function has(a){
+ } : KEY == 'has' ? function has(a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
- } : KEY == 'get' ? function get(a){
+ } : KEY == 'get' ? function get(a) {
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
- } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
- : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
+ } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
+ : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
- if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
+ if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
- }))){
+ }))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
- var instance = new C
- // early implementations not supports chaining
- , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
- // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
- , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
- // most early implementations doesn't supports iterables, most modern - not close it correctly
- , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
- // for early implementations -0 and +0 not the same
- , BUGGY_ZERO = !IS_WEAK && fails(function(){
- // V8 ~ Chromium 42- fails only with 5+ elements
- var $instance = new C()
- , index = 5;
- while(index--)$instance[ADDER](index, index);
- return !$instance.has(-0);
- });
- if(!ACCEPT_ITERABLES){
- C = wrapper(function(target, iterable){
+ var instance = new C();
+ // early implementations not supports chaining
+ var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
+ // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
+ var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
+ // most early implementations doesn't supports iterables, most modern - not close it correctly
+ var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
+ // for early implementations -0 and +0 not the same
+ var BUGGY_ZERO = !IS_WEAK && fails(function () {
+ // V8 ~ Chromium 42- fails only with 5+ elements
+ var $instance = new C();
+ var index = 5;
+ while (index--) $instance[ADDER](index, index);
+ return !$instance.has(-0);
+ });
+ if (!ACCEPT_ITERABLES) {
+ C = wrapper(function (target, iterable) {
anInstance(target, C, NAME);
- var that = inheritIfRequired(new Base, target, C);
- if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
+ var that = inheritIfRequired(new Base(), target, C);
+ if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
- if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
+ if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
- if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
+ if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
- if(IS_WEAK && proto.clear)delete proto.clear;
+ if (IS_WEAK && proto.clear) delete proto.clear;
}
setToStringTag(C, NAME);
@@ -5009,81 +5315,88 @@ return /******/ (function(modules) { // webpackBootstrap
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
- if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
+ if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
+
/***/ }),
-/* 215 */
+/* 220 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var strong = __webpack_require__(213);
+ var strong = __webpack_require__(217);
+ var validate = __webpack_require__(218);
+ var SET = 'Set';
// 23.2 Set Objects
- module.exports = __webpack_require__(214)('Set', function(get){
- return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
+ module.exports = __webpack_require__(219)(SET, function (get) {
+ return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
- add: function add(value){
- return strong.def(this, value = value === 0 ? 0 : value, value);
+ add: function add(value) {
+ return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
+
/***/ }),
-/* 216 */
+/* 221 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var each = __webpack_require__(173)(0)
- , redefine = __webpack_require__(19)
- , meta = __webpack_require__(23)
- , assign = __webpack_require__(70)
- , weak = __webpack_require__(217)
- , isObject = __webpack_require__(14)
- , getWeak = meta.getWeak
- , isExtensible = Object.isExtensible
- , uncaughtFrozenStore = weak.ufstore
- , tmp = {}
- , InternalMap;
-
- var wrapper = function(get){
- return function WeakMap(){
+ var each = __webpack_require__(174)(0);
+ var redefine = __webpack_require__(19);
+ var meta = __webpack_require__(23);
+ var assign = __webpack_require__(69);
+ var weak = __webpack_require__(222);
+ var isObject = __webpack_require__(14);
+ var fails = __webpack_require__(8);
+ var validate = __webpack_require__(218);
+ var WEAK_MAP = 'WeakMap';
+ var getWeak = meta.getWeak;
+ var isExtensible = Object.isExtensible;
+ var uncaughtFrozenStore = weak.ufstore;
+ var tmp = {};
+ var InternalMap;
+
+ var wrapper = function (get) {
+ return function WeakMap() {
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
- get: function get(key){
- if(isObject(key)){
+ get: function get(key) {
+ if (isObject(key)) {
var data = getWeak(key);
- if(data === true)return uncaughtFrozenStore(this).get(key);
+ if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
- set: function set(key, value){
- return weak.def(this, key, value);
+ set: function set(key, value) {
+ return weak.def(validate(this, WEAK_MAP), key, value);
}
};
// 23.3 WeakMap Objects
- var $WeakMap = module.exports = __webpack_require__(214)('WeakMap', wrapper, methods, weak, true, true);
+ var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
- if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
- InternalMap = weak.getConstructor(wrapper);
+ if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) {
+ InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
assign(InternalMap.prototype, methods);
meta.NEED = true;
- each(['delete', 'has', 'get', 'set'], function(key){
- var proto = $WeakMap.prototype
- , method = proto[key];
- redefine(proto, key, function(a, b){
+ each(['delete', 'has', 'get', 'set'], function (key) {
+ var proto = $WeakMap.prototype;
+ var method = proto[key];
+ redefine(proto, key, function (a, b) {
// store frozen objects on internal weakmap shim
- if(isObject(a) && !isExtensible(a)){
- if(!this._f)this._f = new InternalMap;
+ if (isObject(a) && !isExtensible(a)) {
+ if (!this._f) this._f = new InternalMap();
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
@@ -5092,268 +5405,283 @@ return /******/ (function(modules) { // webpackBootstrap
});
}
+
/***/ }),
-/* 217 */
+/* 222 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var redefineAll = __webpack_require__(211)
- , getWeak = __webpack_require__(23).getWeak
- , anObject = __webpack_require__(13)
- , isObject = __webpack_require__(14)
- , anInstance = __webpack_require__(206)
- , forOf = __webpack_require__(207)
- , createArrayMethod = __webpack_require__(173)
- , $has = __webpack_require__(6)
- , arrayFind = createArrayMethod(5)
- , arrayFindIndex = createArrayMethod(6)
- , id = 0;
+ var redefineAll = __webpack_require__(215);
+ var getWeak = __webpack_require__(23).getWeak;
+ var anObject = __webpack_require__(13);
+ var isObject = __webpack_require__(14);
+ var anInstance = __webpack_require__(207);
+ var forOf = __webpack_require__(208);
+ var createArrayMethod = __webpack_require__(174);
+ var $has = __webpack_require__(6);
+ var validate = __webpack_require__(218);
+ var arrayFind = createArrayMethod(5);
+ var arrayFindIndex = createArrayMethod(6);
+ var id = 0;
// fallback for uncaught frozen keys
- var uncaughtFrozenStore = function(that){
- return that._l || (that._l = new UncaughtFrozenStore);
+ var uncaughtFrozenStore = function (that) {
+ return that._l || (that._l = new UncaughtFrozenStore());
};
- var UncaughtFrozenStore = function(){
+ var UncaughtFrozenStore = function () {
this.a = [];
};
- var findUncaughtFrozen = function(store, key){
- return arrayFind(store.a, function(it){
+ var findUncaughtFrozen = function (store, key) {
+ return arrayFind(store.a, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
- get: function(key){
+ get: function (key) {
var entry = findUncaughtFrozen(this, key);
- if(entry)return entry[1];
+ if (entry) return entry[1];
},
- has: function(key){
+ has: function (key) {
return !!findUncaughtFrozen(this, key);
},
- set: function(key, value){
+ set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
- if(entry)entry[1] = value;
+ if (entry) entry[1] = value;
else this.a.push([key, value]);
},
- 'delete': function(key){
- var index = arrayFindIndex(this.a, function(it){
+ 'delete': function (key) {
+ var index = arrayFindIndex(this.a, function (it) {
return it[0] === key;
});
- if(~index)this.a.splice(index, 1);
+ if (~index) this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
- getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
- var C = wrapper(function(that, iterable){
+ getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
+ var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
+ that._t = NAME; // collection type
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
- if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
+ if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
- 'delete': function(key){
- if(!isObject(key))return false;
+ 'delete': function (key) {
+ if (!isObject(key)) return false;
var data = getWeak(key);
- if(data === true)return uncaughtFrozenStore(this)['delete'](key);
+ if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
- has: function has(key){
- if(!isObject(key))return false;
+ has: function has(key) {
+ if (!isObject(key)) return false;
var data = getWeak(key);
- if(data === true)return uncaughtFrozenStore(this).has(key);
+ if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
return data && $has(data, this._i);
}
});
return C;
},
- def: function(that, key, value){
+ def: function (that, key, value) {
var data = getWeak(anObject(key), true);
- if(data === true)uncaughtFrozenStore(that).set(key, value);
+ if (data === true) uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
+
/***/ }),
-/* 218 */
+/* 223 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var weak = __webpack_require__(217);
+ var weak = __webpack_require__(222);
+ var validate = __webpack_require__(218);
+ var WEAK_SET = 'WeakSet';
// 23.4 WeakSet Objects
- __webpack_require__(214)('WeakSet', function(get){
- return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
+ __webpack_require__(219)(WEAK_SET, function (get) {
+ return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
- add: function add(value){
- return weak.def(this, value, true);
+ add: function add(value) {
+ return weak.def(validate(this, WEAK_SET), value, true);
}
}, weak, false, true);
+
/***/ }),
-/* 219 */
+/* 224 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , $typed = __webpack_require__(220)
- , buffer = __webpack_require__(221)
- , anObject = __webpack_require__(13)
- , toIndex = __webpack_require__(40)
- , toLength = __webpack_require__(38)
- , isObject = __webpack_require__(14)
- , ArrayBuffer = __webpack_require__(5).ArrayBuffer
- , speciesConstructor = __webpack_require__(208)
- , $ArrayBuffer = buffer.ArrayBuffer
- , $DataView = buffer.DataView
- , $isView = $typed.ABV && ArrayBuffer.isView
- , $slice = $ArrayBuffer.prototype.slice
- , VIEW = $typed.VIEW
- , ARRAY_BUFFER = 'ArrayBuffer';
-
- $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
+ var $export = __webpack_require__(9);
+ var $typed = __webpack_require__(225);
+ var buffer = __webpack_require__(226);
+ var anObject = __webpack_require__(13);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var toLength = __webpack_require__(38);
+ var isObject = __webpack_require__(14);
+ var ArrayBuffer = __webpack_require__(5).ArrayBuffer;
+ var speciesConstructor = __webpack_require__(209);
+ var $ArrayBuffer = buffer.ArrayBuffer;
+ var $DataView = buffer.DataView;
+ var $isView = $typed.ABV && ArrayBuffer.isView;
+ var $slice = $ArrayBuffer.prototype.slice;
+ var VIEW = $typed.VIEW;
+ var ARRAY_BUFFER = 'ArrayBuffer';
+
+ $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer });
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
- isView: function isView(it){
+ isView: function isView(it) {
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
- $export($export.P + $export.U + $export.F * __webpack_require__(8)(function(){
+ $export($export.P + $export.U + $export.F * __webpack_require__(8)(function () {
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
- slice: function slice(start, end){
- if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
- var len = anObject(this).byteLength
- , first = toIndex(start, len)
- , final = toIndex(end === undefined ? len : end, len)
- , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
- , viewS = new $DataView(this)
- , viewT = new $DataView(result)
- , index = 0;
- while(first < final){
+ slice: function slice(start, end) {
+ if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix
+ var len = anObject(this).byteLength;
+ var first = toAbsoluteIndex(start, len);
+ var final = toAbsoluteIndex(end === undefined ? len : end, len);
+ var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first));
+ var viewS = new $DataView(this);
+ var viewT = new $DataView(result);
+ var index = 0;
+ while (first < final) {
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
- __webpack_require__(193)(ARRAY_BUFFER);
+ __webpack_require__(194)(ARRAY_BUFFER);
+
/***/ }),
-/* 220 */
+/* 225 */
/***/ (function(module, exports, __webpack_require__) {
- var global = __webpack_require__(5)
- , hide = __webpack_require__(11)
- , uid = __webpack_require__(20)
- , TYPED = uid('typed_array')
- , VIEW = uid('view')
- , ABV = !!(global.ArrayBuffer && global.DataView)
- , CONSTR = ABV
- , i = 0, l = 9, Typed;
+ var global = __webpack_require__(5);
+ var hide = __webpack_require__(11);
+ var uid = __webpack_require__(20);
+ var TYPED = uid('typed_array');
+ var VIEW = uid('view');
+ var ABV = !!(global.ArrayBuffer && global.DataView);
+ var CONSTR = ABV;
+ var i = 0;
+ var l = 9;
+ var Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
- while(i < l){
- if(Typed = global[TypedArrayConstructors[i++]]){
+ while (i < l) {
+ if (Typed = global[TypedArrayConstructors[i++]]) {
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
- ABV: ABV,
+ ABV: ABV,
CONSTR: CONSTR,
- TYPED: TYPED,
- VIEW: VIEW
+ TYPED: TYPED,
+ VIEW: VIEW
};
+
/***/ }),
-/* 221 */
+/* 226 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var global = __webpack_require__(5)
- , DESCRIPTORS = __webpack_require__(7)
- , LIBRARY = __webpack_require__(29)
- , $typed = __webpack_require__(220)
- , hide = __webpack_require__(11)
- , redefineAll = __webpack_require__(211)
- , fails = __webpack_require__(8)
- , anInstance = __webpack_require__(206)
- , toInteger = __webpack_require__(39)
- , toLength = __webpack_require__(38)
- , gOPN = __webpack_require__(51).f
- , dP = __webpack_require__(12).f
- , arrayFill = __webpack_require__(189)
- , setToStringTag = __webpack_require__(25)
- , ARRAY_BUFFER = 'ArrayBuffer'
- , DATA_VIEW = 'DataView'
- , PROTOTYPE = 'prototype'
- , WRONG_LENGTH = 'Wrong length!'
- , WRONG_INDEX = 'Wrong index!'
- , $ArrayBuffer = global[ARRAY_BUFFER]
- , $DataView = global[DATA_VIEW]
- , Math = global.Math
- , RangeError = global.RangeError
- , Infinity = global.Infinity
- , BaseBuffer = $ArrayBuffer
- , abs = Math.abs
- , pow = Math.pow
- , floor = Math.floor
- , log = Math.log
- , LN2 = Math.LN2
- , BUFFER = 'buffer'
- , BYTE_LENGTH = 'byteLength'
- , BYTE_OFFSET = 'byteOffset'
- , $BUFFER = DESCRIPTORS ? '_b' : BUFFER
- , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
- , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
+ var global = __webpack_require__(5);
+ var DESCRIPTORS = __webpack_require__(7);
+ var LIBRARY = __webpack_require__(29);
+ var $typed = __webpack_require__(225);
+ var hide = __webpack_require__(11);
+ var redefineAll = __webpack_require__(215);
+ var fails = __webpack_require__(8);
+ var anInstance = __webpack_require__(207);
+ var toInteger = __webpack_require__(39);
+ var toLength = __webpack_require__(38);
+ var toIndex = __webpack_require__(227);
+ var gOPN = __webpack_require__(50).f;
+ var dP = __webpack_require__(12).f;
+ var arrayFill = __webpack_require__(190);
+ var setToStringTag = __webpack_require__(25);
+ var ARRAY_BUFFER = 'ArrayBuffer';
+ var DATA_VIEW = 'DataView';
+ var PROTOTYPE = 'prototype';
+ var WRONG_LENGTH = 'Wrong length!';
+ var WRONG_INDEX = 'Wrong index!';
+ var $ArrayBuffer = global[ARRAY_BUFFER];
+ var $DataView = global[DATA_VIEW];
+ var Math = global.Math;
+ var RangeError = global.RangeError;
+ // eslint-disable-next-line no-shadow-restricted-names
+ var Infinity = global.Infinity;
+ var BaseBuffer = $ArrayBuffer;
+ var abs = Math.abs;
+ var pow = Math.pow;
+ var floor = Math.floor;
+ var log = Math.log;
+ var LN2 = Math.LN2;
+ var BUFFER = 'buffer';
+ var BYTE_LENGTH = 'byteLength';
+ var BYTE_OFFSET = 'byteOffset';
+ var $BUFFER = DESCRIPTORS ? '_b' : BUFFER;
+ var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH;
+ var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
- var packIEEE754 = function(value, mLen, nBytes){
- var buffer = Array(nBytes)
- , eLen = nBytes * 8 - mLen - 1
- , eMax = (1 << eLen) - 1
- , eBias = eMax >> 1
- , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
- , i = 0
- , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
- , e, m, c;
- value = abs(value)
- if(value != value || value === Infinity){
+ function packIEEE754(value, mLen, nBytes) {
+ var buffer = Array(nBytes);
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0;
+ var i = 0;
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
+ var e, m, c;
+ value = abs(value);
+ // eslint-disable-next-line no-self-compare
+ if (value != value || value === Infinity) {
+ // eslint-disable-next-line no-self-compare
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
- if(value * (c = pow(2, -e)) < 1){
+ if (value * (c = pow(2, -e)) < 1) {
e--;
c *= 2;
}
- if(e + eBias >= 1){
+ if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
- if(value * c >= 2){
+ if (value * c >= 2) {
e++;
c /= 2;
}
- if(e + eBias >= eMax){
+ if (e + eBias >= eMax) {
m = 0;
e = eMax;
- } else if(e + eBias >= 1){
+ } else if (e + eBias >= 1) {
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
@@ -5361,109 +5689,102 @@ return /******/ (function(modules) { // webpackBootstrap
e = 0;
}
}
- for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
+ for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
- for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
+ for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
- };
- var unpackIEEE754 = function(buffer, mLen, nBytes){
- var eLen = nBytes * 8 - mLen - 1
- , eMax = (1 << eLen) - 1
- , eBias = eMax >> 1
- , nBits = eLen - 7
- , i = nBytes - 1
- , s = buffer[i--]
- , e = s & 127
- , m;
+ }
+ function unpackIEEE754(buffer, mLen, nBytes) {
+ var eLen = nBytes * 8 - mLen - 1;
+ var eMax = (1 << eLen) - 1;
+ var eBias = eMax >> 1;
+ var nBits = eLen - 7;
+ var i = nBytes - 1;
+ var s = buffer[i--];
+ var e = s & 127;
+ var m;
s >>= 7;
- for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
+ for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
- for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
- if(e === 0){
+ for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
+ if (e === 0) {
e = 1 - eBias;
- } else if(e === eMax){
+ } else if (e === eMax) {
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
- };
+ }
- var unpackI32 = function(bytes){
+ function unpackI32(bytes) {
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
- };
- var packI8 = function(it){
+ }
+ function packI8(it) {
return [it & 0xff];
- };
- var packI16 = function(it){
+ }
+ function packI16(it) {
return [it & 0xff, it >> 8 & 0xff];
- };
- var packI32 = function(it){
+ }
+ function packI32(it) {
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
- };
- var packF64 = function(it){
+ }
+ function packF64(it) {
return packIEEE754(it, 52, 8);
- };
- var packF32 = function(it){
+ }
+ function packF32(it) {
return packIEEE754(it, 23, 4);
- };
+ }
- var addGetter = function(C, key, internal){
- dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
- };
+ function addGetter(C, key, internal) {
+ dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } });
+ }
- var get = function(view, bytes, index, isLittleEndian){
- var numIndex = +index
- , intIndex = toInteger(numIndex);
- if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
- var store = view[$BUFFER]._b
- , start = intIndex + view[$OFFSET]
- , pack = store.slice(start, start + bytes);
+ function get(view, bytes, index, isLittleEndian) {
+ var numIndex = +index;
+ var intIndex = toIndex(numIndex);
+ if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
+ var store = view[$BUFFER]._b;
+ var start = intIndex + view[$OFFSET];
+ var pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
- };
- var set = function(view, bytes, index, conversion, value, isLittleEndian){
- var numIndex = +index
- , intIndex = toInteger(numIndex);
- if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
- var store = view[$BUFFER]._b
- , start = intIndex + view[$OFFSET]
- , pack = conversion(+value);
- for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
- };
-
- var validateArrayBufferArguments = function(that, length){
- anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
- var numberLength = +length
- , byteLength = toLength(numberLength);
- if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
- return byteLength;
- };
-
- if(!$typed.ABV){
- $ArrayBuffer = function ArrayBuffer(length){
- var byteLength = validateArrayBufferArguments(this, length);
- this._b = arrayFill.call(Array(byteLength), 0);
+ }
+ function set(view, bytes, index, conversion, value, isLittleEndian) {
+ var numIndex = +index;
+ var intIndex = toIndex(numIndex);
+ if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
+ var store = view[$BUFFER]._b;
+ var start = intIndex + view[$OFFSET];
+ var pack = conversion(+value);
+ for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
+ }
+
+ if (!$typed.ABV) {
+ $ArrayBuffer = function ArrayBuffer(length) {
+ anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
+ var byteLength = toIndex(length);
+ this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
- $DataView = function DataView(buffer, byteOffset, byteLength){
+ $DataView = function DataView(buffer, byteOffset, byteLength) {
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
- var bufferLength = buffer[$LENGTH]
- , offset = toInteger(byteOffset);
- if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
+ var bufferLength = buffer[$LENGTH];
+ var offset = toInteger(byteOffset);
+ if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
- if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
+ if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
- if(DESCRIPTORS){
+ if (DESCRIPTORS) {
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
@@ -5471,82 +5792,88 @@ return /******/ (function(modules) { // webpackBootstrap
}
redefineAll($DataView[PROTOTYPE], {
- getInt8: function getInt8(byteOffset){
+ getInt8: function getInt8(byteOffset) {
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
- getUint8: function getUint8(byteOffset){
+ getUint8: function getUint8(byteOffset) {
return get(this, 1, byteOffset)[0];
},
- getInt16: function getInt16(byteOffset /*, littleEndian */){
+ getInt16: function getInt16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
- getUint16: function getUint16(byteOffset /*, littleEndian */){
+ getUint16: function getUint16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
- getInt32: function getInt32(byteOffset /*, littleEndian */){
+ getInt32: function getInt32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
- getUint32: function getUint32(byteOffset /*, littleEndian */){
+ getUint32: function getUint32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
- getFloat32: function getFloat32(byteOffset /*, littleEndian */){
+ getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
- getFloat64: function getFloat64(byteOffset /*, littleEndian */){
+ getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
- setInt8: function setInt8(byteOffset, value){
+ setInt8: function setInt8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
- setUint8: function setUint8(byteOffset, value){
+ setUint8: function setUint8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
- setInt16: function setInt16(byteOffset, value /*, littleEndian */){
+ setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
- setUint16: function setUint16(byteOffset, value /*, littleEndian */){
+ setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
- setInt32: function setInt32(byteOffset, value /*, littleEndian */){
+ setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
- setUint32: function setUint32(byteOffset, value /*, littleEndian */){
+ setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
- setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
+ setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
- setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
+ setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
- if(!fails(function(){
- new $ArrayBuffer; // eslint-disable-line no-new
- }) || !fails(function(){
- new $ArrayBuffer(.5); // eslint-disable-line no-new
- })){
- $ArrayBuffer = function ArrayBuffer(length){
- return new BaseBuffer(validateArrayBufferArguments(this, length));
+ if (!fails(function () {
+ $ArrayBuffer(1);
+ }) || !fails(function () {
+ new $ArrayBuffer(-1); // eslint-disable-line no-new
+ }) || fails(function () {
+ new $ArrayBuffer(); // eslint-disable-line no-new
+ new $ArrayBuffer(1.5); // eslint-disable-line no-new
+ new $ArrayBuffer(NaN); // eslint-disable-line no-new
+ return $ArrayBuffer.name != ARRAY_BUFFER;
+ })) {
+ $ArrayBuffer = function ArrayBuffer(length) {
+ anInstance(this, $ArrayBuffer);
+ return new BaseBuffer(toIndex(length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
- for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
- if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
- };
- if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
+ for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) {
+ if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]);
+ }
+ if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
- var view = new $DataView(new $ArrayBuffer(2))
- , $setInt8 = $DataView[PROTOTYPE].setInt8;
+ var view = new $DataView(new $ArrayBuffer(2));
+ var $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
- if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
- setInt8: function setInt8(byteOffset, value){
+ if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
+ setInt8: function setInt8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
- setUint8: function setUint8(byteOffset, value){
+ setUint8: function setUint8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
@@ -5557,311 +5884,323 @@ return /******/ (function(modules) { // webpackBootstrap
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
+
/***/ }),
-/* 222 */
+/* 227 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://tc39.github.io/ecma262/#sec-toindex
+ var toInteger = __webpack_require__(39);
+ var toLength = __webpack_require__(38);
+ module.exports = function (it) {
+ if (it === undefined) return 0;
+ var number = toInteger(it);
+ var length = toLength(number);
+ if (number !== length) throw RangeError('Wrong length!');
+ return length;
+ };
+
+
+/***/ }),
+/* 228 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(9);
- $export($export.G + $export.W + $export.F * !__webpack_require__(220).ABV, {
- DataView: __webpack_require__(221).DataView
+ $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, {
+ DataView: __webpack_require__(226).DataView
});
+
/***/ }),
-/* 223 */
+/* 229 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Int8', 1, function(init){
- return function Int8Array(data, byteOffset, length){
+ __webpack_require__(230)('Int8', 1, function (init) {
+ return function Int8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 224 */
+/* 230 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- if(__webpack_require__(7)){
- var LIBRARY = __webpack_require__(29)
- , global = __webpack_require__(5)
- , fails = __webpack_require__(8)
- , $export = __webpack_require__(9)
- , $typed = __webpack_require__(220)
- , $buffer = __webpack_require__(221)
- , ctx = __webpack_require__(21)
- , anInstance = __webpack_require__(206)
- , propertyDesc = __webpack_require__(18)
- , hide = __webpack_require__(11)
- , redefineAll = __webpack_require__(211)
- , toInteger = __webpack_require__(39)
- , toLength = __webpack_require__(38)
- , toIndex = __webpack_require__(40)
- , toPrimitive = __webpack_require__(17)
- , has = __webpack_require__(6)
- , same = __webpack_require__(72)
- , classof = __webpack_require__(76)
- , isObject = __webpack_require__(14)
- , toObject = __webpack_require__(59)
- , isArrayIter = __webpack_require__(163)
- , create = __webpack_require__(47)
- , getPrototypeOf = __webpack_require__(60)
- , gOPN = __webpack_require__(51).f
- , getIterFn = __webpack_require__(165)
- , uid = __webpack_require__(20)
- , wks = __webpack_require__(26)
- , createArrayMethod = __webpack_require__(173)
- , createArrayIncludes = __webpack_require__(37)
- , speciesConstructor = __webpack_require__(208)
- , ArrayIterators = __webpack_require__(194)
- , Iterators = __webpack_require__(130)
- , $iterDetect = __webpack_require__(166)
- , setSpecies = __webpack_require__(193)
- , arrayFill = __webpack_require__(189)
- , arrayCopyWithin = __webpack_require__(186)
- , $DP = __webpack_require__(12)
- , $GOPD = __webpack_require__(52)
- , dP = $DP.f
- , gOPD = $GOPD.f
- , RangeError = global.RangeError
- , TypeError = global.TypeError
- , Uint8Array = global.Uint8Array
- , ARRAY_BUFFER = 'ArrayBuffer'
- , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
- , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
- , PROTOTYPE = 'prototype'
- , ArrayProto = Array[PROTOTYPE]
- , $ArrayBuffer = $buffer.ArrayBuffer
- , $DataView = $buffer.DataView
- , arrayForEach = createArrayMethod(0)
- , arrayFilter = createArrayMethod(2)
- , arraySome = createArrayMethod(3)
- , arrayEvery = createArrayMethod(4)
- , arrayFind = createArrayMethod(5)
- , arrayFindIndex = createArrayMethod(6)
- , arrayIncludes = createArrayIncludes(true)
- , arrayIndexOf = createArrayIncludes(false)
- , arrayValues = ArrayIterators.values
- , arrayKeys = ArrayIterators.keys
- , arrayEntries = ArrayIterators.entries
- , arrayLastIndexOf = ArrayProto.lastIndexOf
- , arrayReduce = ArrayProto.reduce
- , arrayReduceRight = ArrayProto.reduceRight
- , arrayJoin = ArrayProto.join
- , arraySort = ArrayProto.sort
- , arraySlice = ArrayProto.slice
- , arrayToString = ArrayProto.toString
- , arrayToLocaleString = ArrayProto.toLocaleString
- , ITERATOR = wks('iterator')
- , TAG = wks('toStringTag')
- , TYPED_CONSTRUCTOR = uid('typed_constructor')
- , DEF_CONSTRUCTOR = uid('def_constructor')
- , ALL_CONSTRUCTORS = $typed.CONSTR
- , TYPED_ARRAY = $typed.TYPED
- , VIEW = $typed.VIEW
- , WRONG_LENGTH = 'Wrong length!';
-
- var $map = createArrayMethod(1, function(O, length){
+ if (__webpack_require__(7)) {
+ var LIBRARY = __webpack_require__(29);
+ var global = __webpack_require__(5);
+ var fails = __webpack_require__(8);
+ var $export = __webpack_require__(9);
+ var $typed = __webpack_require__(225);
+ var $buffer = __webpack_require__(226);
+ var ctx = __webpack_require__(21);
+ var anInstance = __webpack_require__(207);
+ var propertyDesc = __webpack_require__(18);
+ var hide = __webpack_require__(11);
+ var redefineAll = __webpack_require__(215);
+ var toInteger = __webpack_require__(39);
+ var toLength = __webpack_require__(38);
+ var toIndex = __webpack_require__(227);
+ var toAbsoluteIndex = __webpack_require__(40);
+ var toPrimitive = __webpack_require__(17);
+ var has = __webpack_require__(6);
+ var classof = __webpack_require__(75);
+ var isObject = __webpack_require__(14);
+ var toObject = __webpack_require__(58);
+ var isArrayIter = __webpack_require__(164);
+ var create = __webpack_require__(46);
+ var getPrototypeOf = __webpack_require__(59);
+ var gOPN = __webpack_require__(50).f;
+ var getIterFn = __webpack_require__(166);
+ var uid = __webpack_require__(20);
+ var wks = __webpack_require__(26);
+ var createArrayMethod = __webpack_require__(174);
+ var createArrayIncludes = __webpack_require__(37);
+ var speciesConstructor = __webpack_require__(209);
+ var ArrayIterators = __webpack_require__(195);
+ var Iterators = __webpack_require__(130);
+ var $iterDetect = __webpack_require__(167);
+ var setSpecies = __webpack_require__(194);
+ var arrayFill = __webpack_require__(190);
+ var arrayCopyWithin = __webpack_require__(187);
+ var $DP = __webpack_require__(12);
+ var $GOPD = __webpack_require__(51);
+ var dP = $DP.f;
+ var gOPD = $GOPD.f;
+ var RangeError = global.RangeError;
+ var TypeError = global.TypeError;
+ var Uint8Array = global.Uint8Array;
+ var ARRAY_BUFFER = 'ArrayBuffer';
+ var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;
+ var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
+ var PROTOTYPE = 'prototype';
+ var ArrayProto = Array[PROTOTYPE];
+ var $ArrayBuffer = $buffer.ArrayBuffer;
+ var $DataView = $buffer.DataView;
+ var arrayForEach = createArrayMethod(0);
+ var arrayFilter = createArrayMethod(2);
+ var arraySome = createArrayMethod(3);
+ var arrayEvery = createArrayMethod(4);
+ var arrayFind = createArrayMethod(5);
+ var arrayFindIndex = createArrayMethod(6);
+ var arrayIncludes = createArrayIncludes(true);
+ var arrayIndexOf = createArrayIncludes(false);
+ var arrayValues = ArrayIterators.values;
+ var arrayKeys = ArrayIterators.keys;
+ var arrayEntries = ArrayIterators.entries;
+ var arrayLastIndexOf = ArrayProto.lastIndexOf;
+ var arrayReduce = ArrayProto.reduce;
+ var arrayReduceRight = ArrayProto.reduceRight;
+ var arrayJoin = ArrayProto.join;
+ var arraySort = ArrayProto.sort;
+ var arraySlice = ArrayProto.slice;
+ var arrayToString = ArrayProto.toString;
+ var arrayToLocaleString = ArrayProto.toLocaleString;
+ var ITERATOR = wks('iterator');
+ var TAG = wks('toStringTag');
+ var TYPED_CONSTRUCTOR = uid('typed_constructor');
+ var DEF_CONSTRUCTOR = uid('def_constructor');
+ var ALL_CONSTRUCTORS = $typed.CONSTR;
+ var TYPED_ARRAY = $typed.TYPED;
+ var VIEW = $typed.VIEW;
+ var WRONG_LENGTH = 'Wrong length!';
+
+ var $map = createArrayMethod(1, function (O, length) {
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
- var LITTLE_ENDIAN = fails(function(){
+ var LITTLE_ENDIAN = fails(function () {
+ // eslint-disable-next-line no-undef
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
- var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
+ var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {
new Uint8Array(1).set({});
});
- var strictToLength = function(it, SAME){
- if(it === undefined)throw TypeError(WRONG_LENGTH);
- var number = +it
- , length = toLength(it);
- if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
- return length;
- };
-
- var toOffset = function(it, BYTES){
+ var toOffset = function (it, BYTES) {
var offset = toInteger(it);
- if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
+ if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');
return offset;
};
- var validate = function(it){
- if(isObject(it) && TYPED_ARRAY in it)return it;
+ var validate = function (it) {
+ if (isObject(it) && TYPED_ARRAY in it) return it;
throw TypeError(it + ' is not a typed array!');
};
- var allocate = function(C, length){
- if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
+ var allocate = function (C, length) {
+ if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
- var speciesFromList = function(O, list){
+ var speciesFromList = function (O, list) {
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
- var fromList = function(C, list){
- var index = 0
- , length = list.length
- , result = allocate(C, length);
- while(length > index)result[index] = list[index++];
+ var fromList = function (C, list) {
+ var index = 0;
+ var length = list.length;
+ var result = allocate(C, length);
+ while (length > index) result[index] = list[index++];
return result;
};
- var addGetter = function(it, key, internal){
- dP(it, key, {get: function(){ return this._d[internal]; }});
+ var addGetter = function (it, key, internal) {
+ dP(it, key, { get: function () { return this._d[internal]; } });
};
- var $from = function from(source /*, mapfn, thisArg */){
- var O = toObject(source)
- , aLen = arguments.length
- , mapfn = aLen > 1 ? arguments[1] : undefined
- , mapping = mapfn !== undefined
- , iterFn = getIterFn(O)
- , i, length, values, result, step, iterator;
- if(iterFn != undefined && !isArrayIter(iterFn)){
- for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
+ var $from = function from(source /* , mapfn, thisArg */) {
+ var O = toObject(source);
+ var aLen = arguments.length;
+ var mapfn = aLen > 1 ? arguments[1] : undefined;
+ var mapping = mapfn !== undefined;
+ var iterFn = getIterFn(O);
+ var i, length, values, result, step, iterator;
+ if (iterFn != undefined && !isArrayIter(iterFn)) {
+ for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {
values.push(step.value);
} O = values;
}
- if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
- for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
+ if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);
+ for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
- var $of = function of(/*...items*/){
- var index = 0
- , length = arguments.length
- , result = allocate(this, length);
- while(length > index)result[index] = arguments[index++];
+ var $of = function of(/* ...items */) {
+ var index = 0;
+ var length = arguments.length;
+ var result = allocate(this, length);
+ while (length > index) result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
- var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
+ var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });
- var $toLocaleString = function toLocaleString(){
+ var $toLocaleString = function toLocaleString() {
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
- copyWithin: function copyWithin(target, start /*, end */){
+ copyWithin: function copyWithin(target, start /* , end */) {
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
- every: function every(callbackfn /*, thisArg */){
+ every: function every(callbackfn /* , thisArg */) {
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
- fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
+ fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
- filter: function filter(callbackfn /*, thisArg */){
+ filter: function filter(callbackfn /* , thisArg */) {
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
- find: function find(predicate /*, thisArg */){
+ find: function find(predicate /* , thisArg */) {
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
- findIndex: function findIndex(predicate /*, thisArg */){
+ findIndex: function findIndex(predicate /* , thisArg */) {
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
- forEach: function forEach(callbackfn /*, thisArg */){
+ forEach: function forEach(callbackfn /* , thisArg */) {
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
- indexOf: function indexOf(searchElement /*, fromIndex */){
+ indexOf: function indexOf(searchElement /* , fromIndex */) {
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
- includes: function includes(searchElement /*, fromIndex */){
+ includes: function includes(searchElement /* , fromIndex */) {
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
- join: function join(separator){ // eslint-disable-line no-unused-vars
+ join: function join(separator) { // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
- lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
+ lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
- map: function map(mapfn /*, thisArg */){
+ map: function map(mapfn /* , thisArg */) {
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
- reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
+ reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
- reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
+ reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
- reverse: function reverse(){
- var that = this
- , length = validate(that).length
- , middle = Math.floor(length / 2)
- , index = 0
- , value;
- while(index < middle){
- value = that[index];
+ reverse: function reverse() {
+ var that = this;
+ var length = validate(that).length;
+ var middle = Math.floor(length / 2);
+ var index = 0;
+ var value;
+ while (index < middle) {
+ value = that[index];
that[index++] = that[--length];
- that[length] = value;
+ that[length] = value;
} return that;
},
- some: function some(callbackfn /*, thisArg */){
+ some: function some(callbackfn /* , thisArg */) {
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
- sort: function sort(comparefn){
+ sort: function sort(comparefn) {
return arraySort.call(validate(this), comparefn);
},
- subarray: function subarray(begin, end){
- var O = validate(this)
- , length = O.length
- , $begin = toIndex(begin, length);
+ subarray: function subarray(begin, end) {
+ var O = validate(this);
+ var length = O.length;
+ var $begin = toAbsoluteIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
- toLength((end === undefined ? length : toIndex(end, length)) - $begin)
+ toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)
);
}
};
- var $slice = function slice(start, end){
+ var $slice = function slice(start, end) {
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
- var $set = function set(arrayLike /*, offset */){
+ var $set = function set(arrayLike /* , offset */) {
validate(this);
- var offset = toOffset(arguments[1], 1)
- , length = this.length
- , src = toObject(arrayLike)
- , len = toLength(src.length)
- , index = 0;
- if(len + offset > length)throw RangeError(WRONG_LENGTH);
- while(index < len)this[offset + index] = src[index++];
+ var offset = toOffset(arguments[1], 1);
+ var length = this.length;
+ var src = toObject(arrayLike);
+ var len = toLength(src.length);
+ var index = 0;
+ if (len + offset > length) throw RangeError(WRONG_LENGTH);
+ while (index < len) this[offset + index] = src[index++];
};
var $iterators = {
- entries: function entries(){
+ entries: function entries() {
return arrayEntries.call(validate(this));
},
- keys: function keys(){
+ keys: function keys() {
return arrayKeys.call(validate(this));
},
- values: function values(){
+ values: function values() {
return arrayValues.call(validate(this));
}
};
- var isTAIndex = function(target, key){
+ var isTAIndex = function (target, key) {
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
- var $getDesc = function getOwnPropertyDescriptor(target, key){
+ var $getDesc = function getOwnPropertyDescriptor(target, key) {
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
- var $setDesc = function defineProperty(target, key, desc){
- if(isTAIndex(target, key = toPrimitive(key, true))
+ var $setDesc = function defineProperty(target, key, desc) {
+ if (isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
@@ -5870,36 +6209,36 @@ return /******/ (function(modules) { // webpackBootstrap
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
- ){
+ ) {
target[key] = desc.value;
return target;
- } else return dP(target, key, desc);
+ } return dP(target, key, desc);
};
- if(!ALL_CONSTRUCTORS){
+ if (!ALL_CONSTRUCTORS) {
$GOPD.f = $getDesc;
- $DP.f = $setDesc;
+ $DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
- defineProperty: $setDesc
+ defineProperty: $setDesc
});
- if(fails(function(){ arrayToString.call({}); })){
- arrayToString = arrayToLocaleString = function toString(){
+ if (fails(function () { arrayToString.call({}); })) {
+ arrayToString = arrayToLocaleString = function toString() {
return arrayJoin.call(this);
- }
+ };
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
- slice: $slice,
- set: $set,
- constructor: function(){ /* noop */ },
- toString: arrayToString,
+ slice: $slice,
+ set: $set,
+ constructor: function () { /* noop */ },
+ toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
@@ -5907,65 +6246,65 @@ return /******/ (function(modules) { // webpackBootstrap
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
- get: function(){ return this[TYPED_ARRAY]; }
+ get: function () { return this[TYPED_ARRAY]; }
});
- module.exports = function(KEY, BYTES, wrapper, CLAMPED){
+ // eslint-disable-next-line max-statements
+ module.exports = function (KEY, BYTES, wrapper, CLAMPED) {
CLAMPED = !!CLAMPED;
- var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
- , ISNT_UINT8 = NAME != 'Uint8Array'
- , GETTER = 'get' + KEY
- , SETTER = 'set' + KEY
- , TypedArray = global[NAME]
- , Base = TypedArray || {}
- , TAC = TypedArray && getPrototypeOf(TypedArray)
- , FORCED = !TypedArray || !$typed.ABV
- , O = {}
- , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
- var getter = function(that, index){
+ var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';
+ var GETTER = 'get' + KEY;
+ var SETTER = 'set' + KEY;
+ var TypedArray = global[NAME];
+ var Base = TypedArray || {};
+ var TAC = TypedArray && getPrototypeOf(TypedArray);
+ var FORCED = !TypedArray || !$typed.ABV;
+ var O = {};
+ var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
+ var getter = function (that, index) {
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
- var setter = function(that, index, value){
+ var setter = function (that, index, value) {
var data = that._d;
- if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
+ if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
- var addElement = function(that, index){
+ var addElement = function (that, index) {
dP(that, index, {
- get: function(){
+ get: function () {
return getter(this, index);
},
- set: function(value){
+ set: function (value) {
return setter(this, index, value);
},
enumerable: true
});
};
- if(FORCED){
- TypedArray = wrapper(function(that, data, $offset, $length){
+ if (FORCED) {
+ TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME, '_d');
- var index = 0
- , offset = 0
- , buffer, byteLength, length, klass;
- if(!isObject(data)){
- length = strictToLength(data, true)
+ var index = 0;
+ var offset = 0;
+ var buffer, byteLength, length, klass;
+ if (!isObject(data)) {
+ length = toIndex(data);
byteLength = length * BYTES;
- buffer = new $ArrayBuffer(byteLength);
- } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
+ buffer = new $ArrayBuffer(byteLength);
+ } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
- if($length === undefined){
- if($len % BYTES)throw RangeError(WRONG_LENGTH);
+ if ($length === undefined) {
+ if ($len % BYTES) throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
- if(byteLength < 0)throw RangeError(WRONG_LENGTH);
+ if (byteLength < 0) throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
- if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
+ if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
- } else if(TYPED_ARRAY in data){
+ } else if (TYPED_ARRAY in data) {
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
@@ -5977,49 +6316,54 @@ return /******/ (function(modules) { // webpackBootstrap
e: length,
v: new $DataView(buffer)
});
- while(index < length)addElement(that, index++);
+ while (index < length) addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
- } else if(!$iterDetect(function(iter){
- // V8 works with iterators, but fails in many other cases
- // https://code.google.com/p/v8/issues/detail?id=4552
+ } else if (!fails(function () {
+ TypedArray(1);
+ }) || !fails(function () {
+ new TypedArray(-1); // eslint-disable-line no-new
+ }) || !$iterDetect(function (iter) {
+ new TypedArray(); // eslint-disable-line no-new
new TypedArray(null); // eslint-disable-line no-new
+ new TypedArray(1.5); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
- }, true)){
- TypedArray = wrapper(function(that, data, $offset, $length){
+ }, true)) {
+ TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
- if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
- if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
+ if (!isObject(data)) return new Base(toIndex(data));
+ if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
- if(TYPED_ARRAY in data)return fromList(TypedArray, data);
+ if (TYPED_ARRAY in data) return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
- arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
- if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
+ arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {
+ if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
- if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
+ if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;
}
- var $nativeIterator = TypedArrayPrototype[ITERATOR]
- , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
- , $iterator = $iterators.values;
+ var $nativeIterator = TypedArrayPrototype[ITERATOR];
+ var CORRECT_ITER_NAME = !!$nativeIterator
+ && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);
+ var $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
- if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
+ if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {
dP(TypedArrayPrototype, TAG, {
- get: function(){ return NAME; }
+ get: function () { return NAME; }
});
}
@@ -6028,173 +6372,186 @@ return /******/ (function(modules) { // webpackBootstrap
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
- BYTES_PER_ELEMENT: BYTES,
+ BYTES_PER_ELEMENT: BYTES
+ });
+
+ $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {
from: $from,
of: $of
});
- if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
+ if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
- $export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
+ $export($export.P + $export.F * FORCED_SET, NAME, { set: $set });
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
- $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
+ if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;
- $export($export.P + $export.F * fails(function(){
+ $export($export.P + $export.F * fails(function () {
new TypedArray(1).slice();
- }), NAME, {slice: $slice});
+ }), NAME, { slice: $slice });
- $export($export.P + $export.F * (fails(function(){
- return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
- }) || !fails(function(){
+ $export($export.P + $export.F * (fails(function () {
+ return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();
+ }) || !fails(function () {
TypedArrayPrototype.toLocaleString.call([1, 2]);
- })), NAME, {toLocaleString: $toLocaleString});
+ })), NAME, { toLocaleString: $toLocaleString });
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
- if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
+ if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);
};
- } else module.exports = function(){ /* empty */ };
+ } else module.exports = function () { /* empty */ };
+
/***/ }),
-/* 225 */
+/* 231 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Uint8', 1, function(init){
- return function Uint8Array(data, byteOffset, length){
+ __webpack_require__(230)('Uint8', 1, function (init) {
+ return function Uint8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 226 */
+/* 232 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Uint8', 1, function(init){
- return function Uint8ClampedArray(data, byteOffset, length){
+ __webpack_require__(230)('Uint8', 1, function (init) {
+ return function Uint8ClampedArray(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
}, true);
+
/***/ }),
-/* 227 */
+/* 233 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Int16', 2, function(init){
- return function Int16Array(data, byteOffset, length){
+ __webpack_require__(230)('Int16', 2, function (init) {
+ return function Int16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 228 */
+/* 234 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Uint16', 2, function(init){
- return function Uint16Array(data, byteOffset, length){
+ __webpack_require__(230)('Uint16', 2, function (init) {
+ return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 229 */
+/* 235 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Int32', 4, function(init){
- return function Int32Array(data, byteOffset, length){
+ __webpack_require__(230)('Int32', 4, function (init) {
+ return function Int32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 230 */
+/* 236 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Uint32', 4, function(init){
- return function Uint32Array(data, byteOffset, length){
+ __webpack_require__(230)('Uint32', 4, function (init) {
+ return function Uint32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 231 */
+/* 237 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Float32', 4, function(init){
- return function Float32Array(data, byteOffset, length){
+ __webpack_require__(230)('Float32', 4, function (init) {
+ return function Float32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 232 */
+/* 238 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(224)('Float64', 8, function(init){
- return function Float64Array(data, byteOffset, length){
+ __webpack_require__(230)('Float64', 8, function (init) {
+ return function Float64Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
+
/***/ }),
-/* 233 */
+/* 239 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
- var $export = __webpack_require__(9)
- , aFunction = __webpack_require__(22)
- , anObject = __webpack_require__(13)
- , rApply = (__webpack_require__(5).Reflect || {}).apply
- , fApply = Function.apply;
+ var $export = __webpack_require__(9);
+ var aFunction = __webpack_require__(22);
+ var anObject = __webpack_require__(13);
+ var rApply = (__webpack_require__(5).Reflect || {}).apply;
+ var fApply = Function.apply;
// MS Edge argumentsList argument is optional
- $export($export.S + $export.F * !__webpack_require__(8)(function(){
- rApply(function(){});
+ $export($export.S + $export.F * !__webpack_require__(8)(function () {
+ rApply(function () { /* empty */ });
}), 'Reflect', {
- apply: function apply(target, thisArgument, argumentsList){
- var T = aFunction(target)
- , L = anObject(argumentsList);
+ apply: function apply(target, thisArgument, argumentsList) {
+ var T = aFunction(target);
+ var L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
+
/***/ }),
-/* 234 */
+/* 240 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
- var $export = __webpack_require__(9)
- , create = __webpack_require__(47)
- , aFunction = __webpack_require__(22)
- , anObject = __webpack_require__(13)
- , isObject = __webpack_require__(14)
- , fails = __webpack_require__(8)
- , bind = __webpack_require__(78)
- , rConstruct = (__webpack_require__(5).Reflect || {}).construct;
+ var $export = __webpack_require__(9);
+ var create = __webpack_require__(46);
+ var aFunction = __webpack_require__(22);
+ var anObject = __webpack_require__(13);
+ var isObject = __webpack_require__(14);
+ var fails = __webpack_require__(8);
+ var bind = __webpack_require__(77);
+ var rConstruct = (__webpack_require__(5).Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
- var NEW_TARGET_BUG = fails(function(){
- function F(){}
- return !(rConstruct(function(){}, [], F) instanceof F);
+ var NEW_TARGET_BUG = fails(function () {
+ function F() { /* empty */ }
+ return !(rConstruct(function () { /* empty */ }, [], F) instanceof F);
});
- var ARGS_BUG = !fails(function(){
- rConstruct(function(){});
+ var ARGS_BUG = !fails(function () {
+ rConstruct(function () { /* empty */ });
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
- construct: function construct(Target, args /*, newTarget*/){
+ construct: function construct(Target, args /* , newTarget */) {
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
- if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget);
- if(Target == newTarget){
+ if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget);
+ if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
- switch(args.length){
- case 0: return new Target;
+ switch (args.length) {
+ case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
@@ -6203,246 +6560,259 @@ return /******/ (function(modules) { // webpackBootstrap
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
- return new (bind.apply(Target, $args));
+ return new (bind.apply(Target, $args))();
}
// with altered newTarget, not support built-in constructors
- var proto = newTarget.prototype
- , instance = create(isObject(proto) ? proto : Object.prototype)
- , result = Function.apply.call(Target, instance, args);
+ var proto = newTarget.prototype;
+ var instance = create(isObject(proto) ? proto : Object.prototype);
+ var result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
+
/***/ }),
-/* 235 */
+/* 241 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
- var dP = __webpack_require__(12)
- , $export = __webpack_require__(9)
- , anObject = __webpack_require__(13)
- , toPrimitive = __webpack_require__(17);
+ var dP = __webpack_require__(12);
+ var $export = __webpack_require__(9);
+ var anObject = __webpack_require__(13);
+ var toPrimitive = __webpack_require__(17);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
- $export($export.S + $export.F * __webpack_require__(8)(function(){
- Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
+ $export($export.S + $export.F * __webpack_require__(8)(function () {
+ // eslint-disable-next-line no-undef
+ Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 });
}), 'Reflect', {
- defineProperty: function defineProperty(target, propertyKey, attributes){
+ defineProperty: function defineProperty(target, propertyKey, attributes) {
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
- } catch(e){
+ } catch (e) {
return false;
}
}
});
+
/***/ }),
-/* 236 */
+/* 242 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
- var $export = __webpack_require__(9)
- , gOPD = __webpack_require__(52).f
- , anObject = __webpack_require__(13);
+ var $export = __webpack_require__(9);
+ var gOPD = __webpack_require__(51).f;
+ var anObject = __webpack_require__(13);
$export($export.S, 'Reflect', {
- deleteProperty: function deleteProperty(target, propertyKey){
+ deleteProperty: function deleteProperty(target, propertyKey) {
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
+
/***/ }),
-/* 237 */
+/* 243 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
- var $export = __webpack_require__(9)
- , anObject = __webpack_require__(13);
- var Enumerate = function(iterated){
+ var $export = __webpack_require__(9);
+ var anObject = __webpack_require__(13);
+ var Enumerate = function (iterated) {
this._t = anObject(iterated); // target
this._i = 0; // next index
- var keys = this._k = [] // keys
- , key;
- for(key in iterated)keys.push(key);
+ var keys = this._k = []; // keys
+ var key;
+ for (key in iterated) keys.push(key);
};
- __webpack_require__(131)(Enumerate, 'Object', function(){
- var that = this
- , keys = that._k
- , key;
+ __webpack_require__(131)(Enumerate, 'Object', function () {
+ var that = this;
+ var keys = that._k;
+ var key;
do {
- if(that._i >= keys.length)return {value: undefined, done: true};
- } while(!((key = keys[that._i++]) in that._t));
- return {value: key, done: false};
+ if (that._i >= keys.length) return { value: undefined, done: true };
+ } while (!((key = keys[that._i++]) in that._t));
+ return { value: key, done: false };
});
$export($export.S, 'Reflect', {
- enumerate: function enumerate(target){
+ enumerate: function enumerate(target) {
return new Enumerate(target);
}
});
+
/***/ }),
-/* 238 */
+/* 244 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
- var gOPD = __webpack_require__(52)
- , getPrototypeOf = __webpack_require__(60)
- , has = __webpack_require__(6)
- , $export = __webpack_require__(9)
- , isObject = __webpack_require__(14)
- , anObject = __webpack_require__(13);
-
- function get(target, propertyKey/*, receiver*/){
- var receiver = arguments.length < 3 ? target : arguments[2]
- , desc, proto;
- if(anObject(target) === receiver)return target[propertyKey];
- if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
+ var gOPD = __webpack_require__(51);
+ var getPrototypeOf = __webpack_require__(59);
+ var has = __webpack_require__(6);
+ var $export = __webpack_require__(9);
+ var isObject = __webpack_require__(14);
+ var anObject = __webpack_require__(13);
+
+ function get(target, propertyKey /* , receiver */) {
+ var receiver = arguments.length < 3 ? target : arguments[2];
+ var desc, proto;
+ if (anObject(target) === receiver) return target[propertyKey];
+ if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
- if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
+ if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver);
}
- $export($export.S, 'Reflect', {get: get});
+ $export($export.S, 'Reflect', { get: get });
+
/***/ }),
-/* 239 */
+/* 245 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
- var gOPD = __webpack_require__(52)
- , $export = __webpack_require__(9)
- , anObject = __webpack_require__(13);
+ var gOPD = __webpack_require__(51);
+ var $export = __webpack_require__(9);
+ var anObject = __webpack_require__(13);
$export($export.S, 'Reflect', {
- getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
+ getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) {
return gOPD.f(anObject(target), propertyKey);
}
});
+
/***/ }),
-/* 240 */
+/* 246 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
- var $export = __webpack_require__(9)
- , getProto = __webpack_require__(60)
- , anObject = __webpack_require__(13);
+ var $export = __webpack_require__(9);
+ var getProto = __webpack_require__(59);
+ var anObject = __webpack_require__(13);
$export($export.S, 'Reflect', {
- getPrototypeOf: function getPrototypeOf(target){
+ getPrototypeOf: function getPrototypeOf(target) {
return getProto(anObject(target));
}
});
+
/***/ }),
-/* 241 */
+/* 247 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(9);
$export($export.S, 'Reflect', {
- has: function has(target, propertyKey){
+ has: function has(target, propertyKey) {
return propertyKey in target;
}
});
+
/***/ }),
-/* 242 */
+/* 248 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
- var $export = __webpack_require__(9)
- , anObject = __webpack_require__(13)
- , $isExtensible = Object.isExtensible;
+ var $export = __webpack_require__(9);
+ var anObject = __webpack_require__(13);
+ var $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
- isExtensible: function isExtensible(target){
+ isExtensible: function isExtensible(target) {
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
+
/***/ }),
-/* 243 */
+/* 249 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(9);
- $export($export.S, 'Reflect', {ownKeys: __webpack_require__(244)});
+ $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) });
+
/***/ }),
-/* 244 */
+/* 250 */
/***/ (function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
- var gOPN = __webpack_require__(51)
- , gOPS = __webpack_require__(44)
- , anObject = __webpack_require__(13)
- , Reflect = __webpack_require__(5).Reflect;
- module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
- var keys = gOPN.f(anObject(it))
- , getSymbols = gOPS.f;
+ var gOPN = __webpack_require__(50);
+ var gOPS = __webpack_require__(43);
+ var anObject = __webpack_require__(13);
+ var Reflect = __webpack_require__(5).Reflect;
+ module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
+ var keys = gOPN.f(anObject(it));
+ var getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
+
/***/ }),
-/* 245 */
+/* 251 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
- var $export = __webpack_require__(9)
- , anObject = __webpack_require__(13)
- , $preventExtensions = Object.preventExtensions;
+ var $export = __webpack_require__(9);
+ var anObject = __webpack_require__(13);
+ var $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
- preventExtensions: function preventExtensions(target){
+ preventExtensions: function preventExtensions(target) {
anObject(target);
try {
- if($preventExtensions)$preventExtensions(target);
+ if ($preventExtensions) $preventExtensions(target);
return true;
- } catch(e){
+ } catch (e) {
return false;
}
}
});
+
/***/ }),
-/* 246 */
+/* 252 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
- var dP = __webpack_require__(12)
- , gOPD = __webpack_require__(52)
- , getPrototypeOf = __webpack_require__(60)
- , has = __webpack_require__(6)
- , $export = __webpack_require__(9)
- , createDesc = __webpack_require__(18)
- , anObject = __webpack_require__(13)
- , isObject = __webpack_require__(14);
-
- function set(target, propertyKey, V/*, receiver*/){
- var receiver = arguments.length < 4 ? target : arguments[3]
- , ownDesc = gOPD.f(anObject(target), propertyKey)
- , existingDescriptor, proto;
- if(!ownDesc){
- if(isObject(proto = getPrototypeOf(target))){
+ var dP = __webpack_require__(12);
+ var gOPD = __webpack_require__(51);
+ var getPrototypeOf = __webpack_require__(59);
+ var has = __webpack_require__(6);
+ var $export = __webpack_require__(9);
+ var createDesc = __webpack_require__(18);
+ var anObject = __webpack_require__(13);
+ var isObject = __webpack_require__(14);
+
+ function set(target, propertyKey, V /* , receiver */) {
+ var receiver = arguments.length < 4 ? target : arguments[3];
+ var ownDesc = gOPD.f(anObject(target), propertyKey);
+ var existingDescriptor, proto;
+ if (!ownDesc) {
+ if (isObject(proto = getPrototypeOf(target))) {
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
- if(has(ownDesc, 'value')){
- if(ownDesc.writable === false || !isObject(receiver))return false;
+ if (has(ownDesc, 'value')) {
+ if (ownDesc.writable === false || !isObject(receiver)) return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
@@ -6451,378 +6821,505 @@ return /******/ (function(modules) { // webpackBootstrap
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
- $export($export.S, 'Reflect', {set: set});
+ $export($export.S, 'Reflect', { set: set });
+
/***/ }),
-/* 247 */
+/* 253 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
- var $export = __webpack_require__(9)
- , setProto = __webpack_require__(74);
+ var $export = __webpack_require__(9);
+ var setProto = __webpack_require__(73);
- if(setProto)$export($export.S, 'Reflect', {
- setPrototypeOf: function setPrototypeOf(target, proto){
+ if (setProto) $export($export.S, 'Reflect', {
+ setPrototypeOf: function setPrototypeOf(target, proto) {
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
- } catch(e){
+ } catch (e) {
return false;
}
}
});
+
/***/ }),
-/* 248 */
+/* 254 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/Array.prototype.includes
- var $export = __webpack_require__(9)
- , $includes = __webpack_require__(37)(true);
+ var $export = __webpack_require__(9);
+ var $includes = __webpack_require__(37)(true);
$export($export.P, 'Array', {
- includes: function includes(el /*, fromIndex = 0 */){
+ includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
- __webpack_require__(187)('includes');
+ __webpack_require__(188)('includes');
+
/***/ }),
-/* 249 */
+/* 255 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ 'use strict';
+ // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap
+ var $export = __webpack_require__(9);
+ var flattenIntoArray = __webpack_require__(256);
+ var toObject = __webpack_require__(58);
+ var toLength = __webpack_require__(38);
+ var aFunction = __webpack_require__(22);
+ var arraySpeciesCreate = __webpack_require__(175);
+
+ $export($export.P, 'Array', {
+ flatMap: function flatMap(callbackfn /* , thisArg */) {
+ var O = toObject(this);
+ var sourceLen, A;
+ aFunction(callbackfn);
+ sourceLen = toLength(O.length);
+ A = arraySpeciesCreate(O, 0);
+ flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]);
+ return A;
+ }
+ });
+
+ __webpack_require__(188)('flatMap');
+
+
+/***/ }),
+/* 256 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ 'use strict';
+ // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
+ var isArray = __webpack_require__(45);
+ var isObject = __webpack_require__(14);
+ var toLength = __webpack_require__(38);
+ var ctx = __webpack_require__(21);
+ var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable');
+
+ function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
+ var targetIndex = start;
+ var sourceIndex = 0;
+ var mapFn = mapper ? ctx(mapper, thisArg, 3) : false;
+ var element, spreadable;
+
+ while (sourceIndex < sourceLen) {
+ if (sourceIndex in source) {
+ element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
+
+ spreadable = false;
+ if (isObject(element)) {
+ spreadable = element[IS_CONCAT_SPREADABLE];
+ spreadable = spreadable !== undefined ? !!spreadable : isArray(element);
+ }
+
+ if (spreadable && depth > 0) {
+ targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
+ } else {
+ if (targetIndex >= 0x1fffffffffffff) throw TypeError();
+ target[targetIndex] = element;
+ }
+
+ targetIndex++;
+ }
+ sourceIndex++;
+ }
+ return targetIndex;
+ }
+
+ module.exports = flattenIntoArray;
+
+
+/***/ }),
+/* 257 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ 'use strict';
+ // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten
+ var $export = __webpack_require__(9);
+ var flattenIntoArray = __webpack_require__(256);
+ var toObject = __webpack_require__(58);
+ var toLength = __webpack_require__(38);
+ var toInteger = __webpack_require__(39);
+ var arraySpeciesCreate = __webpack_require__(175);
+
+ $export($export.P, 'Array', {
+ flatten: function flatten(/* depthArg = 1 */) {
+ var depthArg = arguments[0];
+ var O = toObject(this);
+ var sourceLen = toLength(O.length);
+ var A = arraySpeciesCreate(O, 0);
+ flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
+ return A;
+ }
+ });
+
+ __webpack_require__(188)('flatten');
+
+
+/***/ }),
+/* 258 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
- var $export = __webpack_require__(9)
- , $at = __webpack_require__(128)(true);
+ var $export = __webpack_require__(9);
+ var $at = __webpack_require__(128)(true);
$export($export.P, 'String', {
- at: function at(pos){
+ at: function at(pos) {
return $at(this, pos);
}
});
+
/***/ }),
-/* 250 */
+/* 259 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
- var $export = __webpack_require__(9)
- , $pad = __webpack_require__(251);
+ var $export = __webpack_require__(9);
+ var $pad = __webpack_require__(260);
$export($export.P, 'String', {
- padStart: function padStart(maxLength /*, fillString = ' ' */){
+ padStart: function padStart(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
+
/***/ }),
-/* 251 */
+/* 260 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
- var toLength = __webpack_require__(38)
- , repeat = __webpack_require__(92)
- , defined = __webpack_require__(36);
-
- module.exports = function(that, maxLength, fillString, left){
- var S = String(defined(that))
- , stringLength = S.length
- , fillStr = fillString === undefined ? ' ' : String(fillString)
- , intMaxLength = toLength(maxLength);
- if(intMaxLength <= stringLength || fillStr == '')return S;
- var fillLen = intMaxLength - stringLength
- , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
- if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
+ var toLength = __webpack_require__(38);
+ var repeat = __webpack_require__(91);
+ var defined = __webpack_require__(36);
+
+ module.exports = function (that, maxLength, fillString, left) {
+ var S = String(defined(that));
+ var stringLength = S.length;
+ var fillStr = fillString === undefined ? ' ' : String(fillString);
+ var intMaxLength = toLength(maxLength);
+ if (intMaxLength <= stringLength || fillStr == '') return S;
+ var fillLen = intMaxLength - stringLength;
+ var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
+ if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ }),
-/* 252 */
+/* 261 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
- var $export = __webpack_require__(9)
- , $pad = __webpack_require__(251);
+ var $export = __webpack_require__(9);
+ var $pad = __webpack_require__(260);
$export($export.P, 'String', {
- padEnd: function padEnd(maxLength /*, fillString = ' ' */){
+ padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
+
/***/ }),
-/* 253 */
+/* 262 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
- __webpack_require__(84)('trimLeft', function($trim){
- return function trimLeft(){
+ __webpack_require__(83)('trimLeft', function ($trim) {
+ return function trimLeft() {
return $trim(this, 1);
};
}, 'trimStart');
+
/***/ }),
-/* 254 */
+/* 263 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
- __webpack_require__(84)('trimRight', function($trim){
- return function trimRight(){
+ __webpack_require__(83)('trimRight', function ($trim) {
+ return function trimRight() {
return $trim(this, 2);
};
}, 'trimEnd');
+
/***/ }),
-/* 255 */
+/* 264 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
- var $export = __webpack_require__(9)
- , defined = __webpack_require__(36)
- , toLength = __webpack_require__(38)
- , isRegExp = __webpack_require__(135)
- , getFlags = __webpack_require__(197)
- , RegExpProto = RegExp.prototype;
-
- var $RegExpStringIterator = function(regexp, string){
+ var $export = __webpack_require__(9);
+ var defined = __webpack_require__(36);
+ var toLength = __webpack_require__(38);
+ var isRegExp = __webpack_require__(135);
+ var getFlags = __webpack_require__(198);
+ var RegExpProto = RegExp.prototype;
+
+ var $RegExpStringIterator = function (regexp, string) {
this._r = regexp;
this._s = string;
};
- __webpack_require__(131)($RegExpStringIterator, 'RegExp String', function next(){
+ __webpack_require__(131)($RegExpStringIterator, 'RegExp String', function next() {
var match = this._r.exec(this._s);
- return {value: match, done: match === null};
+ return { value: match, done: match === null };
});
$export($export.P, 'String', {
- matchAll: function matchAll(regexp){
+ matchAll: function matchAll(regexp) {
defined(this);
- if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
- var S = String(this)
- , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
- , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
+ if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!');
+ var S = String(this);
+ var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp);
+ var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
+
/***/ }),
-/* 256 */
+/* 265 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(28)('asyncIterator');
+
/***/ }),
-/* 257 */
+/* 266 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(28)('observable');
+
/***/ }),
-/* 258 */
+/* 267 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
- var $export = __webpack_require__(9)
- , ownKeys = __webpack_require__(244)
- , toIObject = __webpack_require__(33)
- , gOPD = __webpack_require__(52)
- , createProperty = __webpack_require__(164);
+ var $export = __webpack_require__(9);
+ var ownKeys = __webpack_require__(250);
+ var toIObject = __webpack_require__(33);
+ var gOPD = __webpack_require__(51);
+ var createProperty = __webpack_require__(165);
$export($export.S, 'Object', {
- getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
- var O = toIObject(object)
- , getDesc = gOPD.f
- , keys = ownKeys(O)
- , result = {}
- , i = 0
- , key;
- while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
+ getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
+ var O = toIObject(object);
+ var getDesc = gOPD.f;
+ var keys = ownKeys(O);
+ var result = {};
+ var i = 0;
+ var key, desc;
+ while (keys.length > i) {
+ desc = getDesc(O, key = keys[i++]);
+ if (desc !== undefined) createProperty(result, key, desc);
+ }
return result;
}
});
+
/***/ }),
-/* 259 */
+/* 268 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
- var $export = __webpack_require__(9)
- , $values = __webpack_require__(260)(false);
+ var $export = __webpack_require__(9);
+ var $values = __webpack_require__(269)(false);
$export($export.S, 'Object', {
- values: function values(it){
+ values: function values(it) {
return $values(it);
}
});
+
/***/ }),
-/* 260 */
+/* 269 */
/***/ (function(module, exports, __webpack_require__) {
- var getKeys = __webpack_require__(31)
- , toIObject = __webpack_require__(33)
- , isEnum = __webpack_require__(45).f;
- module.exports = function(isEntries){
- return function(it){
- var O = toIObject(it)
- , keys = getKeys(O)
- , length = keys.length
- , i = 0
- , result = []
- , key;
- while(length > i)if(isEnum.call(O, key = keys[i++])){
+ var getKeys = __webpack_require__(31);
+ var toIObject = __webpack_require__(33);
+ var isEnum = __webpack_require__(44).f;
+ module.exports = function (isEntries) {
+ return function (it) {
+ var O = toIObject(it);
+ var keys = getKeys(O);
+ var length = keys.length;
+ var i = 0;
+ var result = [];
+ var key;
+ while (length > i) if (isEnum.call(O, key = keys[i++])) {
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
+
/***/ }),
-/* 261 */
+/* 270 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
- var $export = __webpack_require__(9)
- , $entries = __webpack_require__(260)(true);
+ var $export = __webpack_require__(9);
+ var $entries = __webpack_require__(269)(true);
$export($export.S, 'Object', {
- entries: function entries(it){
+ entries: function entries(it) {
return $entries(it);
}
});
+
/***/ }),
-/* 262 */
+/* 271 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , aFunction = __webpack_require__(22)
- , $defineProperty = __webpack_require__(12);
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var aFunction = __webpack_require__(22);
+ var $defineProperty = __webpack_require__(12);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
- __webpack_require__(7) && $export($export.P + __webpack_require__(263), 'Object', {
- __defineGetter__: function __defineGetter__(P, getter){
- $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
+ __webpack_require__(7) && $export($export.P + __webpack_require__(272), 'Object', {
+ __defineGetter__: function __defineGetter__(P, getter) {
+ $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true });
}
});
+
/***/ }),
-/* 263 */
+/* 272 */
/***/ (function(module, exports, __webpack_require__) {
+ 'use strict';
// Forced replacement prototype accessors methods
- module.exports = __webpack_require__(29)|| !__webpack_require__(8)(function(){
+ module.exports = __webpack_require__(29) || !__webpack_require__(8)(function () {
var K = Math.random();
// In FF throws only define methods
- __defineSetter__.call(null, K, function(){ /* empty */});
+ // eslint-disable-next-line no-undef, no-useless-call
+ __defineSetter__.call(null, K, function () { /* empty */ });
delete __webpack_require__(5)[K];
});
+
/***/ }),
-/* 264 */
+/* 273 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , aFunction = __webpack_require__(22)
- , $defineProperty = __webpack_require__(12);
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var aFunction = __webpack_require__(22);
+ var $defineProperty = __webpack_require__(12);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
- __webpack_require__(7) && $export($export.P + __webpack_require__(263), 'Object', {
- __defineSetter__: function __defineSetter__(P, setter){
- $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
+ __webpack_require__(7) && $export($export.P + __webpack_require__(272), 'Object', {
+ __defineSetter__: function __defineSetter__(P, setter) {
+ $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true });
}
});
+
/***/ }),
-/* 265 */
+/* 274 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , toPrimitive = __webpack_require__(17)
- , getPrototypeOf = __webpack_require__(60)
- , getOwnPropertyDescriptor = __webpack_require__(52).f;
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var toPrimitive = __webpack_require__(17);
+ var getPrototypeOf = __webpack_require__(59);
+ var getOwnPropertyDescriptor = __webpack_require__(51).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
- __webpack_require__(7) && $export($export.P + __webpack_require__(263), 'Object', {
- __lookupGetter__: function __lookupGetter__(P){
- var O = toObject(this)
- , K = toPrimitive(P, true)
- , D;
+ __webpack_require__(7) && $export($export.P + __webpack_require__(272), 'Object', {
+ __lookupGetter__: function __lookupGetter__(P) {
+ var O = toObject(this);
+ var K = toPrimitive(P, true);
+ var D;
do {
- if(D = getOwnPropertyDescriptor(O, K))return D.get;
- } while(O = getPrototypeOf(O));
+ if (D = getOwnPropertyDescriptor(O, K)) return D.get;
+ } while (O = getPrototypeOf(O));
}
});
+
/***/ }),
-/* 266 */
+/* 275 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var $export = __webpack_require__(9)
- , toObject = __webpack_require__(59)
- , toPrimitive = __webpack_require__(17)
- , getPrototypeOf = __webpack_require__(60)
- , getOwnPropertyDescriptor = __webpack_require__(52).f;
+ var $export = __webpack_require__(9);
+ var toObject = __webpack_require__(58);
+ var toPrimitive = __webpack_require__(17);
+ var getPrototypeOf = __webpack_require__(59);
+ var getOwnPropertyDescriptor = __webpack_require__(51).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
- __webpack_require__(7) && $export($export.P + __webpack_require__(263), 'Object', {
- __lookupSetter__: function __lookupSetter__(P){
- var O = toObject(this)
- , K = toPrimitive(P, true)
- , D;
+ __webpack_require__(7) && $export($export.P + __webpack_require__(272), 'Object', {
+ __lookupSetter__: function __lookupSetter__(P) {
+ var O = toObject(this);
+ var K = toPrimitive(P, true);
+ var D;
do {
- if(D = getOwnPropertyDescriptor(O, K))return D.set;
- } while(O = getPrototypeOf(O));
+ if (D = getOwnPropertyDescriptor(O, K)) return D.set;
+ } while (O = getPrototypeOf(O));
}
});
+
/***/ }),
-/* 267 */
+/* 276 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
- var $export = __webpack_require__(9);
+ var $export = __webpack_require__(9);
- $export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(268)('Map')});
+ $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') });
+
/***/ }),
-/* 268 */
+/* 277 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
- var classof = __webpack_require__(76)
- , from = __webpack_require__(269);
- module.exports = function(NAME){
- return function toJSON(){
- if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
+ var classof = __webpack_require__(75);
+ var from = __webpack_require__(278);
+ module.exports = function (NAME) {
+ return function toJSON() {
+ if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
+
/***/ }),
-/* 269 */
+/* 278 */
/***/ (function(module, exports, __webpack_require__) {
- var forOf = __webpack_require__(207);
+ var forOf = __webpack_require__(208);
- module.exports = function(iter, ITERATOR){
+ module.exports = function (iter, ITERATOR) {
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
@@ -6830,166 +7327,471 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 270 */
+/* 279 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
- var $export = __webpack_require__(9);
-
- $export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(268)('Set')});
-
-/***/ }),
-/* 271 */
-/***/ (function(module, exports, __webpack_require__) {
-
- // https://github.com/ljharb/proposal-global
var $export = __webpack_require__(9);
- $export($export.S, 'System', {global: __webpack_require__(5)});
+ $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') });
+
/***/ }),
-/* 272 */
+/* 280 */
/***/ (function(module, exports, __webpack_require__) {
- // https://github.com/ljharb/proposal-is-error
- var $export = __webpack_require__(9)
- , cof = __webpack_require__(35);
-
- $export($export.S, 'Error', {
- isError: function isError(it){
- return cof(it) === 'Error';
- }
- });
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
+ __webpack_require__(281)('Map');
+
/***/ }),
-/* 273 */
+/* 281 */
/***/ (function(module, exports, __webpack_require__) {
- // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
+ 'use strict';
+ // https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(9);
- $export($export.S, 'Math', {
- iaddh: function iaddh(x0, x1, y0, y1){
- var $x0 = x0 >>> 0
- , $x1 = x1 >>> 0
- , $y0 = y0 >>> 0;
- return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
- }
- });
+ module.exports = function (COLLECTION) {
+ $export($export.S, COLLECTION, { of: function of() {
+ var length = arguments.length;
+ var A = Array(length);
+ while (length--) A[length] = arguments[length];
+ return new this(A);
+ } });
+ };
+
/***/ }),
-/* 274 */
+/* 282 */
/***/ (function(module, exports, __webpack_require__) {
- // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
- var $export = __webpack_require__(9);
-
- $export($export.S, 'Math', {
- isubh: function isubh(x0, x1, y0, y1){
- var $x0 = x0 >>> 0
- , $x1 = x1 >>> 0
- , $y0 = y0 >>> 0;
- return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
- }
- });
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
+ __webpack_require__(281)('Set');
+
/***/ }),
-/* 275 */
+/* 283 */
/***/ (function(module, exports, __webpack_require__) {
- // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
- var $export = __webpack_require__(9);
-
- $export($export.S, 'Math', {
- imulh: function imulh(u, v){
- var UINT16 = 0xffff
- , $u = +u
- , $v = +v
- , u0 = $u & UINT16
- , v0 = $v & UINT16
- , u1 = $u >> 16
- , v1 = $v >> 16
- , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
- return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
- }
- });
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of
+ __webpack_require__(281)('WeakMap');
+
/***/ }),
-/* 276 */
+/* 284 */
/***/ (function(module, exports, __webpack_require__) {
- // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
- var $export = __webpack_require__(9);
-
- $export($export.S, 'Math', {
- umulh: function umulh(u, v){
- var UINT16 = 0xffff
- , $u = +u
- , $v = +v
- , u0 = $u & UINT16
- , v0 = $v & UINT16
- , u1 = $u >>> 16
- , v1 = $v >>> 16
- , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
- return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
- }
- });
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of
+ __webpack_require__(281)('WeakSet');
+
/***/ }),
-/* 277 */
+/* 285 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , toMetaKey = metadata.key
- , ordinaryDefineOwnMetadata = metadata.set;
-
- metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
- ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
- }});
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
+ __webpack_require__(286)('Map');
+
/***/ }),
-/* 278 */
+/* 286 */
/***/ (function(module, exports, __webpack_require__) {
- var Map = __webpack_require__(212)
- , $export = __webpack_require__(9)
- , shared = __webpack_require__(24)('metadata')
- , store = shared.store || (shared.store = new (__webpack_require__(216)));
-
- var getOrCreateMetadataMap = function(target, targetKey, create){
- var targetMetadata = store.get(target);
- if(!targetMetadata){
- if(!create)return undefined;
- store.set(target, targetMetadata = new Map);
- }
- var keyMetadata = targetMetadata.get(targetKey);
- if(!keyMetadata){
- if(!create)return undefined;
- targetMetadata.set(targetKey, keyMetadata = new Map);
- } return keyMetadata;
- };
- var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
+ 'use strict';
+ // https://tc39.github.io/proposal-setmap-offrom/
+ var $export = __webpack_require__(9);
+ var aFunction = __webpack_require__(22);
+ var ctx = __webpack_require__(21);
+ var forOf = __webpack_require__(208);
+
+ module.exports = function (COLLECTION) {
+ $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
+ var mapFn = arguments[1];
+ var mapping, A, n, cb;
+ aFunction(this);
+ mapping = mapFn !== undefined;
+ if (mapping) aFunction(mapFn);
+ if (source == undefined) return new this();
+ A = [];
+ if (mapping) {
+ n = 0;
+ cb = ctx(mapFn, arguments[2], 2);
+ forOf(source, false, function (nextItem) {
+ A.push(cb(nextItem, n++));
+ });
+ } else {
+ forOf(source, false, A.push, A);
+ }
+ return new this(A);
+ } });
+ };
+
+
+/***/ }),
+/* 287 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
+ __webpack_require__(286)('Set');
+
+
+/***/ }),
+/* 288 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from
+ __webpack_require__(286)('WeakMap');
+
+
+/***/ }),
+/* 289 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from
+ __webpack_require__(286)('WeakSet');
+
+
+/***/ }),
+/* 290 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://github.com/tc39/proposal-global
+ var $export = __webpack_require__(9);
+
+ $export($export.G, { global: __webpack_require__(5) });
+
+
+/***/ }),
+/* 291 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://github.com/tc39/proposal-global
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'System', { global: __webpack_require__(5) });
+
+
+/***/ }),
+/* 292 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://github.com/ljharb/proposal-is-error
+ var $export = __webpack_require__(9);
+ var cof = __webpack_require__(35);
+
+ $export($export.S, 'Error', {
+ isError: function isError(it) {
+ return cof(it) === 'Error';
+ }
+ });
+
+
+/***/ }),
+/* 293 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', {
+ clamp: function clamp(x, lower, upper) {
+ return Math.min(upper, Math.max(lower, x));
+ }
+ });
+
+
+/***/ }),
+/* 294 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 });
+
+
+/***/ }),
+/* 295 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+ var RAD_PER_DEG = 180 / Math.PI;
+
+ $export($export.S, 'Math', {
+ degrees: function degrees(radians) {
+ return radians * RAD_PER_DEG;
+ }
+ });
+
+
+/***/ }),
+/* 296 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+ var scale = __webpack_require__(297);
+ var fround = __webpack_require__(114);
+
+ $export($export.S, 'Math', {
+ fscale: function fscale(x, inLow, inHigh, outLow, outHigh) {
+ return fround(scale(x, inLow, inHigh, outLow, outHigh));
+ }
+ });
+
+
+/***/ }),
+/* 297 */
+/***/ (function(module, exports) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) {
+ if (
+ arguments.length === 0
+ // eslint-disable-next-line no-self-compare
+ || x != x
+ // eslint-disable-next-line no-self-compare
+ || inLow != inLow
+ // eslint-disable-next-line no-self-compare
+ || inHigh != inHigh
+ // eslint-disable-next-line no-self-compare
+ || outLow != outLow
+ // eslint-disable-next-line no-self-compare
+ || outHigh != outHigh
+ ) return NaN;
+ if (x === Infinity || x === -Infinity) return x;
+ return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
+ };
+
+
+/***/ }),
+/* 298 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', {
+ iaddh: function iaddh(x0, x1, y0, y1) {
+ var $x0 = x0 >>> 0;
+ var $x1 = x1 >>> 0;
+ var $y0 = y0 >>> 0;
+ return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
+ }
+ });
+
+
+/***/ }),
+/* 299 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', {
+ isubh: function isubh(x0, x1, y0, y1) {
+ var $x0 = x0 >>> 0;
+ var $x1 = x1 >>> 0;
+ var $y0 = y0 >>> 0;
+ return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
+ }
+ });
+
+
+/***/ }),
+/* 300 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', {
+ imulh: function imulh(u, v) {
+ var UINT16 = 0xffff;
+ var $u = +u;
+ var $v = +v;
+ var u0 = $u & UINT16;
+ var v0 = $v & UINT16;
+ var u1 = $u >> 16;
+ var v1 = $v >> 16;
+ var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
+ return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
+ }
+ });
+
+
+/***/ }),
+/* 301 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI });
+
+
+/***/ }),
+/* 302 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+ var DEG_PER_RAD = Math.PI / 180;
+
+ $export($export.S, 'Math', {
+ radians: function radians(degrees) {
+ return degrees * DEG_PER_RAD;
+ }
+ });
+
+
+/***/ }),
+/* 303 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://rwaldron.github.io/proposal-math-extensions/
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', { scale: __webpack_require__(297) });
+
+
+/***/ }),
+/* 304 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', {
+ umulh: function umulh(u, v) {
+ var UINT16 = 0xffff;
+ var $u = +u;
+ var $v = +v;
+ var u0 = $u & UINT16;
+ var v0 = $v & UINT16;
+ var u1 = $u >>> 16;
+ var v1 = $v >>> 16;
+ var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
+ return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
+ }
+ });
+
+
+/***/ }),
+/* 305 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // http://jfbastien.github.io/papers/Math.signbit.html
+ var $export = __webpack_require__(9);
+
+ $export($export.S, 'Math', { signbit: function signbit(x) {
+ // eslint-disable-next-line no-self-compare
+ return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0;
+ } });
+
+
+/***/ }),
+/* 306 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // https://github.com/tc39/proposal-promise-finally
+ 'use strict';
+ var $export = __webpack_require__(9);
+ var core = __webpack_require__(10);
+ var global = __webpack_require__(5);
+ var speciesConstructor = __webpack_require__(209);
+ var promiseResolve = __webpack_require__(214);
+
+ $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
+ var C = speciesConstructor(this, core.Promise || global.Promise);
+ var isFunction = typeof onFinally == 'function';
+ return this.then(
+ isFunction ? function (x) {
+ return promiseResolve(C, onFinally()).then(function () { return x; });
+ } : onFinally,
+ isFunction ? function (e) {
+ return promiseResolve(C, onFinally()).then(function () { throw e; });
+ } : onFinally
+ );
+ } });
+
+
+/***/ }),
+/* 307 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ 'use strict';
+ // https://github.com/tc39/proposal-promise-try
+ var $export = __webpack_require__(9);
+ var newPromiseCapability = __webpack_require__(212);
+ var perform = __webpack_require__(213);
+
+ $export($export.S, 'Promise', { 'try': function (callbackfn) {
+ var promiseCapability = newPromiseCapability.f(this);
+ var result = perform(callbackfn);
+ (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
+ return promiseCapability.promise;
+ } });
+
+
+/***/ }),
+/* 308 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var toMetaKey = metadata.key;
+ var ordinaryDefineOwnMetadata = metadata.set;
+
+ metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) {
+ ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
+ } });
+
+
+/***/ }),
+/* 309 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ var Map = __webpack_require__(216);
+ var $export = __webpack_require__(9);
+ var shared = __webpack_require__(24)('metadata');
+ var store = shared.store || (shared.store = new (__webpack_require__(221))());
+
+ var getOrCreateMetadataMap = function (target, targetKey, create) {
+ var targetMetadata = store.get(target);
+ if (!targetMetadata) {
+ if (!create) return undefined;
+ store.set(target, targetMetadata = new Map());
+ }
+ var keyMetadata = targetMetadata.get(targetKey);
+ if (!keyMetadata) {
+ if (!create) return undefined;
+ targetMetadata.set(targetKey, keyMetadata = new Map());
+ } return keyMetadata;
+ };
+ var ordinaryHasOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
- var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
+ var ordinaryGetOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
- var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
+ var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
- var ordinaryOwnMetadataKeys = function(target, targetKey){
- var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
- , keys = [];
- if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
+ var ordinaryOwnMetadataKeys = function (target, targetKey) {
+ var metadataMap = getOrCreateMetadataMap(target, targetKey, false);
+ var keys = [];
+ if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });
return keys;
};
- var toMetaKey = function(it){
+ var toMetaKey = function (it) {
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
- var exp = function(O){
+ var exp = function (O) {
$export($export.S, 'Reflect', O);
};
@@ -7004,249 +7806,259 @@ return /******/ (function(modules) { // webpackBootstrap
exp: exp
};
+
/***/ }),
-/* 279 */
+/* 310 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , toMetaKey = metadata.key
- , getOrCreateMetadataMap = metadata.map
- , store = metadata.store;
-
- metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
- var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
- , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
- if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
- if(metadataMap.size)return true;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var toMetaKey = metadata.key;
+ var getOrCreateMetadataMap = metadata.map;
+ var store = metadata.store;
+
+ metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) {
+ var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]);
+ var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
+ if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false;
+ if (metadataMap.size) return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
- }});
+ } });
+
/***/ }),
-/* 280 */
+/* 311 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , getPrototypeOf = __webpack_require__(60)
- , ordinaryHasOwnMetadata = metadata.has
- , ordinaryGetOwnMetadata = metadata.get
- , toMetaKey = metadata.key;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var getPrototypeOf = __webpack_require__(59);
+ var ordinaryHasOwnMetadata = metadata.has;
+ var ordinaryGetOwnMetadata = metadata.get;
+ var toMetaKey = metadata.key;
- var ordinaryGetMetadata = function(MetadataKey, O, P){
+ var ordinaryGetMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
- if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
+ if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
- metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
+ metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
- }});
+ } });
+
/***/ }),
-/* 281 */
+/* 312 */
/***/ (function(module, exports, __webpack_require__) {
- var Set = __webpack_require__(215)
- , from = __webpack_require__(269)
- , metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , getPrototypeOf = __webpack_require__(60)
- , ordinaryOwnMetadataKeys = metadata.keys
- , toMetaKey = metadata.key;
-
- var ordinaryMetadataKeys = function(O, P){
- var oKeys = ordinaryOwnMetadataKeys(O, P)
- , parent = getPrototypeOf(O);
- if(parent === null)return oKeys;
- var pKeys = ordinaryMetadataKeys(parent, P);
+ var Set = __webpack_require__(220);
+ var from = __webpack_require__(278);
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var getPrototypeOf = __webpack_require__(59);
+ var ordinaryOwnMetadataKeys = metadata.keys;
+ var toMetaKey = metadata.key;
+
+ var ordinaryMetadataKeys = function (O, P) {
+ var oKeys = ordinaryOwnMetadataKeys(O, P);
+ var parent = getPrototypeOf(O);
+ if (parent === null) return oKeys;
+ var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
- metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
+ metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) {
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
- }});
+ } });
+
/***/ }),
-/* 282 */
+/* 313 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , ordinaryGetOwnMetadata = metadata.get
- , toMetaKey = metadata.key;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var ordinaryGetOwnMetadata = metadata.get;
+ var toMetaKey = metadata.key;
- metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
+ metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
- }});
+ } });
+
/***/ }),
-/* 283 */
+/* 314 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , ordinaryOwnMetadataKeys = metadata.keys
- , toMetaKey = metadata.key;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var ordinaryOwnMetadataKeys = metadata.keys;
+ var toMetaKey = metadata.key;
- metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
+ metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) {
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
- }});
+ } });
+
/***/ }),
-/* 284 */
+/* 315 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , getPrototypeOf = __webpack_require__(60)
- , ordinaryHasOwnMetadata = metadata.has
- , toMetaKey = metadata.key;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var getPrototypeOf = __webpack_require__(59);
+ var ordinaryHasOwnMetadata = metadata.has;
+ var toMetaKey = metadata.key;
- var ordinaryHasMetadata = function(MetadataKey, O, P){
+ var ordinaryHasMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
- if(hasOwn)return true;
+ if (hasOwn) return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
- metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
+ metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
- }});
+ } });
+
/***/ }),
-/* 285 */
+/* 316 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , ordinaryHasOwnMetadata = metadata.has
- , toMetaKey = metadata.key;
+ var metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var ordinaryHasOwnMetadata = metadata.has;
+ var toMetaKey = metadata.key;
- metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
+ metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
- }});
+ } });
+
/***/ }),
-/* 286 */
+/* 317 */
/***/ (function(module, exports, __webpack_require__) {
- var metadata = __webpack_require__(278)
- , anObject = __webpack_require__(13)
- , aFunction = __webpack_require__(22)
- , toMetaKey = metadata.key
- , ordinaryDefineOwnMetadata = metadata.set;
+ var $metadata = __webpack_require__(309);
+ var anObject = __webpack_require__(13);
+ var aFunction = __webpack_require__(22);
+ var toMetaKey = $metadata.key;
+ var ordinaryDefineOwnMetadata = $metadata.set;
- metadata.exp({metadata: function metadata(metadataKey, metadataValue){
- return function decorator(target, targetKey){
+ $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) {
+ return function decorator(target, targetKey) {
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
- }});
+ } });
+
/***/ }),
-/* 287 */
+/* 318 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
- var $export = __webpack_require__(9)
- , microtask = __webpack_require__(210)()
- , process = __webpack_require__(5).process
- , isNode = __webpack_require__(35)(process) == 'process';
+ var $export = __webpack_require__(9);
+ var microtask = __webpack_require__(211)();
+ var process = __webpack_require__(5).process;
+ var isNode = __webpack_require__(35)(process) == 'process';
$export($export.G, {
- asap: function asap(fn){
+ asap: function asap(fn) {
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
+
/***/ }),
-/* 288 */
+/* 319 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/zenparsing/es-observable
- var $export = __webpack_require__(9)
- , global = __webpack_require__(5)
- , core = __webpack_require__(10)
- , microtask = __webpack_require__(210)()
- , OBSERVABLE = __webpack_require__(26)('observable')
- , aFunction = __webpack_require__(22)
- , anObject = __webpack_require__(13)
- , anInstance = __webpack_require__(206)
- , redefineAll = __webpack_require__(211)
- , hide = __webpack_require__(11)
- , forOf = __webpack_require__(207)
- , RETURN = forOf.RETURN;
-
- var getMethod = function(fn){
+ var $export = __webpack_require__(9);
+ var global = __webpack_require__(5);
+ var core = __webpack_require__(10);
+ var microtask = __webpack_require__(211)();
+ var OBSERVABLE = __webpack_require__(26)('observable');
+ var aFunction = __webpack_require__(22);
+ var anObject = __webpack_require__(13);
+ var anInstance = __webpack_require__(207);
+ var redefineAll = __webpack_require__(215);
+ var hide = __webpack_require__(11);
+ var forOf = __webpack_require__(208);
+ var RETURN = forOf.RETURN;
+
+ var getMethod = function (fn) {
return fn == null ? undefined : aFunction(fn);
};
- var cleanupSubscription = function(subscription){
+ var cleanupSubscription = function (subscription) {
var cleanup = subscription._c;
- if(cleanup){
+ if (cleanup) {
subscription._c = undefined;
cleanup();
}
};
- var subscriptionClosed = function(subscription){
+ var subscriptionClosed = function (subscription) {
return subscription._o === undefined;
};
- var closeSubscription = function(subscription){
- if(!subscriptionClosed(subscription)){
+ var closeSubscription = function (subscription) {
+ if (!subscriptionClosed(subscription)) {
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
- var Subscription = function(observer, subscriber){
+ var Subscription = function (observer, subscriber) {
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
- var cleanup = subscriber(observer)
- , subscription = cleanup;
- if(cleanup != null){
- if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
+ var cleanup = subscriber(observer);
+ var subscription = cleanup;
+ if (cleanup != null) {
+ if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
- } catch(e){
+ } catch (e) {
observer.error(e);
return;
- } if(subscriptionClosed(this))cleanupSubscription(this);
+ } if (subscriptionClosed(this)) cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
- unsubscribe: function unsubscribe(){ closeSubscription(this); }
+ unsubscribe: function unsubscribe() { closeSubscription(this); }
});
- var SubscriptionObserver = function(subscription){
+ var SubscriptionObserver = function (subscription) {
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
- next: function next(value){
+ next: function next(value) {
var subscription = this._s;
- if(!subscriptionClosed(subscription)){
+ if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
try {
var m = getMethod(observer.next);
- if(m)return m.call(observer, value);
- } catch(e){
+ if (m) return m.call(observer, value);
+ } catch (e) {
try {
closeSubscription(subscription);
} finally {
@@ -7255,16 +8067,16 @@ return /******/ (function(modules) { // webpackBootstrap
}
}
},
- error: function error(value){
+ error: function error(value) {
var subscription = this._s;
- if(subscriptionClosed(subscription))throw value;
+ if (subscriptionClosed(subscription)) throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
- if(!m)throw value;
+ if (!m) throw value;
value = m.call(observer, value);
- } catch(e){
+ } catch (e) {
try {
cleanupSubscription(subscription);
} finally {
@@ -7273,15 +8085,15 @@ return /******/ (function(modules) { // webpackBootstrap
} cleanupSubscription(subscription);
return value;
},
- complete: function complete(value){
+ complete: function complete(value) {
var subscription = this._s;
- if(!subscriptionClosed(subscription)){
+ if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
- } catch(e){
+ } catch (e) {
try {
cleanupSubscription(subscription);
} finally {
@@ -7293,23 +8105,23 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
- var $Observable = function Observable(subscriber){
+ var $Observable = function Observable(subscriber) {
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
- subscribe: function subscribe(observer){
+ subscribe: function subscribe(observer) {
return new Subscription(observer, this._f);
},
- forEach: function forEach(fn){
+ forEach: function forEach(fn) {
var that = this;
- return new (core.Promise || global.Promise)(function(resolve, reject){
+ return new (core.Promise || global.Promise)(function (resolve, reject) {
aFunction(fn);
var subscription = that.subscribe({
- next : function(value){
+ next: function (value) {
try {
return fn(value);
- } catch(e){
+ } catch (e) {
reject(e);
subscription.unsubscribe();
}
@@ -7322,156 +8134,162 @@ return /******/ (function(modules) { // webpackBootstrap
});
redefineAll($Observable, {
- from: function from(x){
+ from: function from(x) {
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
- if(method){
+ if (method) {
var observable = anObject(method.call(x));
- return observable.constructor === C ? observable : new C(function(observer){
+ return observable.constructor === C ? observable : new C(function (observer) {
return observable.subscribe(observer);
});
}
- return new C(function(observer){
+ return new C(function (observer) {
var done = false;
- microtask(function(){
- if(!done){
+ microtask(function () {
+ if (!done) {
try {
- if(forOf(x, false, function(it){
+ if (forOf(x, false, function (it) {
observer.next(it);
- if(done)return RETURN;
- }) === RETURN)return;
- } catch(e){
- if(done)throw e;
+ if (done) return RETURN;
+ }) === RETURN) return;
+ } catch (e) {
+ if (done) throw e;
observer.error(e);
return;
} observer.complete();
}
});
- return function(){ done = true; };
+ return function () { done = true; };
});
},
- of: function of(){
- for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
- return new (typeof this === 'function' ? this : $Observable)(function(observer){
+ of: function of() {
+ for (var i = 0, l = arguments.length, items = Array(l); i < l;) items[i] = arguments[i++];
+ return new (typeof this === 'function' ? this : $Observable)(function (observer) {
var done = false;
- microtask(function(){
- if(!done){
- for(var i = 0; i < items.length; ++i){
- observer.next(items[i]);
- if(done)return;
+ microtask(function () {
+ if (!done) {
+ for (var j = 0; j < items.length; ++j) {
+ observer.next(items[j]);
+ if (done) return;
} observer.complete();
}
});
- return function(){ done = true; };
+ return function () { done = true; };
});
}
});
- hide($Observable.prototype, OBSERVABLE, function(){ return this; });
+ hide($Observable.prototype, OBSERVABLE, function () { return this; });
- $export($export.G, {Observable: $Observable});
+ $export($export.G, { Observable: $Observable });
- __webpack_require__(193)('Observable');
+ __webpack_require__(194)('Observable');
+
/***/ }),
-/* 289 */
+/* 320 */
/***/ (function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
- var global = __webpack_require__(5)
- , $export = __webpack_require__(9)
- , invoke = __webpack_require__(79)
- , partial = __webpack_require__(290)
- , navigator = global.navigator
- , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
- var wrap = function(set){
- return MSIE ? function(fn, time /*, ...args */){
- return set(invoke(
- partial,
- [].slice.call(arguments, 2),
- typeof fn == 'function' ? fn : Function(fn)
- ), time);
- } : set;
+ var global = __webpack_require__(5);
+ var $export = __webpack_require__(9);
+ var navigator = global.navigator;
+ var slice = [].slice;
+ var MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
+ var wrap = function (set) {
+ return function (fn, time /* , ...args */) {
+ var boundArgs = arguments.length > 2;
+ var args = boundArgs ? slice.call(arguments, 2) : false;
+ return set(boundArgs ? function () {
+ // eslint-disable-next-line no-new-func
+ (typeof fn == 'function' ? fn : Function(fn)).apply(this, args);
+ } : fn, time);
+ };
};
$export($export.G + $export.B + $export.F * MSIE, {
- setTimeout: wrap(global.setTimeout),
+ setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
-/***/ }),
-/* 290 */
-/***/ (function(module, exports, __webpack_require__) {
-
- 'use strict';
- var path = __webpack_require__(291)
- , invoke = __webpack_require__(79)
- , aFunction = __webpack_require__(22);
- module.exports = function(/* ...pargs */){
- var fn = aFunction(this)
- , length = arguments.length
- , pargs = Array(length)
- , i = 0
- , _ = path._
- , holder = false;
- while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
- return function(/* ...args */){
- var that = this
- , aLen = arguments.length
- , j = 0, k = 0, args;
- if(!holder && !aLen)return invoke(fn, pargs, that);
- args = pargs.slice();
- if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
- while(aLen > k)args.push(arguments[k++]);
- return invoke(fn, args, that);
- };
- };
-
-/***/ }),
-/* 291 */
-/***/ (function(module, exports, __webpack_require__) {
-
- module.exports = __webpack_require__(5);
/***/ }),
-/* 292 */
+/* 321 */
/***/ (function(module, exports, __webpack_require__) {
- var $export = __webpack_require__(9)
- , $task = __webpack_require__(209);
+ var $export = __webpack_require__(9);
+ var $task = __webpack_require__(210);
$export($export.G + $export.B, {
- setImmediate: $task.set,
+ setImmediate: $task.set,
clearImmediate: $task.clear
});
+
/***/ }),
-/* 293 */
+/* 322 */
/***/ (function(module, exports, __webpack_require__) {
- var $iterators = __webpack_require__(194)
- , redefine = __webpack_require__(19)
- , global = __webpack_require__(5)
- , hide = __webpack_require__(11)
- , Iterators = __webpack_require__(130)
- , wks = __webpack_require__(26)
- , ITERATOR = wks('iterator')
- , TO_STRING_TAG = wks('toStringTag')
- , ArrayValues = Iterators.Array;
-
- for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
- var NAME = collections[i]
- , Collection = global[NAME]
- , proto = Collection && Collection.prototype
- , key;
- if(proto){
- if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
- if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
+ var $iterators = __webpack_require__(195);
+ var getKeys = __webpack_require__(31);
+ var redefine = __webpack_require__(19);
+ var global = __webpack_require__(5);
+ var hide = __webpack_require__(11);
+ var Iterators = __webpack_require__(130);
+ var wks = __webpack_require__(26);
+ var ITERATOR = wks('iterator');
+ var TO_STRING_TAG = wks('toStringTag');
+ var ArrayValues = Iterators.Array;
+
+ var DOMIterables = {
+ CSSRuleList: true, // TODO: Not spec compliant, should be false.
+ CSSStyleDeclaration: false,
+ CSSValueList: false,
+ ClientRectList: false,
+ DOMRectList: false,
+ DOMStringList: false,
+ DOMTokenList: true,
+ DataTransferItemList: false,
+ FileList: false,
+ HTMLAllCollection: false,
+ HTMLCollection: false,
+ HTMLFormElement: false,
+ HTMLSelectElement: false,
+ MediaList: true, // TODO: Not spec compliant, should be false.
+ MimeTypeArray: false,
+ NamedNodeMap: false,
+ NodeList: true,
+ PaintRequestList: false,
+ Plugin: false,
+ PluginArray: false,
+ SVGLengthList: false,
+ SVGNumberList: false,
+ SVGPathSegList: false,
+ SVGPointList: false,
+ SVGStringList: false,
+ SVGTransformList: false,
+ SourceBufferList: false,
+ StyleSheetList: true, // TODO: Not spec compliant, should be false.
+ TextTrackCueList: false,
+ TextTrackList: false,
+ TouchList: false
+ };
+
+ for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
+ var NAME = collections[i];
+ var explicit = DOMIterables[NAME];
+ var Collection = global[NAME];
+ var proto = Collection && Collection.prototype;
+ var key;
+ if (proto) {
+ if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
+ if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
- for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
+ if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
+
/***/ }),
-/* 294 */
+/* 323 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/**
@@ -8214,53 +9032,53 @@ return /******/ (function(modules) { // webpackBootstrap
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
-/* 295 */
+/* 324 */
/***/ (function(module, exports, __webpack_require__) {
- __webpack_require__(296);
+ __webpack_require__(325);
module.exports = __webpack_require__(10).RegExp.escape;
+
/***/ }),
-/* 296 */
+/* 325 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/benjamingr/RexExp.escape
- var $export = __webpack_require__(9)
- , $re = __webpack_require__(297)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
+ var $export = __webpack_require__(9);
+ var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
- $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
+ $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } });
/***/ }),
-/* 297 */
+/* 326 */
/***/ (function(module, exports) {
- module.exports = function(regExp, replace){
- var replacer = replace === Object(replace) ? function(part){
+ module.exports = function (regExp, replace) {
+ var replacer = replace === Object(replace) ? function (part) {
return replace[part];
} : replace;
- return function(it){
+ return function (it) {
return String(it).replace(regExp, replacer);
};
};
+
/***/ }),
-/* 298 */
+/* 327 */
/***/ (function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE_298__;
+ module.exports = __WEBPACK_EXTERNAL_MODULE_327__;
/***/ }),
-/* 299 */
+/* 328 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2013-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*/
if (process.env.NODE_ENV !== 'production') {
@@ -8278,17 +9096,17 @@ return /******/ (function(modules) { // webpackBootstrap
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
- module.exports = __webpack_require__(301)(isValidElement, throwOnDirectAccess);
+ module.exports = __webpack_require__(330)(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
- module.exports = __webpack_require__(307)();
+ module.exports = __webpack_require__(337)();
}
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
/***/ }),
-/* 300 */
+/* 329 */
/***/ (function(module, exports) {
// shim for using process in browser
@@ -8478,26 +9296,25 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 301 */
+/* 330 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2013-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*/
'use strict';
- var emptyFunction = __webpack_require__(302);
- var invariant = __webpack_require__(303);
- var warning = __webpack_require__(304);
+ var emptyFunction = __webpack_require__(331);
+ var invariant = __webpack_require__(332);
+ var warning = __webpack_require__(333);
+ var assign = __webpack_require__(334);
- var ReactPropTypesSecret = __webpack_require__(305);
- var checkPropTypes = __webpack_require__(306);
+ var ReactPropTypesSecret = __webpack_require__(335);
+ var checkPropTypes = __webpack_require__(336);
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
@@ -8593,7 +9410,8 @@ return /******/ (function(modules) { // webpackBootstrap
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
- shape: createShapeTypeChecker
+ shape: createShapeTypeChecker,
+ exact: createStrictShapeTypeChecker,
};
/**
@@ -8808,7 +9626,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (typeof checker !== 'function') {
warning(
false,
- 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' +
+ 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
@@ -8862,6 +9680,36 @@ return /******/ (function(modules) { // webpackBootstrap
return createChainableTypeChecker(validate);
}
+ function createStrictShapeTypeChecker(shapeTypes) {
+ function validate(props, propName, componentName, location, propFullName) {
+ var propValue = props[propName];
+ var propType = getPropType(propValue);
+ if (propType !== 'object') {
+ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
+ }
+ // We need to check all keys in case some are required but missing from
+ // props.
+ var allKeys = assign({}, props[propName], shapeTypes);
+ for (var key in allKeys) {
+ var checker = shapeTypes[key];
+ if (!checker) {
+ return new PropTypeError(
+ 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
+ '\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
+ '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
+ );
+ }
+ var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
+ if (error) {
+ return error;
+ }
+ }
+ return null;
+ }
+
+ return createChainableTypeChecker(validate);
+ }
+
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
@@ -8994,21 +9842,19 @@ return /******/ (function(modules) { // webpackBootstrap
return ReactPropTypes;
};
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
/***/ }),
-/* 302 */
+/* 331 */
/***/ (function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*
*
*/
@@ -9040,16 +9886,14 @@ return /******/ (function(modules) { // webpackBootstrap
module.exports = emptyFunction;
/***/ }),
-/* 303 */
+/* 332 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*
*/
@@ -9098,25 +9942,23 @@ return /******/ (function(modules) { // webpackBootstrap
}
module.exports = invariant;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
/***/ }),
-/* 304 */
+/* 333 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2014-2015, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2014-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*
*/
'use strict';
- var emptyFunction = __webpack_require__(302);
+ var emptyFunction = __webpack_require__(331);
/**
* Similar to invariant but only logs a warning if the condition is not met.
@@ -9128,61 +9970,153 @@ return /******/ (function(modules) { // webpackBootstrap
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
- (function () {
- var printWarning = function printWarning(format) {
- for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
-
- var argIndex = 0;
- var message = 'Warning: ' + format.replace(/%s/g, function () {
- return args[argIndex++];
- });
- if (typeof console !== 'undefined') {
- console.error(message);
- }
- try {
- // --- Welcome to debugging React ---
- // This error was thrown as a convenience so that you can use this stack
- // to find the callsite that caused this warning to fire.
- throw new Error(message);
- } catch (x) {}
- };
+ var printWarning = function printWarning(format) {
+ for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
- warning = function warning(condition, format) {
- if (format === undefined) {
- throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
- }
+ var argIndex = 0;
+ var message = 'Warning: ' + format.replace(/%s/g, function () {
+ return args[argIndex++];
+ });
+ if (typeof console !== 'undefined') {
+ console.error(message);
+ }
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ throw new Error(message);
+ } catch (x) {}
+ };
- if (format.indexOf('Failed Composite propType: ') === 0) {
- return; // Ignore CompositeComponent proptype check.
- }
+ warning = function warning(condition, format) {
+ if (format === undefined) {
+ throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
+ }
- if (!condition) {
- for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
- args[_key2 - 2] = arguments[_key2];
- }
+ if (format.indexOf('Failed Composite propType: ') === 0) {
+ return; // Ignore CompositeComponent proptype check.
+ }
- printWarning.apply(undefined, [format].concat(args));
+ if (!condition) {
+ for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
+ args[_key2 - 2] = arguments[_key2];
}
- };
- })();
+
+ printWarning.apply(undefined, [format].concat(args));
+ }
+ };
}
module.exports = warning;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
/***/ }),
-/* 305 */
+/* 334 */
+/***/ (function(module, exports) {
+
+ /*
+ object-assign
+ (c) Sindre Sorhus
+ @license MIT
+ */
+
+ 'use strict';
+ /* eslint-disable no-unused-vars */
+ var getOwnPropertySymbols = Object.getOwnPropertySymbols;
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+
+ function toObject(val) {
+ if (val === null || val === undefined) {
+ throw new TypeError('Object.assign cannot be called with null or undefined');
+ }
+
+ return Object(val);
+ }
+
+ function shouldUseNative() {
+ try {
+ if (!Object.assign) {
+ return false;
+ }
+
+ // Detect buggy property enumeration order in older V8 versions.
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=4118
+ var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
+ test1[5] = 'de';
+ if (Object.getOwnPropertyNames(test1)[0] === '5') {
+ return false;
+ }
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test2 = {};
+ for (var i = 0; i < 10; i++) {
+ test2['_' + String.fromCharCode(i)] = i;
+ }
+ var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
+ return test2[n];
+ });
+ if (order2.join('') !== '0123456789') {
+ return false;
+ }
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test3 = {};
+ 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
+ test3[letter] = letter;
+ });
+ if (Object.keys(Object.assign({}, test3)).join('') !==
+ 'abcdefghijklmnopqrst') {
+ return false;
+ }
+
+ return true;
+ } catch (err) {
+ // We don't expect any of the above to throw, but better to be safe.
+ return false;
+ }
+ }
+
+ module.exports = shouldUseNative() ? Object.assign : function (target, source) {
+ var from;
+ var to = toObject(target);
+ var symbols;
+
+ for (var s = 1; s < arguments.length; s++) {
+ from = Object(arguments[s]);
+
+ for (var key in from) {
+ if (hasOwnProperty.call(from, key)) {
+ to[key] = from[key];
+ }
+ }
+
+ if (getOwnPropertySymbols) {
+ symbols = getOwnPropertySymbols(from);
+ for (var i = 0; i < symbols.length; i++) {
+ if (propIsEnumerable.call(from, symbols[i])) {
+ to[symbols[i]] = from[symbols[i]];
+ }
+ }
+ }
+ }
+
+ return to;
+ };
+
+
+/***/ }),
+/* 335 */
/***/ (function(module, exports) {
/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2013-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*/
'use strict';
@@ -9193,24 +10127,22 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 306 */
+/* 336 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2013-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== 'production') {
- var invariant = __webpack_require__(303);
- var warning = __webpack_require__(304);
- var ReactPropTypesSecret = __webpack_require__(305);
+ var invariant = __webpack_require__(332);
+ var warning = __webpack_require__(333);
+ var ReactPropTypesSecret = __webpack_require__(335);
var loggedTypeFailures = {};
}
@@ -9236,7 +10168,7 @@ return /******/ (function(modules) { // webpackBootstrap
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
- invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName);
+ invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
@@ -9258,26 +10190,24 @@ return /******/ (function(modules) { // webpackBootstrap
module.exports = checkPropTypes;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
/***/ }),
-/* 307 */
+/* 337 */
/***/ (function(module, exports, __webpack_require__) {
/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
+ * Copyright (c) 2013-present, Facebook, Inc.
*
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
*/
'use strict';
- var emptyFunction = __webpack_require__(302);
- var invariant = __webpack_require__(303);
- var ReactPropTypesSecret = __webpack_require__(305);
+ var emptyFunction = __webpack_require__(331);
+ var invariant = __webpack_require__(332);
+ var ReactPropTypesSecret = __webpack_require__(335);
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
@@ -9315,7 +10245,8 @@ return /******/ (function(modules) { // webpackBootstrap
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
- shape: getShim
+ shape: getShim,
+ exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
@@ -9326,7 +10257,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
-/* 308 */
+/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
@@ -9337,15 +10268,15 @@ return /******/ (function(modules) { // webpackBootstrap
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
- var _react = __webpack_require__(298);
+ var _react = __webpack_require__(327);
var _react2 = _interopRequireDefault(_react);
- var _propTypes = __webpack_require__(299);
+ var _propTypes = __webpack_require__(328);
var _propTypes2 = _interopRequireDefault(_propTypes);
- var _reactCodemirror = __webpack_require__(309);
+ var _reactCodemirror = __webpack_require__(339);
var _reactCodemirror2 = _interopRequireDefault(_reactCodemirror);
@@ -9359,7 +10290,7 @@ return /******/ (function(modules) { // webpackBootstrap
if (typeof window !== "undefined") {
- __webpack_require__(320);
+ __webpack_require__(341);
}
var Editor = function (_Component) {
@@ -9377,7 +10308,7 @@ return /******/ (function(modules) { // webpackBootstrap
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Editor.__proto__ || Object.getPrototypeOf(Editor)).call.apply(_ref, [this].concat(args))), _this), _this.componentDidMount = function () {
- var editor = _this.refs.editor.getCodeMirror();
+ var editor = _this.editor.editor;
_this.highlightSelectedLines(editor, _this.props.selectedLines);
}, _this.highlightSelectedLines = function (editor, selectedLines) {
if (Array.isArray(selectedLines)) {
@@ -9385,7 +10316,7 @@ return /******/ (function(modules) { // webpackBootstrap
return editor.addLineClass(lineNumber, "wrap", "CodeMirror-activeline-background");
});
}
- }, _this.updateCode = function (code) {
+ }, _this.updateCode = function (editor, meta, code) {
if (!_this.props.readOnly && _this.props.onChange) {
_this.props.onChange(code);
}
@@ -9395,6 +10326,8 @@ return /******/ (function(modules) { // webpackBootstrap
_createClass(Editor, [{
key: "render",
value: function render() {
+ var _this2 = this;
+
var _props = this.props,
className = _props.className,
external = _props.external,
@@ -9415,13 +10348,16 @@ return /******/ (function(modules) { // webpackBootstrap
};
return _react2.default.createElement(_reactCodemirror2.default, {
- ref: "editor",
+ ref: function ref(c) {
+ _this2.editor = c;
+ },
className: className,
external: external,
options: options,
style: style,
value: codeText,
- onChange: this.updateCode });
+ onChange: this.updateCode
+ });
}
}]);
@@ -9429,33975 +10365,15002 @@ return /******/ (function(modules) { // webpackBootstrap
}(_react.Component);
Editor.propTypes = {
- theme: _propTypes2.default.string,
- readOnly: _propTypes2.default.bool,
- external: _propTypes2.default.bool,
+ className: _propTypes2.default.string,
codeText: _propTypes2.default.string,
- selectedLines: _propTypes2.default.array,
+ external: _propTypes2.default.bool,
onChange: _propTypes2.default.func,
+ readOnly: _propTypes2.default.bool,
+ selectedLines: _propTypes2.default.array,
style: _propTypes2.default.object,
- className: _propTypes2.default.string
+ theme: _propTypes2.default.string
};
exports.default = Editor;
/***/ }),
-/* 309 */
+/* 339 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
- var React = __webpack_require__(298);
- var ReactDOM = __webpack_require__(310);
- var PropTypes = __webpack_require__(299);
- var className = __webpack_require__(311);
- var debounce = __webpack_require__(312);
- var isEqual = __webpack_require__(313);
- var createReactClass = __webpack_require__(315);
-
- function normalizeLineEndings(str) {
- if (!str) return str;
- return str.replace(/\r\n|\r/g, '\n');
- }
-
- var CodeMirror = createReactClass({
- propTypes: {
- autoFocus: PropTypes.bool,
- className: PropTypes.any,
- codeMirrorInstance: PropTypes.func,
- defaultValue: PropTypes.string,
- name: PropTypes.string,
- onChange: PropTypes.func,
- onCursorActivity: PropTypes.func,
- onFocusChange: PropTypes.func,
- onScroll: PropTypes.func,
- options: PropTypes.object,
- path: PropTypes.string,
- value: PropTypes.string,
- preserveScrollPosition: PropTypes.bool
- },
- getDefaultProps: function getDefaultProps() {
- return {
- preserveScrollPosition: false
- };
- },
- getCodeMirrorInstance: function getCodeMirrorInstance() {
- return this.props.codeMirrorInstance || __webpack_require__(319);
- },
- getInitialState: function getInitialState() {
- return {
- isFocused: false
- };
- },
- componentWillMount: function componentWillMount() {
- this.componentWillReceiveProps = debounce(this.componentWillReceiveProps, 0);
- if (this.props.path) {
- console.error('Warning: react-codemirror: the `path` prop has been changed to `name`');
- }
- },
- componentDidMount: function componentDidMount() {
- var codeMirrorInstance = this.getCodeMirrorInstance();
- this.codeMirror = codeMirrorInstance.fromTextArea(this.textareaNode, this.props.options);
- this.codeMirror.on('change', this.codemirrorValueChanged);
- this.codeMirror.on('cursorActivity', this.cursorActivity);
- this.codeMirror.on('focus', this.focusChanged.bind(this, true));
- this.codeMirror.on('blur', this.focusChanged.bind(this, false));
- this.codeMirror.on('scroll', this.scrollChanged);
- this.codeMirror.setValue(this.props.defaultValue || this.props.value || '');
- },
- componentWillUnmount: function componentWillUnmount() {
- // is there a lighter-weight way to remove the cm instance?
- if (this.codeMirror) {
- this.codeMirror.toTextArea();
- }
- },
- componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
- if (this.codeMirror && nextProps.value !== undefined && nextProps.value !== this.props.value && normalizeLineEndings(this.codeMirror.getValue()) !== normalizeLineEndings(nextProps.value)) {
- if (this.props.preserveScrollPosition) {
- var prevScrollPosition = this.codeMirror.getScrollInfo();
- this.codeMirror.setValue(nextProps.value);
- this.codeMirror.scrollTo(prevScrollPosition.left, prevScrollPosition.top);
- } else {
- this.codeMirror.setValue(nextProps.value);
- }
- }
- if (typeof nextProps.options === 'object') {
- for (var optionName in nextProps.options) {
- if (nextProps.options.hasOwnProperty(optionName)) {
- this.setOptionIfChanged(optionName, nextProps.options[optionName]);
- }
- }
- }
- },
- setOptionIfChanged: function setOptionIfChanged(optionName, newValue) {
- var oldValue = this.codeMirror.getOption(optionName);
- if (!isEqual(oldValue, newValue)) {
- this.codeMirror.setOption(optionName, newValue);
- }
- },
- getCodeMirror: function getCodeMirror() {
- return this.codeMirror;
- },
- focus: function focus() {
- if (this.codeMirror) {
- this.codeMirror.focus();
- }
- },
- focusChanged: function focusChanged(focused) {
- this.setState({
- isFocused: focused
- });
- this.props.onFocusChange && this.props.onFocusChange(focused);
- },
- cursorActivity: function cursorActivity(cm) {
- this.props.onCursorActivity && this.props.onCursorActivity(cm);
- },
- scrollChanged: function scrollChanged(cm) {
- this.props.onScroll && this.props.onScroll(cm.getScrollInfo());
- },
- codemirrorValueChanged: function codemirrorValueChanged(doc, change) {
- if (this.props.onChange && change.origin !== 'setValue') {
- this.props.onChange(doc.getValue(), change);
- }
- },
- render: function render() {
- var _this = this;
-
- var editorClassName = className('ReactCodeMirror', this.state.isFocused ? 'ReactCodeMirror--focused' : null, this.props.className);
- return React.createElement(
- 'div',
- { className: editorClassName },
- React.createElement('textarea', {
- ref: function (ref) {
- return _this.textareaNode = ref;
- },
- name: this.props.name || this.props.path,
- defaultValue: this.props.value,
- autoComplete: 'off',
- autoFocus: this.props.autoFocus
- })
- );
- }
+ Object.defineProperty(exports, "__esModule", {
+ value: true
});
- module.exports = CodeMirror;
-
-/***/ }),
-/* 310 */
-/***/ (function(module, exports) {
-
- module.exports = __WEBPACK_EXTERNAL_MODULE_310__;
-
-/***/ }),
-/* 311 */
-/***/ (function(module, exports, __webpack_require__) {
-
- var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
- Copyright (c) 2016 Jed Watson.
- Licensed under the MIT License (MIT), see
- http://jedwatson.github.io/classnames
- */
- /* global define */
-
- (function () {
- 'use strict';
-
- var hasOwn = {}.hasOwnProperty;
-
- function classNames () {
- var classes = [];
-
- for (var i = 0; i < arguments.length; i++) {
- var arg = arguments[i];
- if (!arg) continue;
-
- var argType = typeof arg;
-
- if (argType === 'string' || argType === 'number') {
- classes.push(arg);
- } else if (Array.isArray(arg)) {
- classes.push(classNames.apply(null, arg));
- } else if (argType === 'object') {
- for (var key in arg) {
- if (hasOwn.call(arg, key) && arg[key]) {
- classes.push(key);
- }
- }
- }
- }
-
- return classes.join(' ');
- }
-
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = classNames;
- } else if (true) {
- // register as 'classnames', consistent with npm package name
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
- return classNames;
- }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {
- window.classNames = classNames;
- }
- }());
-
-
-/***/ }),
-/* 312 */
-/***/ (function(module, exports) {
-
- /* WEBPACK VAR INJECTION */(function(global) {/**
- * lodash (Custom Build)
- * Build: `lodash modularize exports="npm" -o ./`
- * Copyright jQuery Foundation and other contributors
- * Released under MIT license
- * Based on Underscore.js 1.8.3
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
-
- /** Used as the `TypeError` message for "Functions" methods. */
- var FUNC_ERROR_TEXT = 'Expected a function';
-
- /** Used as references for various `Number` constants. */
- var NAN = 0 / 0;
-
- /** `Object#toString` result references. */
- var symbolTag = '[object Symbol]';
-
- /** Used to match leading and trailing whitespace. */
- var reTrim = /^\s+|\s+$/g;
-
- /** Used to detect bad signed hexadecimal string values. */
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
+ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
- /** Used to detect binary string values. */
- var reIsBinary = /^0b[01]+$/i;
+ var _react = __webpack_require__(327);
- /** Used to detect octal string values. */
- var reIsOctal = /^0o[0-7]+$/i;
+ var _react2 = _interopRequireDefault(_react);
- /** Built-in method references without a dependency on `root`. */
- var freeParseInt = parseInt;
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /** Detect free variable `self`. */
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+ function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
- /** Used as a reference to the global object. */
- var root = freeGlobal || freeSelf || Function('return this')();
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
+ var codemirror = __webpack_require__(340);
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var objectToString = objectProto.toString;
+ var CodeMirror = function (_React$Component) {
+ _inherits(CodeMirror, _React$Component);
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeMax = Math.max,
- nativeMin = Math.min;
+ function CodeMirror(props) {
+ _classCallCheck(this, CodeMirror);
- /**
- * Gets the timestamp of the number of milliseconds that have elapsed since
- * the Unix epoch (1 January 1970 00:00:00 UTC).
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Date
- * @returns {number} Returns the timestamp.
- * @example
- *
- * _.defer(function(stamp) {
- * console.log(_.now() - stamp);
- * }, _.now());
- * // => Logs the number of milliseconds it took for the deferred invocation.
- */
- var now = function() {
- return root.Date.now();
- };
+ var _this = _possibleConstructorReturn(this, (CodeMirror.__proto__ || Object.getPrototypeOf(CodeMirror)).call(this, props));
- /**
- * Creates a debounced function that delays invoking `func` until after `wait`
- * milliseconds have elapsed since the last time the debounced function was
- * invoked. The debounced function comes with a `cancel` method to cancel
- * delayed `func` invocations and a `flush` method to immediately invoke them.
- * Provide `options` to indicate whether `func` should be invoked on the
- * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
- * with the last arguments provided to the debounced function. Subsequent
- * calls to the debounced function return the result of the last `func`
- * invocation.
- *
- * **Note:** If `leading` and `trailing` options are `true`, `func` is
- * invoked on the trailing edge of the timeout only if the debounced function
- * is invoked more than once during the `wait` timeout.
- *
- * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
- * until to the next tick, similar to `setTimeout` with a timeout of `0`.
- *
- * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
- * for details over the differences between `_.debounce` and `_.throttle`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Function
- * @param {Function} func The function to debounce.
- * @param {number} [wait=0] The number of milliseconds to delay.
- * @param {Object} [options={}] The options object.
- * @param {boolean} [options.leading=false]
- * Specify invoking on the leading edge of the timeout.
- * @param {number} [options.maxWait]
- * The maximum time `func` is allowed to be delayed before it's invoked.
- * @param {boolean} [options.trailing=true]
- * Specify invoking on the trailing edge of the timeout.
- * @returns {Function} Returns the new debounced function.
- * @example
- *
- * // Avoid costly calculations while the window size is in flux.
- * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
- *
- * // Invoke `sendMail` when clicked, debouncing subsequent calls.
- * jQuery(element).on('click', _.debounce(sendMail, 300, {
- * 'leading': true,
- * 'trailing': false
- * }));
- *
- * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
- * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
- * var source = new EventSource('/stream');
- * jQuery(source).on('message', debounced);
- *
- * // Cancel the trailing debounced invocation.
- * jQuery(window).on('popstate', debounced.cancel);
- */
- function debounce(func, wait, options) {
- var lastArgs,
- lastThis,
- maxWait,
- result,
- timerId,
- lastCallTime,
- lastInvokeTime = 0,
- leading = false,
- maxing = false,
- trailing = true;
-
- if (typeof func != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- wait = toNumber(wait) || 0;
- if (isObject(options)) {
- leading = !!options.leading;
- maxing = 'maxWait' in options;
- maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
- trailing = 'trailing' in options ? !!options.trailing : trailing;
- }
-
- function invokeFunc(time) {
- var args = lastArgs,
- thisArg = lastThis;
-
- lastArgs = lastThis = undefined;
- lastInvokeTime = time;
- result = func.apply(thisArg, args);
- return result;
- }
+ _this.hydrated = false;
+ _this.continuePreSet = false;
+ _this.continuePreChange = false;
- function leadingEdge(time) {
- // Reset any `maxWait` timer.
- lastInvokeTime = time;
- // Start the timer for the trailing edge.
- timerId = setTimeout(timerExpired, wait);
- // Invoke the leading edge.
- return leading ? invokeFunc(time) : result;
- }
+ _this.onBeforeChangeCb = function () {
- function remainingWait(time) {
- var timeSinceLastCall = time - lastCallTime,
- timeSinceLastInvoke = time - lastInvokeTime,
- result = wait - timeSinceLastCall;
+ _this.continuePreChange = true;
+ };
- return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
- }
+ _this.onBeforeSetCb = function () {
- function shouldInvoke(time) {
- var timeSinceLastCall = time - lastCallTime,
- timeSinceLastInvoke = time - lastInvokeTime;
+ _this.continuePreSet = true;
+ };
- // Either this is the first call, activity has stopped and we're at the
- // trailing edge, the system time has gone backwards and we're treating
- // it as the trailing edge, or we've hit the `maxWait` limit.
- return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
- (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
+ _this.initCb = function () {
+ if (_this.props.editorDidConfigure) {
+ _this.props.editorDidConfigure(_this.editor);
+ }
+ };
+ return _this;
}
- function timerExpired() {
- var time = now();
- if (shouldInvoke(time)) {
- return trailingEdge(time);
+ _createClass(CodeMirror, [{
+ key: 'componentWillMount',
+ value: function componentWillMount() {
+ if (this.props.editorWillMount) {
+ this.props.editorWillMount();
+ }
}
- // Restart the timer.
- timerId = setTimeout(timerExpired, remainingWait(time));
- }
+ }, {
+ key: 'componentDidMount',
+ value: function componentDidMount() {
+ var _this2 = this;
- function trailingEdge(time) {
- timerId = undefined;
+ if (this.props.defineMode) {
+ if (this.props.defineMode.name && this.props.defineMode.fn) {
+ codemirror.defineMode(this.props.defineMode.name, this.props.defineMode.fn);
+ }
+ }
- // Only invoke if we have `lastArgs` which means `func` has been
- // debounced at least once.
- if (trailing && lastArgs) {
- return invokeFunc(time);
- }
- lastArgs = lastThis = undefined;
- return result;
- }
+ this.editor = codemirror(this.ref);
- function cancel() {
- if (timerId !== undefined) {
- clearTimeout(timerId);
- }
- lastInvokeTime = 0;
- lastArgs = lastCallTime = lastThis = timerId = undefined;
- }
+ this.editor.on('beforeChange', function (cm, changeObj) {
+ if (_this2.props.onBeforeChange && _this2.hydrated) {
+ _this2.props.onBeforeChange(_this2.editor, changeObj, _this2.onBeforeChangeCb);
+ }
+ });
- function flush() {
- return timerId === undefined ? result : trailingEdge(now());
- }
+ this.editor.on('change', function (cm, metadata) {
- function debounced() {
- var time = now(),
- isInvoking = shouldInvoke(time);
+ if (_this2.props.onChange && _this2.hydrated) {
- lastArgs = arguments;
- lastThis = this;
- lastCallTime = time;
+ if (_this2.props.onBeforeChange) {
+ if (_this2.continuePreChange) {
+ _this2.props.onChange(_this2.editor, metadata, _this2.editor.getValue());
+ }
+ } else {
+ _this2.props.onChange(_this2.editor, metadata, _this2.editor.getValue());
+ }
+ }
+ });
- if (isInvoking) {
- if (timerId === undefined) {
- return leadingEdge(lastCallTime);
+ if (this.props.onCursorActivity) {
+ this.editor.on('cursorActivity', function (cm) {
+ _this2.props.onViewportChange(_this2.editor);
+ });
}
- if (maxing) {
- // Handle invocations in a tight loop.
- timerId = setTimeout(timerExpired, wait);
- return invokeFunc(lastCallTime);
+
+ if (this.props.onViewportChange) {
+ this.editor.on('viewportChange', function (cm, start, end) {
+ _this2.props.onViewportChange(_this2.editor, start, end);
+ });
}
- }
- if (timerId === undefined) {
- timerId = setTimeout(timerExpired, wait);
- }
- return result;
- }
- debounced.cancel = cancel;
- debounced.flush = flush;
- return debounced;
- }
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject(value) {
- var type = typeof value;
- return !!value && (type == 'object' || type == 'function');
- }
+ if (this.props.onGutterClick) {
+ this.editor.on('gutterClick', function (cm, lineNumber, event) {
+ _this2.props.onGutterClick(_this2.editor, lineNumber, event);
+ });
+ }
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return !!value && typeof value == 'object';
- }
+ if (this.props.onFocus) {
+ this.editor.on('focus', function (cm, event) {
+ _this2.props.onFocus(_this2.editor, event);
+ });
+ }
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == 'symbol' ||
- (isObjectLike(value) && objectToString.call(value) == symbolTag);
- }
+ if (this.props.onBlur) {
+ this.editor.on('blur', function (cm, event) {
+ _this2.props.onBlur(_this2.editor, event);
+ });
+ }
- /**
- * Converts `value` to a number.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to process.
- * @returns {number} Returns the number.
- * @example
- *
- * _.toNumber(3.2);
- * // => 3.2
- *
- * _.toNumber(Number.MIN_VALUE);
- * // => 5e-324
- *
- * _.toNumber(Infinity);
- * // => Infinity
- *
- * _.toNumber('3.2');
- * // => 3.2
- */
- function toNumber(value) {
- if (typeof value == 'number') {
- return value;
- }
- if (isSymbol(value)) {
- return NAN;
- }
- if (isObject(value)) {
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
- value = isObject(other) ? (other + '') : other;
- }
- if (typeof value != 'string') {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, '');
- var isBinary = reIsBinary.test(value);
- return (isBinary || reIsOctal.test(value))
- ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
- : (reIsBadHex.test(value) ? NAN : +value);
- }
+ if (this.props.onUpdate) {
+ this.editor.on('update', function (cm, event) {
+ _this2.props.onUpdate(_this2.editor, event);
+ });
+ }
- module.exports = debounce;
+ if (this.props.onKeyDown) {
+ this.editor.on('keydown', function (cm, event) {
+ _this2.props.onKeyDown(_this2.editor, event);
+ });
+ }
- /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
-
-/***/ }),
-/* 313 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(global, module) {/**
- * Lodash (Custom Build)
- * Build: `lodash modularize exports="npm" -o ./`
- * Copyright JS Foundation and other contributors
- * Released under MIT license
- * Based on Underscore.js 1.8.3
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
+ if (this.props.onKeyUp) {
+ this.editor.on('keyup', function (cm, event) {
+ _this2.props.onKeyUp(_this2.editor, event);
+ });
+ }
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE = 200;
-
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
-
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 2;
-
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER = 9007199254740991;
-
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]',
- arrayTag = '[object Array]',
- asyncTag = '[object AsyncFunction]',
- boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- nullTag = '[object Null]',
- objectTag = '[object Object]',
- promiseTag = '[object Promise]',
- proxyTag = '[object Proxy]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- symbolTag = '[object Symbol]',
- undefinedTag = '[object Undefined]',
- weakMapTag = '[object WeakMap]';
-
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[object DataView]',
- float32Tag = '[object Float32Array]',
- float64Tag = '[object Float64Array]',
- int8Tag = '[object Int8Array]',
- int16Tag = '[object Int16Array]',
- int32Tag = '[object Int32Array]',
- uint8Tag = '[object Uint8Array]',
- uint8ClampedTag = '[object Uint8ClampedArray]',
- uint16Tag = '[object Uint16Array]',
- uint32Tag = '[object Uint32Array]';
+ if (this.props.onKeyPress) {
+ this.editor.on('keypress', function (cm, event) {
+ _this2.props.onKeyPress(_this2.editor, event);
+ });
+ }
- /**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
+ if (this.props.onDragEnter) {
+ this.editor.on('dragenter', function (cm, event) {
+ _this2.props.onDragEnter(_this2.editor, event);
+ });
+ }
+
+ if (this.props.onDragOver) {
+ this.editor.on('dragover', function (cm, event) {
+ _this2.props.onDragOver(_this2.editor, event);
+ });
+ }
- /** Used to detect host constructors (Safari). */
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
+ if (this.props.onDrop) {
+ this.editor.on('drop', function (cm, event) {
+ _this2.props.onDrop(_this2.editor, event);
+ });
+ }
- /** Used to detect unsigned integer values. */
- var reIsUint = /^(?:0|[1-9]\d*)$/;
+ if (this.props.onSelection) {
+ this.editor.on('beforeSelectionChange', function (cm, meta) {
+ _this2.props.onSelection(_this2.editor, meta.ranges);
+ });
+ }
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
- typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
- typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
- typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
- typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
- typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
- typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
- typedArrayTags[errorTag] = typedArrayTags[funcTag] =
- typedArrayTags[mapTag] = typedArrayTags[numberTag] =
- typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
- typedArrayTags[setTag] = typedArrayTags[stringTag] =
- typedArrayTags[weakMapTag] = false;
+ if (this.props.onScroll) {
+ this.editor.on('scroll', function (cm) {
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
+ var meta = _this2.editor.getScrollInfo();
- /** Detect free variable `self`. */
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+ _this2.props.onScroll(_this2.editor, {
+ x: meta.left,
+ y: meta.top
+ });
+ });
+ }
- /** Used as a reference to the global object. */
- var root = freeGlobal || freeSelf || Function('return this')();
+ if (this.props.onCursor) {
+ this.editor.on('cursorActivity', function (cm) {
- /** Detect free variable `exports`. */
- var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
+ var meta = _this2.editor.getCursor();
- /** Detect free variable `module`. */
- var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
+ _this2.props.onCursor(_this2.editor, {
+ line: meta.line,
+ ch: meta.ch
+ });
+ });
+ }
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
+ this.hydrate(this.props);
- /** Detect free variable `process` from Node.js. */
- var freeProcess = moduleExports && freeGlobal.process;
+ // commands
+ if (this.props.selection) {
+ this.editor.setSelections(this.props.selection);
+ }
- /** Used to access faster Node.js helpers. */
- var nodeUtil = (function() {
- try {
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
- } catch (e) {}
- }());
+ if (this.props.cursor) {
+ this.editor.focus();
+ this.editor.setCursor(this.props.cursor);
+ }
- /* Node.js helper references. */
- var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
+ if (this.props.scroll) {
+ this.editor.scrollTo(this.props.scroll.x, this.props.scroll.y);
+ }
- /**
- * A specialized version of `_.filter` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Array} Returns the new filtered array.
- */
- function arrayFilter(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length,
- resIndex = 0,
- result = [];
-
- while (++index < length) {
- var value = array[index];
- if (predicate(value, index, array)) {
- result[resIndex++] = value;
+ if (this.props.editorDidMount) {
+ this.props.editorDidMount(this.editor, this.initCb);
+ }
}
- }
- return result;
- }
+ }, {
+ key: 'componentWillReceiveProps',
+ value: function componentWillReceiveProps(nextProps) {
- /**
- * Appends the elements of `values` to `array`.
- *
- * @private
- * @param {Array} array The array to modify.
- * @param {Array} values The values to append.
- * @returns {Array} Returns `array`.
- */
- function arrayPush(array, values) {
- var index = -1,
- length = values.length,
- offset = array.length;
+ if (this.props.value !== nextProps.value) {
+ this.hydrated = false;
+ }
- while (++index < length) {
- array[offset + index] = values[index];
- }
- return array;
- }
+ if (!this.props.resetCursorOnSet) {
+ this.cursorPos = this.editor.getCursor();
+ }
- /**
- * A specialized version of `_.some` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
- */
- function arraySome(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length;
+ this.hydrate(nextProps);
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
- }
+ if (!this.props.resetCursorOnSet) {
- /**
- * The base implementation of `_.times` without support for iteratee shorthands
- * or max array length checks.
- *
- * @private
- * @param {number} n The number of times to invoke `iteratee`.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the array of results.
- */
- function baseTimes(n, iteratee) {
- var index = -1,
- result = Array(n);
+ !this.props.autoScrollCursorOnSet && this.props.autoScrollCursorOnSet !== undefined ? this.editor.setCursor(this.cursorPos, null, { scroll: false }) : this.editor.setCursor(this.cursorPos);
+ }
+ }
+ }, {
+ key: 'componentWillUnmount',
+ value: function componentWillUnmount() {
- while (++index < n) {
- result[index] = iteratee(index);
- }
- return result;
- }
+ if (this.props.editorWillUnmount) {
+ this.props.editorWillUnmount(codemirror);
+ }
+ }
+ }, {
+ key: 'hydrate',
+ value: function hydrate(props) {
+ var _this3 = this;
- /**
- * The base implementation of `_.unary` without support for storing metadata.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @returns {Function} Returns the new capped function.
- */
- function baseUnary(func) {
- return function(value) {
- return func(value);
- };
- }
+ Object.keys(props.options || {}).forEach(function (key) {
+ return _this3.editor.setOption(key, props.options[key]);
+ });
- /**
- * Checks if a `cache` value for `key` exists.
- *
- * @private
- * @param {Object} cache The cache to query.
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function cacheHas(cache, key) {
- return cache.has(key);
- }
+ if (this.props.editorDidConfigure) {
+ this.props.editorDidConfigure(this.editor);
+ }
- /**
- * Gets the value at `key` of `object`.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {string} key The key of the property to get.
- * @returns {*} Returns the property value.
- */
- function getValue(object, key) {
- return object == null ? undefined : object[key];
- }
+ if (!this.hydrated) {
- /**
- * Converts `map` to its key-value pairs.
- *
- * @private
- * @param {Object} map The map to convert.
- * @returns {Array} Returns the key-value pairs.
- */
- function mapToArray(map) {
- var index = -1,
- result = Array(map.size);
+ var lastLine = this.editor.lastLine();
+ var lastChar = this.editor.getLine(this.editor.lastLine()).length;
- map.forEach(function(value, key) {
- result[++index] = [key, value];
- });
- return result;
- }
+ this.editor.replaceRange(props.value || '', { line: 0, ch: 0 }, { line: lastLine, ch: lastChar });
- /**
- * Creates a unary function that invokes `func` with its argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
- */
- function overArg(func, transform) {
- return function(arg) {
- return func(transform(arg));
- };
- }
+ if (this.props.onBeforeSet) {
+ this.props.onBeforeSet(this.editor, this.onBeforeSetCb);
+ }
- /**
- * Converts `set` to an array of its values.
- *
- * @private
- * @param {Object} set The set to convert.
- * @returns {Array} Returns the values.
- */
- function setToArray(set) {
- var index = -1,
- result = Array(set.size);
+ if (this.props.onBeforeSet) {
- set.forEach(function(value) {
- result[++index] = value;
- });
- return result;
- }
+ if (this.continuePreSet && this.props.onSet) {
- /** Used for built-in method references. */
- var arrayProto = Array.prototype,
- funcProto = Function.prototype,
- objectProto = Object.prototype;
+ this.props.onSet(this.editor, this.editor.getValue());
+ }
+ } else {
+ if (this.props.onSet) {
+ this.props.onSet(this.editor, this.editor.getValue());
+ }
+ }
+ }
- /** Used to detect overreaching core-js shims. */
- var coreJsData = root['__core-js_shared__'];
+ this.hydrated = true;
+ }
+ }, {
+ key: 'render',
+ value: function render() {
+ var _this4 = this;
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
+ var className = this.props.className ? 'react-codemirror2 ' + this.props.className : 'react-codemirror2';
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
+ return _react2.default.createElement('div', { className: className, ref: function ref(self) {
+ return _this4.ref = self;
+ } });
+ }
+ }]);
- /** Used to detect methods masquerading as native. */
- var maskSrcKey = (function() {
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
- return uid ? ('Symbol(src)_1.' + uid) : '';
- }());
+ return CodeMirror;
+ }(_react2.default.Component);
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto.toString;
+ exports.default = CodeMirror;
+
+/***/ }),
+/* 340 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' +
- funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
- );
+ // This is CodeMirror (http://codemirror.net), a code editor
+ // implemented in JavaScript on top of the browser's DOM.
+ //
+ // You can find some technical background for some of the code below
+ // at http://marijnhaverbeke.nl/blog/#cm-internals .
- /** Built-in value references. */
- var Buffer = moduleExports ? root.Buffer : undefined,
- Symbol = root.Symbol,
- Uint8Array = root.Uint8Array,
- propertyIsEnumerable = objectProto.propertyIsEnumerable,
- splice = arrayProto.splice,
- symToStringTag = Symbol ? Symbol.toStringTag : undefined;
-
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols = Object.getOwnPropertySymbols,
- nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
- nativeKeys = overArg(Object.keys, Object);
-
- /* Built-in method references that are verified to be native. */
- var DataView = getNative(root, 'DataView'),
- Map = getNative(root, 'Map'),
- Promise = getNative(root, 'Promise'),
- Set = getNative(root, 'Set'),
- WeakMap = getNative(root, 'WeakMap'),
- nativeCreate = getNative(Object, 'create');
-
- /** Used to detect maps, sets, and weakmaps. */
- var dataViewCtorString = toSource(DataView),
- mapCtorString = toSource(Map),
- promiseCtorString = toSource(Promise),
- setCtorString = toSource(Set),
- weakMapCtorString = toSource(WeakMap);
-
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = Symbol ? Symbol.prototype : undefined,
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
+ (function (global, factory) {
+ true ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global.CodeMirror = factory());
+ }(this, (function () { 'use strict';
- /**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Hash(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
+ // Kludges for bugs and behavior differences that can't be feature
+ // detected are enabled based on userAgent etc sniffing.
+ var userAgent = navigator.userAgent;
+ var platform = navigator.platform;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
+ var gecko = /gecko\/\d/i.test(userAgent);
+ var ie_upto10 = /MSIE \d/.test(userAgent);
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
+ var edge = /Edge\/(\d+)/.exec(userAgent);
+ var ie = ie_upto10 || ie_11up || edge;
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
+ var webkit = !edge && /WebKit\//.test(userAgent);
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
+ var chrome = !edge && /Chrome\//.test(userAgent);
+ var presto = /Opera\//.test(userAgent);
+ var safari = /Apple Computer/.test(navigator.vendor);
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
+ var phantom = /PhantomJS/.test(userAgent);
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
- this.size = 0;
- }
+ var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
+ var android = /Android/.test(userAgent);
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
+ var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
+ var mac = ios || /Mac/.test(platform);
+ var chromeOS = /\bCrOS\b/.test(userAgent);
+ var windows = /win/i.test(platform);
- /**
- * Removes `key` and its value from the hash.
- *
- * @private
- * @name delete
- * @memberOf Hash
- * @param {Object} hash The hash to modify.
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function hashDelete(key) {
- var result = this.has(key) && delete this.__data__[key];
- this.size -= result ? 1 : 0;
- return result;
- }
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
+ if (presto_version) { presto_version = Number(presto_version[1]); }
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
+ var captureRightClick = gecko || (ie && ie_version >= 9);
- /**
- * Gets the hash value for `key`.
- *
- * @private
- * @name get
- * @memberOf Hash
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function hashGet(key) {
- var data = this.__data__;
- if (nativeCreate) {
- var result = data[key];
- return result === HASH_UNDEFINED ? undefined : result;
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+
+ var rmClass = function(node, cls) {
+ var current = node.className;
+ var match = classTest(cls).exec(current);
+ if (match) {
+ var after = current.slice(match.index + match[0].length);
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
}
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
+ };
+
+ function removeChildren(e) {
+ for (var count = e.childNodes.length; count > 0; --count)
+ { e.removeChild(e.firstChild); }
+ return e
}
- /**
- * Checks if a hash value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Hash
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function hashHas(key) {
- var data = this.__data__;
- return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
+ function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e)
}
- /**
- * Sets the hash `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Hash
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the hash instance.
- */
- function hashSet(key, value) {
- var data = this.__data__;
- this.size += this.has(key) ? 0 : 1;
- data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
- return this;
+ function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) { e.className = className; }
+ if (style) { e.style.cssText = style; }
+ if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
+ else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
+ return e
+ }
+ // wrapper for elt, which removes the elt from the accessibility tree
+ function eltP(tag, content, className, style) {
+ var e = elt(tag, content, className, style);
+ e.setAttribute("role", "presentation");
+ return e
}
- // Add methods to `Hash`.
- Hash.prototype.clear = hashClear;
- Hash.prototype['delete'] = hashDelete;
- Hash.prototype.get = hashGet;
- Hash.prototype.has = hashHas;
- Hash.prototype.set = hashSet;
+ var range;
+ if (document.createRange) { range = function(node, start, end, endNode) {
+ var r = document.createRange();
+ r.setEnd(endNode || node, end);
+ r.setStart(node, start);
+ return r
+ }; }
+ else { range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ try { r.moveToElementText(node.parentNode); }
+ catch(e) { return r }
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r
+ }; }
- /**
- * Creates an list cache object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function ListCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
+ function contains(parent, child) {
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+ { child = child.parentNode; }
+ if (parent.contains)
+ { return parent.contains(child) }
+ do {
+ if (child.nodeType == 11) { child = child.host; }
+ if (child == parent) { return true }
+ } while (child = child.parentNode)
+ }
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
+ function activeElt() {
+ // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
+ // IE < 10 will throw when accessed while the page is loading or in an iframe.
+ // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
+ var activeElement;
+ try {
+ activeElement = document.activeElement;
+ } catch(e) {
+ activeElement = document.body || null;
}
+ while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
+ { activeElement = activeElement.shadowRoot.activeElement; }
+ return activeElement
}
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
+ function addClass(node, cls) {
+ var current = node.className;
+ if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
}
-
- /**
- * Removes `key` and its value from the list cache.
- *
- * @private
- * @name delete
- * @memberOf ListCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function listCacheDelete(key) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
-
- if (index < 0) {
- return false;
- }
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
- --this.size;
- return true;
+ function joinClasses(a, b) {
+ var as = a.split(" ");
+ for (var i = 0; i < as.length; i++)
+ { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
+ return b
}
- /**
- * Gets the list cache value for `key`.
- *
- * @private
- * @name get
- * @memberOf ListCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function listCacheGet(key) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
+ var selectInput = function(node) { node.select(); };
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
+ { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
+ else if (ie) // Suppress mysterious IE10 errors
+ { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
- return index < 0 ? undefined : data[index][1];
+ function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args)}
}
- /**
- * Checks if a list cache value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf ListCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function listCacheHas(key) {
- return assocIndexOf(this.__data__, key) > -1;
+ function copyObj(obj, target, overwrite) {
+ if (!target) { target = {}; }
+ for (var prop in obj)
+ { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+ { target[prop] = obj[prop]; } }
+ return target
}
- /**
- * Sets the list cache `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf ListCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the list cache instance.
- */
- function listCacheSet(key, value) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
-
- if (index < 0) {
- ++this.size;
- data.push([key, value]);
- } else {
- data[index][1] = value;
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ function countColumn(string, end, tabSize, startIndex, startValue) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) { end = string.length; }
+ }
+ for (var i = startIndex || 0, n = startValue || 0;;) {
+ var nextTab = string.indexOf("\t", i);
+ if (nextTab < 0 || nextTab >= end)
+ { return n + (end - i) }
+ n += nextTab - i;
+ n += tabSize - (n % tabSize);
+ i = nextTab + 1;
}
- return this;
}
- // Add methods to `ListCache`.
- ListCache.prototype.clear = listCacheClear;
- ListCache.prototype['delete'] = listCacheDelete;
- ListCache.prototype.get = listCacheGet;
- ListCache.prototype.has = listCacheHas;
- ListCache.prototype.set = listCacheSet;
-
- /**
- * Creates a map cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function MapCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
+ var Delayed = function() {this.id = null;};
+ Delayed.prototype.set = function (ms, f) {
+ clearTimeout(this.id);
+ this.id = setTimeout(f, ms);
+ };
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
+ function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ { if (array[i] == elt) { return i } }
+ return -1
}
- /**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
- function mapCacheClear() {
- this.size = 0;
- this.__data__ = {
- 'hash': new Hash,
- 'map': new (Map || ListCache),
- 'string': new Hash
- };
- }
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerGap = 30;
- /**
- * Removes `key` and its value from the map.
- *
- * @private
- * @name delete
- * @memberOf MapCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function mapCacheDelete(key) {
- var result = getMapData(this, key)['delete'](key);
- this.size -= result ? 1 : 0;
- return result;
- }
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var Pass = {toString: function(){return "CodeMirror.Pass"}};
- /**
- * Gets the map value for `key`.
- *
- * @private
- * @name get
- * @memberOf MapCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function mapCacheGet(key) {
- return getMapData(this, key).get(key);
+ // Reused option objects for setSelection & friends
+ var sel_dontScroll = {scroll: false};
+ var sel_mouse = {origin: "*mouse"};
+ var sel_move = {origin: "+move"};
+
+ // The inverse of countColumn -- find the offset that corresponds to
+ // a particular column.
+ function findColumn(string, goal, tabSize) {
+ for (var pos = 0, col = 0;;) {
+ var nextTab = string.indexOf("\t", pos);
+ if (nextTab == -1) { nextTab = string.length; }
+ var skipped = nextTab - pos;
+ if (nextTab == string.length || col + skipped >= goal)
+ { return pos + Math.min(skipped, goal - col) }
+ col += nextTab - pos;
+ col += tabSize - (col % tabSize);
+ pos = nextTab + 1;
+ if (col >= goal) { return pos }
+ }
}
- /**
- * Checks if a map value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf MapCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function mapCacheHas(key) {
- return getMapData(this, key).has(key);
+ var spaceStrs = [""];
+ function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ { spaceStrs.push(lst(spaceStrs) + " "); }
+ return spaceStrs[n]
}
- /**
- * Sets the map `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf MapCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the map cache instance.
- */
- function mapCacheSet(key, value) {
- var data = getMapData(this, key),
- size = data.size;
+ function lst(arr) { return arr[arr.length-1] }
- data.set(key, value);
- this.size += data.size == size ? 0 : 1;
- return this;
+ function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
+ return out
}
- // Add methods to `MapCache`.
- MapCache.prototype.clear = mapCacheClear;
- MapCache.prototype['delete'] = mapCacheDelete;
- MapCache.prototype.get = mapCacheGet;
- MapCache.prototype.has = mapCacheHas;
- MapCache.prototype.set = mapCacheSet;
+ function insertSorted(array, value, score) {
+ var pos = 0, priority = score(value);
+ while (pos < array.length && score(array[pos]) <= priority) { pos++; }
+ array.splice(pos, 0, value);
+ }
- /**
- *
- * Creates an array cache object to store unique values.
- *
- * @private
- * @constructor
- * @param {Array} [values] The values to cache.
- */
- function SetCache(values) {
- var index = -1,
- length = values == null ? 0 : values.length;
+ function nothing() {}
- this.__data__ = new MapCache;
- while (++index < length) {
- this.add(values[index]);
+ function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ nothing.prototype = base;
+ inst = new nothing();
}
+ if (props) { copyObj(props, inst); }
+ return inst
}
- /**
- * Adds `value` to the array cache.
- *
- * @private
- * @name add
- * @memberOf SetCache
- * @alias push
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache instance.
- */
- function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED);
- return this;
- }
-
- /**
- * Checks if `value` is in the array cache.
- *
- * @private
- * @name has
- * @memberOf SetCache
- * @param {*} value The value to search for.
- * @returns {number} Returns `true` if `value` is found, else `false`.
- */
- function setCacheHas(value) {
- return this.__data__.has(value);
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+ function isWordCharBasic(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
}
-
- // Add methods to `SetCache`.
- SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
- SetCache.prototype.has = setCacheHas;
-
- /**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Stack(entries) {
- var data = this.__data__ = new ListCache(entries);
- this.size = data.size;
+ function isWordChar(ch, helper) {
+ if (!helper) { return isWordCharBasic(ch) }
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
+ return helper.test(ch)
}
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new ListCache;
- this.size = 0;
+ function isEmpty(obj) {
+ for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
+ return true
}
- /**
- * Removes `key` and its value from the stack.
- *
- * @private
- * @name delete
- * @memberOf Stack
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function stackDelete(key) {
- var data = this.__data__,
- result = data['delete'](key);
+ // Extending unicode characters. A series of a non-extending char +
+ // any number of extending chars is treated as a single unit as far
+ // as editing and measuring is concerned. This is not fully correct,
+ // since some scripts/fonts/browsers also treat other configurations
+ // of code points as a group.
+ var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
- this.size = data.size;
- return result;
+ // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
+ function skipExtendingChars(str, pos, dir) {
+ while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
+ return pos
}
- /**
- * Gets the stack value for `key`.
- *
- * @private
- * @name get
- * @memberOf Stack
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function stackGet(key) {
- return this.__data__.get(key);
+ // Returns the value from the range [`from`; `to`] that satisfies
+ // `pred` and is closest to `from`. Assumes that at least `to`
+ // satisfies `pred`. Supports `from` being greater than `to`.
+ function findFirst(pred, from, to) {
+ // At any point we are certain `to` satisfies `pred`, don't know
+ // whether `from` does.
+ var dir = from > to ? -1 : 1;
+ for (;;) {
+ if (from == to) { return from }
+ var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
+ if (mid == from) { return pred(mid) ? from : to }
+ if (pred(mid)) { to = mid; }
+ else { from = mid + dir; }
+ }
}
- /**
- * Checks if a stack value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Stack
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function stackHas(key) {
- return this.__data__.has(key);
- }
+ // The display handles the DOM integration, both for input reading
+ // and content drawing. It holds references to DOM nodes and
+ // display-related state.
- /**
- * Sets the stack `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Stack
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the stack cache instance.
- */
- function stackSet(key, value) {
- var data = this.__data__;
- if (data instanceof ListCache) {
- var pairs = data.__data__;
- if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
- pairs.push([key, value]);
- this.size = ++data.size;
- return this;
- }
- data = this.__data__ = new MapCache(pairs);
- }
- data.set(key, value);
- this.size = data.size;
- return this;
- }
+ function Display(place, doc, input) {
+ var d = this;
+ this.input = input;
- // Add methods to `Stack`.
- Stack.prototype.clear = stackClear;
- Stack.prototype['delete'] = stackDelete;
- Stack.prototype.get = stackGet;
- Stack.prototype.has = stackHas;
- Stack.prototype.set = stackSet;
+ // Covers bottom-right square when both scrollbars are present.
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
+ // and h scrollbar is present.
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+ d.gutterFiller.setAttribute("cm-not-content", "true");
+ // Will contain the actual code, positioned to cover the viewport.
+ d.lineDiv = eltP("div", null, "CodeMirror-code");
+ // Elements are added to these to represent selection and cursors.
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
+ // A visibility: hidden element used to find the size of things.
+ d.measure = elt("div", null, "CodeMirror-measure");
+ // When lines outside of the viewport are measured, they are drawn in this.
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
+ d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+ null, "position: relative; outline: none");
+ var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
+ // Moved around its parent to cover visible view.
+ d.mover = elt("div", [lines], null, "position: relative");
+ // Set to the height of the document, allowing scrolling.
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ d.sizerWidth = null;
+ // Behavior of elts with overflow: auto and padding is
+ // inconsistent across browsers. This is used to ensure the
+ // scrollable area is big enough.
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
+ // Will contain the gutters, if any.
+ d.gutters = elt("div", null, "CodeMirror-gutters");
+ d.lineGutter = null;
+ // Actual scrollable element.
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
+ d.scroller.setAttribute("tabIndex", "-1");
+ // The element in which the editor lives.
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
- /**
- * Creates an array of the enumerable property names of the array-like `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @param {boolean} inherited Specify returning inherited property names.
- * @returns {Array} Returns the array of property names.
- */
- function arrayLikeKeys(value, inherited) {
- var isArr = isArray(value),
- isArg = !isArr && isArguments(value),
- isBuff = !isArr && !isArg && isBuffer(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? baseTimes(value.length, String) : [],
- length = result.length;
-
- for (var key in value) {
- if ((inherited || hasOwnProperty.call(value, key)) &&
- !(skipIndexes && (
- // Safari 9 has enumerable `arguments.length` in strict mode.
- key == 'length' ||
- // Node.js 0.10 has enumerable non-index properties on buffers.
- (isBuff && (key == 'offset' || key == 'parent')) ||
- // PhantomJS 2 has enumerable non-index properties on typed arrays.
- (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
- // Skip index properties.
- isIndex(key, length)
- ))) {
- result.push(key);
- }
- }
- return result;
- }
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
- /**
- * Gets the index at which the `key` is found in `array` of key-value pairs.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} key The key to search for.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function assocIndexOf(array, key) {
- var length = array.length;
- while (length--) {
- if (eq(array[length][0], key)) {
- return length;
- }
+ if (place) {
+ if (place.appendChild) { place.appendChild(d.wrapper); }
+ else { place(d.wrapper); }
}
- return -1;
- }
- /**
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
- * symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function baseGetAllKeys(object, keysFunc, symbolsFunc) {
- var result = keysFunc(object);
- return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
- }
+ // Current rendered range (may be bigger than the view window).
+ d.viewFrom = d.viewTo = doc.first;
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
+ // Information about the rendered lines.
+ d.view = [];
+ d.renderedView = null;
+ // Holds info about a single rendered line when it was rendered
+ // for measurement, while not in view.
+ d.externalMeasured = null;
+ // Empty space (in pixels) above the view
+ d.viewOffset = 0;
+ d.lastWrapHeight = d.lastWrapWidth = 0;
+ d.updateLineNumbers = null;
- /**
- * The base implementation of `getTag` without fallbacks for buggy environments.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- function baseGetTag(value) {
- if (value == null) {
- return value === undefined ? undefinedTag : nullTag;
- }
- return (symToStringTag && symToStringTag in Object(value))
- ? getRawTag(value)
- : objectToString(value);
- }
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
+ d.scrollbarsClipped = false;
- /**
- * The base implementation of `_.isArguments`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- */
- function baseIsArguments(value) {
- return isObjectLike(value) && baseGetTag(value) == argsTag;
- }
+ // Used to only resize the line number gutter when necessary (when
+ // the amount of lines crosses a boundary that makes its width change)
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+ // Set to true when a non-horizontal-scrolling line widget is
+ // added. As an optimization, line widget aligning is skipped when
+ // this is false.
+ d.alignWidgets = false;
- /**
- * The base implementation of `_.isEqual` which supports partial comparisons
- * and tracks traversed objects.
- *
- * @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {boolean} bitmask The bitmask flags.
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
- function baseIsEqual(value, other, bitmask, customizer, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
- return value !== value && other !== other;
- }
- return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
- }
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
- /**
- * A specialized version of `baseIsEqual` for arrays and objects which performs
- * deep comparisons and tracks traversed objects enabling objects with circular
- * references to be compared.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
- var objIsArr = isArray(object),
- othIsArr = isArray(other),
- objTag = objIsArr ? arrayTag : getTag(object),
- othTag = othIsArr ? arrayTag : getTag(other);
+ // Tracks the maximum line length so that the horizontal scrollbar
+ // can be kept static when scrolling.
+ d.maxLine = null;
+ d.maxLineLength = 0;
+ d.maxLineChanged = false;
- objTag = objTag == argsTag ? objectTag : objTag;
- othTag = othTag == argsTag ? objectTag : othTag;
+ // Used for measuring wheel scrolling granularity
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
- var objIsObj = objTag == objectTag,
- othIsObj = othTag == objectTag,
- isSameTag = objTag == othTag;
+ // True when shift is held down.
+ d.shift = false;
- if (isSameTag && isBuffer(object)) {
- if (!isBuffer(other)) {
- return false;
- }
- objIsArr = true;
- objIsObj = false;
- }
- if (isSameTag && !objIsObj) {
- stack || (stack = new Stack);
- return (objIsArr || isTypedArray(object))
- ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
- : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
- var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
- othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
+ // Used to track whether anything happened since the context menu
+ // was opened.
+ d.selForContextMenu = null;
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object,
- othUnwrapped = othIsWrapped ? other.value() : other;
+ d.activeTouch = null;
- stack || (stack = new Stack);
- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new Stack);
- return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
+ input.init(d);
}
- /**
- * The base implementation of `_.isNative` without bad shim checks.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- */
- function baseIsNative(value) {
- if (!isObject(value) || isMasked(value)) {
- return false;
+ // Find the line object corresponding to the given line number.
+ function getLine(doc, n) {
+ n -= doc.first;
+ if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
+ var chunk = doc;
+ while (!chunk.lines) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break }
+ n -= sz;
+ }
}
- var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
- return pattern.test(toSource(value));
- }
-
- /**
- * The base implementation of `_.isTypedArray` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- */
- function baseIsTypedArray(value) {
- return isObjectLike(value) &&
- isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
+ return chunk.lines[n]
}
- /**
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function baseKeys(object) {
- if (!isPrototype(object)) {
- return nativeKeys(object);
- }
- var result = [];
- for (var key in Object(object)) {
- if (hasOwnProperty.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
+ // Get the part of a document between two positions, as an array of
+ // strings.
+ function getBetween(doc, start, end) {
+ var out = [], n = start.line;
+ doc.iter(start.line, end.line + 1, function (line) {
+ var text = line.text;
+ if (n == end.line) { text = text.slice(0, end.ch); }
+ if (n == start.line) { text = text.slice(start.ch); }
+ out.push(text);
+ ++n;
+ });
+ return out
+ }
+ // Get the lines between from and to, as array of strings.
+ function getLines(doc, from, to) {
+ var out = [];
+ doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
+ return out
}
- /**
- * A specialized version of `baseIsEqualDeep` for arrays with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Array} array The array to compare.
- * @param {Array} other The other array to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
- function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
- arrLength = array.length,
- othLength = other.length;
+ // Update the height of a line, propagating the height change
+ // upwards to parent nodes.
+ function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
+ }
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(array);
- if (stacked && stack.get(other)) {
- return stacked == other;
+ // Given a line object, find its line number by walking up through
+ // its parent links.
+ function lineNo(line) {
+ if (line.parent == null) { return null }
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) { break }
+ no += chunk.children[i].chunkSize();
+ }
}
- var index = -1,
- result = true,
- seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
-
- stack.set(array, other);
- stack.set(other, array);
-
- // Ignore non-index properties.
- while (++index < arrLength) {
- var arrValue = array[index],
- othValue = other[index];
+ return no + cur.first
+ }
- if (customizer) {
- var compared = isPartial
- ? customizer(othValue, arrValue, index, other, array, stack)
- : customizer(arrValue, othValue, index, array, other, stack);
- }
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- }
- // Recursively compare arrays (susceptible to call stack limits).
- if (seen) {
- if (!arraySome(other, function(othValue, othIndex) {
- if (!cacheHas(seen, othIndex) &&
- (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- return seen.push(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(
- arrValue === othValue ||
- equalFunc(arrValue, othValue, bitmask, customizer, stack)
- )) {
- result = false;
- break;
+ // Find the line at the given vertical position, using the height
+ // information in the document tree.
+ function lineAtHeight(chunk, h) {
+ var n = chunk.first;
+ outer: do {
+ for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
+ var child = chunk.children[i$1], ch = child.height;
+ if (h < ch) { chunk = child; continue outer }
+ h -= ch;
+ n += child.chunkSize();
}
+ return n
+ } while (!chunk.lines)
+ var i = 0;
+ for (; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) { break }
+ h -= lh;
}
- stack['delete'](array);
- stack['delete'](other);
- return result;
+ return n + i
}
- /**
- * A specialized version of `baseIsEqualDeep` for comparing objects of
- * the same `toStringTag`.
- *
- * **Note:** This function only supports comparing values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {string} tag The `toStringTag` of the objects to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
- switch (tag) {
- case dataViewTag:
- if ((object.byteLength != other.byteLength) ||
- (object.byteOffset != other.byteOffset)) {
- return false;
- }
- object = object.buffer;
- other = other.buffer;
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
- case arrayBufferTag:
- if ((object.byteLength != other.byteLength) ||
- !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
- return false;
- }
- return true;
+ function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber))
+ }
- case boolTag:
- case dateTag:
- case numberTag:
- // Coerce booleans to `1` or `0` and dates to milliseconds.
- // Invalid dates are coerced to `NaN`.
- return eq(+object, +other);
+ // A Pos instance represents a position within the text.
+ function Pos(line, ch, sticky) {
+ if ( sticky === void 0 ) sticky = null;
- case errorTag:
- return object.name == other.name && object.message == other.message;
+ if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
+ this.line = line;
+ this.ch = ch;
+ this.sticky = sticky;
+ }
- case regexpTag:
- case stringTag:
- // Coerce regexes to strings and treat strings, primitives and objects,
- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
- // for more details.
- return object == (other + '');
+ // Compare two positions, return 0 if they are the same, a negative
+ // number when a is less, and a positive number otherwise.
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
- case mapTag:
- var convert = mapToArray;
+ function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
- case setTag:
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
- convert || (convert = setToArray);
+ function copyPos(x) {return Pos(x.line, x.ch)}
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
- if (object.size != other.size && !isPartial) {
- return false;
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked) {
- return stacked == other;
- }
- bitmask |= COMPARE_UNORDERED_FLAG;
+ // Most of the external API clips given positions to make sure they
+ // actually exist within the document.
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
+ function clipPos(doc, pos) {
+ if (pos.line < doc.first) { return Pos(doc.first, 0) }
+ var last = doc.first + doc.size - 1;
+ if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
+ return clipToLen(pos, getLine(doc, pos.line).text.length)
+ }
+ function clipToLen(pos, linelen) {
+ var ch = pos.ch;
+ if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
+ else if (ch < 0) { return Pos(pos.line, 0) }
+ else { return pos }
+ }
+ function clipPosArray(doc, array) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
+ return out
+ }
- // Recursively compare objects (susceptible to call stack limits).
- stack.set(object, other);
- var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
- stack['delete'](object);
- return result;
+ // Optimize some code when these features are not used.
+ var sawReadOnlySpans = false;
+ var sawCollapsedSpans = false;
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
+ function seeReadOnlySpans() {
+ sawReadOnlySpans = true;
}
- /**
- * A specialized version of `baseIsEqualDeep` for objects with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
- objProps = getAllKeys(object),
- objLength = objProps.length,
- othProps = getAllKeys(other),
- othLength = othProps.length;
-
- if (objLength != othLength && !isPartial) {
- return false;
- }
- var index = objLength;
- while (index--) {
- var key = objProps[index];
- if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
- return false;
- }
- }
- // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
-
- var skipCtor = isPartial;
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key],
- othValue = other[key];
-
- if (customizer) {
- var compared = isPartial
- ? customizer(othValue, objValue, key, other, object, stack)
- : customizer(objValue, othValue, key, object, other, stack);
- }
- // Recursively compare objects (susceptible to call stack limits).
- if (!(compared === undefined
- ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
- : compared
- )) {
- result = false;
- break;
- }
- skipCtor || (skipCtor = key == 'constructor');
- }
- if (result && !skipCtor) {
- var objCtor = object.constructor,
- othCtor = other.constructor;
-
- // Non `Object` object instances with different constructors are not equal.
- if (objCtor != othCtor &&
- ('constructor' in object && 'constructor' in other) &&
- !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
- typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- result = false;
- }
- }
- stack['delete'](object);
- stack['delete'](other);
- return result;
+ function seeCollapsedSpans() {
+ sawCollapsedSpans = true;
}
- /**
- * Creates an array of own enumerable property names and symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function getAllKeys(object) {
- return baseGetAllKeys(object, keys, getSymbols);
- }
+ // TEXTMARKER SPANS
- /**
- * Gets the data for `map`.
- *
- * @private
- * @param {Object} map The map to query.
- * @param {string} key The reference key.
- * @returns {*} Returns the map data.
- */
- function getMapData(map, key) {
- var data = map.__data__;
- return isKeyable(key)
- ? data[typeof key == 'string' ? 'string' : 'hash']
- : data.map;
+ function MarkedSpan(marker, from, to) {
+ this.marker = marker;
+ this.from = from; this.to = to;
}
- /**
- * Gets the native function at `key` of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {string} key The key of the method to get.
- * @returns {*} Returns the function if it's native, else `undefined`.
- */
- function getNative(object, key) {
- var value = getValue(object, key);
- return baseIsNative(value) ? value : undefined;
+ // Search an array of spans for a span matching the given marker.
+ function getMarkedSpanFor(spans, marker) {
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) { return span }
+ } }
+ }
+ // Remove a span from an array, returning undefined if no spans are
+ // left (we don't store arrays for lines without spans).
+ function removeMarkedSpan(spans, span) {
+ var r;
+ for (var i = 0; i < spans.length; ++i)
+ { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
+ return r
+ }
+ // Add a span to a line.
+ function addMarkedSpan(line, span) {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ span.marker.attachLine(line);
}
- /**
- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the raw `toStringTag`.
- */
- function getRawTag(value) {
- var isOwn = hasOwnProperty.call(value, symToStringTag),
- tag = value[symToStringTag];
-
- try {
- value[symToStringTag] = undefined;
- var unmasked = true;
- } catch (e) {}
-
- var result = nativeObjectToString.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag] = tag;
- } else {
- delete value[symToStringTag];
+ // Used for the algorithm that adjusts markers for a change in the
+ // document. These functions cut an array of spans at a given
+ // character position, returning an array of remaining chunks (or
+ // undefined if nothing remains).
+ function markedSpansBefore(old, startCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
}
- }
- return result;
+ } }
+ return nw
+ }
+ function markedSpansAfter(old, endCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+ span.to == null ? null : span.to - endCh));
+ }
+ } }
+ return nw
}
- /**
- * Creates an array of the own enumerable symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
- var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
- if (object == null) {
- return [];
- }
- object = Object(object);
- return arrayFilter(nativeGetSymbols(object), function(symbol) {
- return propertyIsEnumerable.call(object, symbol);
- });
- };
+ // Given a change object, compute the new set of marker spans that
+ // cover the line in which the change took place. Removes spans
+ // entirely within the change, reconnects spans belonging to the
+ // same marker that appear on both sides of the change, and cuts off
+ // spans partially within the change. Returns an array of span
+ // arrays with one element for each line in (after) the change.
+ function stretchSpansOverChange(doc, change) {
+ if (change.full) { return null }
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+ if (!oldFirst && !oldLast) { return null }
- /**
- * Gets the `toStringTag` of `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- var getTag = baseGetTag;
-
- // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
- if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
- (Map && getTag(new Map) != mapTag) ||
- (Promise && getTag(Promise.resolve()) != promiseTag) ||
- (Set && getTag(new Set) != setTag) ||
- (WeakMap && getTag(new WeakMap) != weakMapTag)) {
- getTag = function(value) {
- var result = baseGetTag(value),
- Ctor = result == objectTag ? value.constructor : undefined,
- ctorString = Ctor ? toSource(Ctor) : '';
-
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString: return dataViewTag;
- case mapCtorString: return mapTag;
- case promiseCtorString: return promiseTag;
- case setCtorString: return setTag;
- case weakMapCtorString: return weakMapTag;
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+ // Next, merge those two ends
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) { span.to = startCh; }
+ else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
}
}
- return result;
- };
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i$1 = 0; i$1 < last.length; ++i$1) {
+ var span$1 = last[i$1];
+ if (span$1.to != null) { span$1.to += offset; }
+ if (span$1.from == null) {
+ var found$1 = getMarkedSpanFor(first, span$1.marker);
+ if (!found$1) {
+ span$1.from = offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ } else {
+ span$1.from += offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ }
+ }
+ // Make sure we didn't create any zero-length spans
+ if (first) { first = clearEmptySpans(first); }
+ if (last && last != first) { last = clearEmptySpans(last); }
+
+ var newMarkers = [first];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = change.text.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ { for (var i$2 = 0; i$2 < first.length; ++i$2)
+ { if (first[i$2].to == null)
+ { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
+ for (var i$3 = 0; i$3 < gap; ++i$3)
+ { newMarkers.push(gapMarkers); }
+ newMarkers.push(last);
+ }
+ return newMarkers
}
- /**
- * 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) {
- length = length == null ? MAX_SAFE_INTEGER : length;
- return !!length &&
- (typeof value == 'number' || reIsUint.test(value)) &&
- (value > -1 && value % 1 == 0 && value < length);
+ // Remove spans that are empty and don't have a clearWhenEmpty
+ // option of false.
+ function clearEmptySpans(spans) {
+ for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+ { spans.splice(i--, 1); }
+ }
+ if (!spans.length) { return null }
+ return spans
}
- /**
- * Checks if `value` is suitable for use as unique object key.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
- */
- function isKeyable(value) {
- var type = typeof value;
- return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
- ? (value !== '__proto__')
- : (value === null);
+ // Used to 'clip' out readOnly ranges when making a change.
+ function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function (line) {
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ { (markers || (markers = [])).push(mark); }
+ } }
+ });
+ if (!markers) { return null }
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var mk = markers[i], m = mk.find(0);
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+ { newParts.push({from: p.from, to: m.from}); }
+ if (dto > 0 || !mk.inclusiveRight && !dto)
+ { newParts.push({from: m.to, to: p.to}); }
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 3;
+ }
+ }
+ return parts
}
- /**
- * Checks if `func` has its source masked.
- *
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
- */
- function isMasked(func) {
- return !!maskSrcKey && (maskSrcKey in func);
+ // Connect or disconnect spans from a line.
+ function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.detachLine(line); }
+ line.markedSpans = null;
+ }
+ function attachMarkedSpans(line, spans) {
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.attachLine(line); }
+ line.markedSpans = spans;
}
- /**
- * Checks if `value` is likely a prototype object.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
- */
- function isPrototype(value) {
- var Ctor = value && value.constructor,
- proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
+ // Helpers used when computing which overlapping collapsed span
+ // counts as the larger one.
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
- return value === proto;
+ // Returns a number indicating which of two overlapping collapsed
+ // spans is larger (and thus includes the other). Falls back to
+ // comparing ids when the spans cover exactly the same range.
+ function compareCollapsedMarkers(a, b) {
+ var lenDiff = a.lines.length - b.lines.length;
+ if (lenDiff != 0) { return lenDiff }
+ var aPos = a.find(), bPos = b.find();
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
+ if (fromCmp) { return -fromCmp }
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
+ if (toCmp) { return toCmp }
+ return b.id - a.id
}
- /**
- * Converts `value` to a string using `Object.prototype.toString`.
- *
- * @private
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- */
- function objectToString(value) {
- return nativeObjectToString.call(value);
+ // Find out whether a line ends or starts in a collapsed span. If
+ // so, return the marker for that span.
+ function collapsedSpanAtSide(line, start) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+ { found = sp.marker; }
+ } }
+ return found
}
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
- /**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to convert.
- * @returns {string} Returns the source code.
- */
- function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
- try {
- return (func + '');
- } catch (e) {}
- }
- return '';
+ // Test whether there exists a collapsed span that partially
+ // overlaps (covers the start or end, but not both) of a new span.
+ // Such overlap is not allowed.
+ function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
+ var line = getLine(doc, lineNo$$1);
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ var found = sp.marker.find(0);
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
+ if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
+ fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
+ { return true }
+ } }
}
- /**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
- function eq(value, other) {
- return value === other || (value !== value && other !== other);
+ // A visual line is a line as drawn on the screen. Folding, for
+ // example, can cause multiple logical lines to appear on the same
+ // visual line. This finds the start of the visual line that the
+ // given line is part of (usually that is the line itself).
+ function visualLine(line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ { line = merged.find(-1, true).line; }
+ return line
}
- /**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
- var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
- return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
- !propertyIsEnumerable.call(value, 'callee');
- };
-
- /**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
- var isArray = Array.isArray;
-
- /**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
- function isArrayLike(value) {
- return value != null && isLength(value.length) && !isFunction(value);
+ function visualLineEnd(line) {
+ var merged;
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return line
}
- /**
- * Checks if `value` is a buffer.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
- * @example
- *
- * _.isBuffer(new Buffer(2));
- * // => true
- *
- * _.isBuffer(new Uint8Array(2));
- * // => false
- */
- var isBuffer = nativeIsBuffer || stubFalse;
-
- /**
- * Performs a deep comparison between two values to determine if they are
- * equivalent.
- *
- * **Note:** This method supports comparing arrays, array buffers, booleans,
- * date objects, error objects, maps, numbers, `Object` objects, regexes,
- * sets, strings, symbols, and typed arrays. `Object` objects are compared
- * by their own, not inherited, enumerable properties. Functions and DOM
- * nodes are compared by strict equality, i.e. `===`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.isEqual(object, other);
- * // => true
- *
- * object === other;
- * // => false
- */
- function isEqual(value, other) {
- return baseIsEqual(value, other);
+ // Returns an array of logical lines that continue the visual line
+ // started by the argument, or undefined if there are no such lines.
+ function visualLineContinued(line) {
+ var merged, lines;
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line
+ ;(lines || (lines = [])).push(line);
+ }
+ return lines
}
- /**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- *
- * _.isFunction(/abc/);
- * // => false
- */
- function isFunction(value) {
- if (!isObject(value)) {
- return false;
- }
- // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 9 which returns 'object' for typed arrays and other constructors.
- var tag = baseGetTag(value);
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
+ // Get the line number of the start of the visual line that the
+ // given line number is part of.
+ function visualLineNo(doc, lineN) {
+ var line = getLine(doc, lineN), vis = visualLine(line);
+ if (line == vis) { return lineN }
+ return lineNo(vis)
}
- /**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
- function isLength(value) {
- return typeof value == 'number' &&
- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+ // Get the line number of the start of the next visual line after
+ // the given line.
+ function visualLineEndNo(doc, lineN) {
+ if (lineN > doc.lastLine()) { return lineN }
+ var line = getLine(doc, lineN), merged;
+ if (!lineIsHidden(doc, line)) { return lineN }
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return lineNo(line) + 1
}
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
+ // Compute whether a line is hidden. Lines count as hidden when they
+ // are part of a visual line that starts with another line, or when
+ // they are entirely covered by collapsed, non-widget span.
+ function lineIsHidden(doc, line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ if (sp.from == null) { return true }
+ if (sp.marker.widgetNode) { continue }
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+ { return true }
+ } }
}
-
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return value != null && typeof value == 'object';
+ function lineIsHiddenInner(doc, line, span) {
+ if (span.to == null) {
+ var end = span.marker.find(1, true);
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
+ }
+ if (span.marker.inclusiveRight && span.to == line.text.length)
+ { return true }
+ for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+ (sp.to == null || sp.to != span.from) &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(doc, line, sp)) { return true }
+ }
}
- /**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
- */
- var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
-
- /**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
- function keys(object) {
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
+ // Find the height above the given line.
+ function heightAtLine(lineObj) {
+ lineObj = visualLine(lineObj);
- /**
- * This method returns a new empty array.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {Array} Returns the new empty array.
- * @example
- *
- * var arrays = _.times(2, _.stubArray);
- *
- * console.log(arrays);
- * // => [[], []]
- *
- * console.log(arrays[0] === arrays[1]);
- * // => false
- */
- function stubArray() {
- return [];
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) { break }
+ else { h += line.height; }
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
+ var cur = p.children[i$1];
+ if (cur == chunk) { break }
+ else { h += cur.height; }
+ }
+ }
+ return h
}
- /**
- * This method returns `false`.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {boolean} Returns `false`.
- * @example
- *
- * _.times(2, _.stubFalse);
- * // => [false, false]
- */
- function stubFalse() {
- return false;
+ // Compute the character length of a line, taking into account
+ // collapsed ranges (see markText) that might hide parts, and join
+ // other lines onto it.
+ function lineLength(line) {
+ if (line.height == 0) { return 0 }
+ var len = line.text.length, merged, cur = line;
+ while (merged = collapsedSpanAtStart(cur)) {
+ var found = merged.find(0, true);
+ cur = found.from.line;
+ len += found.from.ch - found.to.ch;
+ }
+ cur = line;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found$1 = merged.find(0, true);
+ len -= cur.text.length - found$1.from.ch;
+ cur = found$1.to.line;
+ len += cur.text.length - found$1.to.ch;
+ }
+ return len
}
- module.exports = isEqual;
-
- /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(314)(module)))
-
-/***/ }),
-/* 314 */
-/***/ (function(module, exports) {
-
- module.exports = function(module) {
- if(!module.webpackPolyfill) {
- module.deprecate = function() {};
- module.paths = [];
- // module.parent = undefined by default
- module.children = [];
- module.webpackPolyfill = 1;
- }
- return module;
- }
-
-
-/***/ }),
-/* 315 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var React = __webpack_require__(298);
- var factory = __webpack_require__(316);
-
- // Hack to grab NoopUpdateQueue from isomorphic React
- var ReactNoopUpdateQueue = new React.Component().updater;
-
- module.exports = factory(
- React.Component,
- React.isValidElement,
- ReactNoopUpdateQueue
- );
-
-
-/***/ }),
-/* 316 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _assign = __webpack_require__(317);
-
- var emptyObject = __webpack_require__(318);
- var _invariant = __webpack_require__(303);
-
- if (process.env.NODE_ENV !== 'production') {
- var warning = __webpack_require__(304);
+ // Find the longest line in the document.
+ function findMaxLine(cm) {
+ var d = cm.display, doc = cm.doc;
+ d.maxLine = getLine(doc, doc.first);
+ d.maxLineLength = lineLength(d.maxLine);
+ d.maxLineChanged = true;
+ doc.iter(function (line) {
+ var len = lineLength(line);
+ if (len > d.maxLineLength) {
+ d.maxLineLength = len;
+ d.maxLine = line;
+ }
+ });
}
- var MIXINS_KEY = 'mixins';
+ // BIDI HELPERS
- // Helper function to allow the creation of anonymous functions which do not
- // have .name set to the name of the variable being assigned to.
- function identity(fn) {
- return fn;
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) { return f(from, to, "ltr", 0) }
+ var found = false;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from || from == to && part.to == from) {
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
+ found = true;
+ }
+ }
+ if (!found) { f(from, to, "ltr"); }
}
- var ReactPropTypeLocationNames;
- if (process.env.NODE_ENV !== 'production') {
- ReactPropTypeLocationNames = {
- prop: 'prop',
- context: 'context',
- childContext: 'child context',
- };
- } else {
- ReactPropTypeLocationNames = {};
+ var bidiOther = null;
+ function getBidiPartAt(order, ch, sticky) {
+ var found;
+ bidiOther = null;
+ for (var i = 0; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < ch && cur.to > ch) { return i }
+ if (cur.to == ch) {
+ if (cur.from != cur.to && sticky == "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ if (cur.from == ch) {
+ if (cur.from != cur.to && sticky != "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ }
+ return found != null ? found : bidiOther
}
- function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
- /**
- * Policies that describe methods in `ReactClassInterface`.
- */
-
+ // Bidirectional ordering algorithm
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+ // that this (partially) implements.
- var injectedMixins = [];
+ // One-char codes used for character types:
+ // L (L): Left-to-Right
+ // R (R): Right-to-Left
+ // r (AL): Right-to-Left Arabic
+ // 1 (EN): European Number
+ // + (ES): European Number Separator
+ // % (ET): European Number Terminator
+ // n (AN): Arabic Number
+ // , (CS): Common Number Separator
+ // m (NSM): Non-Spacing Mark
+ // b (BN): Boundary Neutral
+ // s (B): Paragraph Separator
+ // t (S): Segment Separator
+ // w (WS): Whitespace
+ // N (ON): Other Neutrals
- /**
- * Composite components are higher-level components that compose other composite
- * or host components.
- *
- * To create a new type of `ReactClass`, pass a specification of
- * your new class to `React.createClass`. The only requirement of your class
- * specification is that you implement a `render` method.
- *
- * var MyComponent = React.createClass({
- * render: function() {
- * return
Hello World
;
- * }
- * });
- *
- * The class specification supports a specific protocol of methods that have
- * special meaning (e.g. `render`). See `ReactClassInterface` for
- * more the comprehensive protocol. Any other properties and methods in the
- * class specification will be available on the prototype.
- *
- * @interface ReactClassInterface
- * @internal
- */
- var ReactClassInterface = {
-
- /**
- * An array of Mixin objects to include when defining your component.
- *
- * @type {array}
- * @optional
- */
- mixins: 'DEFINE_MANY',
-
- /**
- * An object containing properties and methods that should be defined on
- * the component's constructor instead of its prototype (static methods).
- *
- * @type {object}
- * @optional
- */
- statics: 'DEFINE_MANY',
-
- /**
- * Definition of prop types for this component.
- *
- * @type {object}
- * @optional
- */
- propTypes: 'DEFINE_MANY',
-
- /**
- * Definition of context types for this component.
- *
- * @type {object}
- * @optional
- */
- contextTypes: 'DEFINE_MANY',
-
- /**
- * Definition of context types this component sets for its children.
- *
- * @type {object}
- * @optional
- */
- childContextTypes: 'DEFINE_MANY',
-
- // ==== Definition methods ====
-
- /**
- * Invoked when the component is mounted. Values in the mapping will be set on
- * `this.props` if that prop is not specified (i.e. using an `in` check).
- *
- * This method is invoked before `getInitialState` and therefore cannot rely
- * on `this.state` or use `this.setState`.
- *
- * @return {object}
- * @optional
- */
- getDefaultProps: 'DEFINE_MANY_MERGED',
-
- /**
- * Invoked once before the component is mounted. The return value will be used
- * as the initial value of `this.state`.
- *
- * getInitialState: function() {
- * return {
- * isOn: false,
- * fooBaz: new BazFoo()
- * }
- * }
- *
- * @return {object}
- * @optional
- */
- getInitialState: 'DEFINE_MANY_MERGED',
-
- /**
- * @return {object}
- * @optional
- */
- getChildContext: 'DEFINE_MANY_MERGED',
-
- /**
- * Uses props from `this.props` and state from `this.state` to render the
- * structure of the component.
- *
- * No guarantees are made about when or how often this method is invoked, so
- * it must not have side effects.
- *
- * render: function() {
- * var name = this.props.name;
- * return
Hello, {name}!
;
- * }
- *
- * @return {ReactComponent}
- * @nosideeffects
- * @required
- */
- render: 'DEFINE_ONCE',
-
- // ==== Delegate methods ====
-
- /**
- * Invoked when the component is initially created and about to be mounted.
- * This may have side effects, but any external subscriptions or data created
- * by this method must be cleaned up in `componentWillUnmount`.
- *
- * @optional
- */
- componentWillMount: 'DEFINE_MANY',
-
- /**
- * Invoked when the component has been mounted and has a DOM representation.
- * However, there is no guarantee that the DOM node is in the document.
- *
- * Use this as an opportunity to operate on the DOM when the component has
- * been mounted (initialized and rendered) for the first time.
- *
- * @param {DOMElement} rootNode DOM element representing the component.
- * @optional
- */
- componentDidMount: 'DEFINE_MANY',
-
- /**
- * Invoked before the component receives new props.
- *
- * Use this as an opportunity to react to a prop transition by updating the
- * state using `this.setState`. Current props are accessed via `this.props`.
- *
- * componentWillReceiveProps: function(nextProps, nextContext) {
- * this.setState({
- * likesIncreasing: nextProps.likeCount > this.props.likeCount
- * });
- * }
- *
- * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
- * transition may cause a state change, but the opposite is not true. If you
- * need it, you are probably looking for `componentWillUpdate`.
- *
- * @param {object} nextProps
- * @optional
- */
- componentWillReceiveProps: 'DEFINE_MANY',
-
- /**
- * Invoked while deciding if the component should be updated as a result of
- * receiving new props, state and/or context.
- *
- * Use this as an opportunity to `return false` when you're certain that the
- * transition to the new props/state/context will not require a component
- * update.
- *
- * shouldComponentUpdate: function(nextProps, nextState, nextContext) {
- * return !equal(nextProps, this.props) ||
- * !equal(nextState, this.state) ||
- * !equal(nextContext, this.context);
- * }
- *
- * @param {object} nextProps
- * @param {?object} nextState
- * @param {?object} nextContext
- * @return {boolean} True if the component should update.
- * @optional
- */
- shouldComponentUpdate: 'DEFINE_ONCE',
-
- /**
- * Invoked when the component is about to update due to a transition from
- * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
- * and `nextContext`.
- *
- * Use this as an opportunity to perform preparation before an update occurs.
- *
- * NOTE: You **cannot** use `this.setState()` in this method.
- *
- * @param {object} nextProps
- * @param {?object} nextState
- * @param {?object} nextContext
- * @param {ReactReconcileTransaction} transaction
- * @optional
- */
- componentWillUpdate: 'DEFINE_MANY',
-
- /**
- * Invoked when the component's DOM representation has been updated.
- *
- * Use this as an opportunity to operate on the DOM when the component has
- * been updated.
- *
- * @param {object} prevProps
- * @param {?object} prevState
- * @param {?object} prevContext
- * @param {DOMElement} rootNode DOM element representing the component.
- * @optional
- */
- componentDidUpdate: 'DEFINE_MANY',
-
- /**
- * Invoked when the component is about to be removed from its parent and have
- * its DOM representation destroyed.
- *
- * Use this as an opportunity to deallocate any external resources.
- *
- * NOTE: There is no `componentDidUnmount` since your component will have been
- * destroyed by that point.
- *
- * @optional
- */
- componentWillUnmount: 'DEFINE_MANY',
-
- // ==== Advanced methods ====
-
- /**
- * Updates the component's currently mounted DOM representation.
- *
- * By default, this implements React's rendering and reconciliation algorithm.
- * Sophisticated clients may wish to override this.
- *
- * @param {ReactReconcileTransaction} transaction
- * @internal
- * @overridable
- */
- updateComponent: 'OVERRIDE_BASE'
+ // Returns null if characters are ordered as they appear
+ // (left-to-right), or an array of sections ({from, to, level}
+ // objects) in the order in which they occur visually.
+ var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
+ // Character types for codepoints 0x600 to 0x6f9
+ var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
+ function charType(code) {
+ if (code <= 0xf7) { return lowTypes.charAt(code) }
+ else if (0x590 <= code && code <= 0x5f4) { return "R" }
+ else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
+ else if (0x6ee <= code && code <= 0x8ac) { return "r" }
+ else if (0x2000 <= code && code <= 0x200b) { return "w" }
+ else if (code == 0x200c) { return "b" }
+ else { return "L" }
+ }
- };
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
- /**
- * Mapping from class specification keys to special processing functions.
- *
- * Although these are declared like instance properties in the specification
- * when defining classes using `React.createClass`, they are actually static
- * and are accessible on the constructor instead of the prototype. Despite
- * being static, they must be defined outside of the "statics" key under
- * which all other static methods are defined.
- */
- var RESERVED_SPEC_KEYS = {
- displayName: function (Constructor, displayName) {
- Constructor.displayName = displayName;
- },
- mixins: function (Constructor, mixins) {
- if (mixins) {
- for (var i = 0; i < mixins.length; i++) {
- mixSpecIntoComponent(Constructor, mixins[i]);
- }
- }
- },
- childContextTypes: function (Constructor, childContextTypes) {
- if (process.env.NODE_ENV !== 'production') {
- validateTypeDef(Constructor, childContextTypes, 'childContext');
- }
- Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes);
- },
- contextTypes: function (Constructor, contextTypes) {
- if (process.env.NODE_ENV !== 'production') {
- validateTypeDef(Constructor, contextTypes, 'context');
- }
- Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes);
- },
- /**
- * Special case getDefaultProps which should move into statics but requires
- * automatic merging.
- */
- getDefaultProps: function (Constructor, getDefaultProps) {
- if (Constructor.getDefaultProps) {
- Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
- } else {
- Constructor.getDefaultProps = getDefaultProps;
- }
- },
- propTypes: function (Constructor, propTypes) {
- if (process.env.NODE_ENV !== 'production') {
- validateTypeDef(Constructor, propTypes, 'prop');
- }
- Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
- },
- statics: function (Constructor, statics) {
- mixStaticSpecIntoComponent(Constructor, statics);
- },
- autobind: function () {} };
-
- function validateTypeDef(Constructor, typeDef, location) {
- for (var propName in typeDef) {
- if (typeDef.hasOwnProperty(propName)) {
- // use a warning instead of an _invariant so components
- // don't show up in prod but only in __DEV__
- process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0;
- }
- }
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
}
- function validateMethodOverride(isAlreadyDefined, name) {
- var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
+ return function(str, direction) {
+ var outerType = direction == "ltr" ? "L" : "R";
+
+ if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
+ var len = str.length, types = [];
+ for (var i = 0; i < len; ++i)
+ { types.push(charType(str.charCodeAt(i))); }
- // Disallow overriding of base class methods unless explicitly allowed.
- if (ReactClassMixin.hasOwnProperty(name)) {
- _invariant(specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name);
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
+ var type = types[i$1];
+ if (type == "m") { types[i$1] = prev; }
+ else { prev = type; }
}
- // Disallow defining methods more than once unless explicitly allowed.
- if (isAlreadyDefined) {
- _invariant(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name);
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
+ var type$1 = types[i$2];
+ if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
+ else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
}
- }
- /**
- * Mixin helper which handles policy validation and reserved
- * specification keys when building React classes.
- */
- function mixSpecIntoComponent(Constructor, spec) {
- if (!spec) {
- if (process.env.NODE_ENV !== 'production') {
- var typeofSpec = typeof spec;
- var isMixinValid = typeofSpec === 'object' && spec !== null;
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
+ var type$2 = types[i$3];
+ if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
+ else if (type$2 == "," && prev$1 == types[i$3+1] &&
+ (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
+ prev$1 = type$2;
+ }
- process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i$4 = 0; i$4 < len; ++i$4) {
+ var type$3 = types[i$4];
+ if (type$3 == ",") { types[i$4] = "N"; }
+ else if (type$3 == "%") {
+ var end = (void 0);
+ for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i$4; j < end; ++j) { types[j] = replace; }
+ i$4 = end - 1;
}
-
- return;
}
- _invariant(typeof spec !== 'function', 'ReactClass: You\'re attempting to ' + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.');
- _invariant(!isValidElement(spec), 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.');
-
- var proto = Constructor.prototype;
- var autoBindPairs = proto.__reactAutoBindPairs;
-
- // By handling mixins before any other properties, we ensure the same
- // chaining order is applied to methods with DEFINE_MANY policy, whether
- // mixins are listed before or after these methods in the spec.
- if (spec.hasOwnProperty(MIXINS_KEY)) {
- RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
+ var type$4 = types[i$5];
+ if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
+ else if (isStrong.test(type$4)) { cur$1 = type$4; }
}
- for (var name in spec) {
- if (!spec.hasOwnProperty(name)) {
- continue;
- }
-
- if (name === MIXINS_KEY) {
- // We have already handled mixins in a special case above.
- continue;
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i$6 = 0; i$6 < len; ++i$6) {
+ if (isNeutral.test(types[i$6])) {
+ var end$1 = (void 0);
+ for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
+ var before = (i$6 ? types[i$6-1] : outerType) == "L";
+ var after = (end$1 < len ? types[end$1] : outerType) == "L";
+ var replace$1 = before == after ? (before ? "L" : "R") : outerType;
+ for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
+ i$6 = end$1 - 1;
}
+ }
- var property = spec[name];
- var isAlreadyDefined = proto.hasOwnProperty(name);
- validateMethodOverride(isAlreadyDefined, name);
-
- if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
- RESERVED_SPEC_KEYS[name](Constructor, property);
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i$7 = 0; i$7 < len;) {
+ if (countsAsLeft.test(types[i$7])) {
+ var start = i$7;
+ for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
+ order.push(new BidiSpan(0, start, i$7));
} else {
- // Setup methods on prototype:
- // The following member methods should not be automatically bound:
- // 1. Expected ReactClass methods (in the "interface").
- // 2. Overridden methods (that were mixed in).
- var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
- var isFunction = typeof property === 'function';
- var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
-
- if (shouldAutoBind) {
- autoBindPairs.push(name, property);
- proto[name] = property;
- } else {
- if (isAlreadyDefined) {
- var specPolicy = ReactClassInterface[name];
-
- // These cases should already be caught by validateMethodOverride.
- _invariant(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name);
-
- // For methods which are defined more than once, call the existing
- // methods before calling the new property, merging if appropriate.
- if (specPolicy === 'DEFINE_MANY_MERGED') {
- proto[name] = createMergedResultFunction(proto[name], property);
- } else if (specPolicy === 'DEFINE_MANY') {
- proto[name] = createChainedFunction(proto[name], property);
- }
- } else {
- proto[name] = property;
- if (process.env.NODE_ENV !== 'production') {
- // Add verbose displayName to the function, which helps when looking
- // at profiling tools.
- if (typeof property === 'function' && spec.displayName) {
- proto[name].displayName = spec.displayName + '_' + name;
- }
- }
- }
+ var pos = i$7, at = order.length;
+ for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
+ for (var j$2 = pos; j$2 < i$7;) {
+ if (countsAsNum.test(types[j$2])) {
+ if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
+ var nstart = j$2;
+ for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j$2));
+ pos = j$2;
+ } else { ++j$2; }
}
+ if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
}
}
- }
-
- function mixStaticSpecIntoComponent(Constructor, statics) {
- if (!statics) {
- return;
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift(new BidiSpan(0, 0, m[0].length));
}
- for (var name in statics) {
- var property = statics[name];
- if (!statics.hasOwnProperty(name)) {
- continue;
- }
-
- var isReserved = name in RESERVED_SPEC_KEYS;
- _invariant(!isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name);
-
- var isInherited = name in Constructor;
- _invariant(!isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name);
- Constructor[name] = property;
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push(new BidiSpan(0, len - m[0].length, len));
}
- }
-
- /**
- * Merge two objects, but throw if both contain the same key.
- *
- * @param {object} one The first object, which is mutated.
- * @param {object} two The second object
- * @return {object} one after it has been mutated to contain everything in two.
- */
- function mergeIntoWithNoDuplicateKeys(one, two) {
- _invariant(one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.');
- for (var key in two) {
- if (two.hasOwnProperty(key)) {
- _invariant(one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key);
- one[key] = two[key];
- }
- }
- return one;
+ return direction == "rtl" ? order.reverse() : order
}
+ })();
- /**
- * Creates a function that invokes two functions and merges their return values.
- *
- * @param {function} one Function to invoke first.
- * @param {function} two Function to invoke second.
- * @return {function} Function that invokes the two argument functions.
- * @private
- */
- function createMergedResultFunction(one, two) {
- return function mergedResult() {
- var a = one.apply(this, arguments);
- var b = two.apply(this, arguments);
- if (a == null) {
- return b;
- } else if (b == null) {
- return a;
- }
- var c = {};
- mergeIntoWithNoDuplicateKeys(c, a);
- mergeIntoWithNoDuplicateKeys(c, b);
- return c;
- };
- }
+ // Get the bidi ordering for the given line (and cache it). Returns
+ // false for lines that are fully left-to-right, and an array of
+ // BidiSpan objects otherwise.
+ function getOrder(line, direction) {
+ var order = line.order;
+ if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
+ return order
+ }
- /**
- * Creates a function that invokes two functions and ignores their return vales.
- *
- * @param {function} one Function to invoke first.
- * @param {function} two Function to invoke second.
- * @return {function} Function that invokes the two argument functions.
- * @private
- */
- function createChainedFunction(one, two) {
- return function chainedFunction() {
- one.apply(this, arguments);
- two.apply(this, arguments);
- };
- }
+ // EVENT HANDLING
- /**
- * Binds a method to the component.
- *
- * @param {object} component Component whose method is going to be bound.
- * @param {function} method Method to be bound.
- * @return {function} The bound method.
- */
- function bindAutoBindMethod(component, method) {
- var boundMethod = method.bind(component);
- if (process.env.NODE_ENV !== 'production') {
- boundMethod.__reactBoundContext = component;
- boundMethod.__reactBoundMethod = method;
- boundMethod.__reactBoundArguments = null;
- var componentName = component.constructor.displayName;
- var _bind = boundMethod.bind;
- boundMethod.bind = function (newThis) {
- for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
+ // Lightweight event framework. on/off also work on DOM nodes,
+ // registering native DOM handlers.
- // User is trying to bind() an autobound method; we effectively will
- // ignore the value of "this" that the user is trying to use, so
- // let's warn.
- if (newThis !== component && newThis !== null) {
- process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0;
- } else if (!args.length) {
- process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0;
- return boundMethod;
- }
- var reboundMethod = _bind.apply(boundMethod, arguments);
- reboundMethod.__reactBoundContext = component;
- reboundMethod.__reactBoundMethod = method;
- reboundMethod.__reactBoundArguments = args;
- return reboundMethod;
- };
- }
- return boundMethod;
- }
+ var noHandlers = [];
- /**
- * Binds all auto-bound methods in a component.
- *
- * @param {object} component Component whose method is going to be bound.
- */
- function bindAutoBindMethods(component) {
- var pairs = component.__reactAutoBindPairs;
- for (var i = 0; i < pairs.length; i += 2) {
- var autoBindKey = pairs[i];
- var method = pairs[i + 1];
- component[autoBindKey] = bindAutoBindMethod(component, method);
- }
+ var on = function(emitter, type, f) {
+ if (emitter.addEventListener) {
+ emitter.addEventListener(type, f, false);
+ } else if (emitter.attachEvent) {
+ emitter.attachEvent("on" + type, f);
+ } else {
+ var map$$1 = emitter._handlers || (emitter._handlers = {});
+ map$$1[type] = (map$$1[type] || noHandlers).concat(f);
}
+ };
- var IsMountedMixin = {
- componentDidMount: function () {
- this.__isMounted = true;
- },
- componentWillUnmount: function () {
- this.__isMounted = false;
- }
- };
-
- /**
- * Add more to the ReactClass base class. These are all legacy features and
- * therefore not already part of the modern ReactComponent.
- */
- var ReactClassMixin = {
-
- /**
- * TODO: This will be deprecated because state should always keep a consistent
- * type signature and the only use case for this, is to avoid that.
- */
- replaceState: function (newState, callback) {
- this.updater.enqueueReplaceState(this, newState, callback);
- },
+ function getHandlers(emitter, type) {
+ return emitter._handlers && emitter._handlers[type] || noHandlers
+ }
- /**
- * Checks whether or not this composite component is mounted.
- * @return {boolean} True if mounted, false otherwise.
- * @protected
- * @final
- */
- isMounted: function () {
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', this.constructor && this.constructor.displayName || this.name || 'Component') : void 0;
- this.__didWarnIsMounted = true;
- }
- return !!this.__isMounted;
+ function off(emitter, type, f) {
+ if (emitter.removeEventListener) {
+ emitter.removeEventListener(type, f, false);
+ } else if (emitter.detachEvent) {
+ emitter.detachEvent("on" + type, f);
+ } else {
+ var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
+ if (arr) {
+ var index = indexOf(arr, f);
+ if (index > -1)
+ { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
}
- };
-
- var ReactClassComponent = function () {};
- _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
+ }
+ }
- /**
- * Creates a composite component class given a class specification.
- * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
- *
- * @param {object} spec Class specification (which must define `render`).
- * @return {function} Component constructor function.
- * @public
- */
- function createClass(spec) {
- // To keep our warnings more understandable, we'll use a little hack here to
- // ensure that Constructor.name !== 'Constructor'. This makes sure we don't
- // unnecessarily identify a class without displayName as 'Constructor'.
- var Constructor = identity(function (props, context, updater) {
- // This constructor gets overridden by mocks. The argument is used
- // by mocks to assert on what gets mounted.
-
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
- }
+ function signal(emitter, type /*, values...*/) {
+ var handlers = getHandlers(emitter, type);
+ if (!handlers.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
+ }
- // Wire up auto-binding
- if (this.__reactAutoBindPairs.length) {
- bindAutoBindMethods(this);
- }
+ // The DOM events that CodeMirror handles can be overridden by
+ // registering a (non-DOM) handler on the editor for the event name,
+ // and preventDefault-ing the event in that handler.
+ function signalDOMEvent(cm, e, override) {
+ if (typeof e == "string")
+ { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore
+ }
- this.props = props;
- this.context = context;
- this.refs = emptyObject;
- this.updater = updater || ReactNoopUpdateQueue;
+ function signalCursorActivity(cm) {
+ var arr = cm._handlers && cm._handlers.cursorActivity;
+ if (!arr) { return }
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
+ for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+ { set.push(arr[i]); } }
+ }
- this.state = null;
+ function hasHandler(emitter, type) {
+ return getHandlers(emitter, type).length > 0
+ }
- // ReactClasses doesn't have constructors. Instead, they use the
- // getInitialState and componentWillMount methods for initialization.
+ // Add on and off methods to a constructor's prototype, to make
+ // registering events on such objects more convenient.
+ function eventMixin(ctor) {
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
+ }
- var initialState = this.getInitialState ? this.getInitialState() : null;
- if (process.env.NODE_ENV !== 'production') {
- // We allow auto-mocks to proceed as if they're returning null.
- if (initialState === undefined && this.getInitialState._isMockFunction) {
- // This is probably bad practice. Consider warning here and
- // deprecating this convenience.
- initialState = null;
- }
- }
- _invariant(typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent');
-
- this.state = initialState;
- });
- Constructor.prototype = new ReactClassComponent();
- Constructor.prototype.constructor = Constructor;
- Constructor.prototype.__reactAutoBindPairs = [];
+ // Due to the fact that we still support jurassic IE versions, some
+ // compatibility wrappers are needed.
- injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
+ function e_preventDefault(e) {
+ if (e.preventDefault) { e.preventDefault(); }
+ else { e.returnValue = false; }
+ }
+ function e_stopPropagation(e) {
+ if (e.stopPropagation) { e.stopPropagation(); }
+ else { e.cancelBubble = true; }
+ }
+ function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+ }
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
- mixSpecIntoComponent(Constructor, IsMountedMixin);
- mixSpecIntoComponent(Constructor, spec);
+ function e_target(e) {return e.target || e.srcElement}
+ function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) { b = 1; }
+ else if (e.button & 2) { b = 3; }
+ else if (e.button & 4) { b = 2; }
+ }
+ if (mac && e.ctrlKey && b == 1) { b = 3; }
+ return b
+ }
- // Initialize the defaultProps property after all mixins have been merged.
- if (Constructor.getDefaultProps) {
- Constructor.defaultProps = Constructor.getDefaultProps();
- }
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie && ie_version < 9) { return false }
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div
+ }();
- if (process.env.NODE_ENV !== 'production') {
- // This is a tag to indicate that the use of these method names is ok,
- // since it's used with createClass. If it's not, then it's likely a
- // mistake so we'll warn you to use the static property, property
- // initializer or constructor respectively.
- if (Constructor.getDefaultProps) {
- Constructor.getDefaultProps.isReactClassApproved = {};
- }
- if (Constructor.prototype.getInitialState) {
- Constructor.prototype.getInitialState.isReactClassApproved = {};
- }
- }
+ var zwspSupported;
+ function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
+ }
+ var node = zwspSupported ? elt("span", "\u200b") :
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ node.setAttribute("cm-text", "");
+ return node
+ }
- _invariant(Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.');
+ // Feature-detect IE's crummy client rect reporting for bidi text
+ var badBidiRects;
+ function hasBadBidiRects(measure) {
+ if (badBidiRects != null) { return badBidiRects }
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ removeChildren(measure);
+ if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
+ return badBidiRects = (r1.right - r0.right < 3)
+ }
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0;
- process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0;
+ // See if "".split is the broken IE version, if so, provide an
+ // alternative way to split lines.
+ var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) { nl = string.length; }
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
}
+ }
+ return result
+ } : function (string) { return string.split(/\r\n?|\n/); };
- // Reduce time spent doing lookups by setting these on the prototype.
- for (var methodName in ReactClassInterface) {
- if (!Constructor.prototype[methodName]) {
- Constructor.prototype[methodName] = null;
- }
- }
+ var hasSelection = window.getSelection ? function (te) {
+ try { return te.selectionStart != te.selectionEnd }
+ catch(e) { return false }
+ } : function (te) {
+ var range$$1;
+ try {range$$1 = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range$$1 || range$$1.parentElement() != te) { return false }
+ return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
+ };
- return Constructor;
- }
+ var hasCopyEvent = (function () {
+ var e = elt("div");
+ if ("oncopy" in e) { return true }
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == "function"
+ })();
- return createClass;
+ var badZoomedRects = null;
+ function hasBadZoomedRects(measure) {
+ if (badZoomedRects != null) { return badZoomedRects }
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
+ var normal = node.getBoundingClientRect();
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
}
- module.exports = factory;
-
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 317 */
-/***/ (function(module, exports) {
-
- /*
- object-assign
- (c) Sindre Sorhus
- @license MIT
- */
+ // Known modes, by name and by MIME
+ var modes = {};
+ var mimeModes = {};
- 'use strict';
- /* eslint-disable no-unused-vars */
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ function defineMode(name, mode) {
+ if (arguments.length > 2)
+ { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
+ modes[name] = mode;
+ }
- function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
+ function defineMIME(mime, spec) {
+ mimeModes[mime] = spec;
+ }
- return Object(val);
+ // Given a MIME type, a {name, ...options} config object, or a name
+ // string, return a mode config object.
+ function resolveMode(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ var found = mimeModes[spec.name];
+ if (typeof found == "string") { found = {name: found}; }
+ spec = createObj(found, spec);
+ spec.name = found.name;
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+ return resolveMode("application/xml")
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+ return resolveMode("application/json")
+ }
+ if (typeof spec == "string") { return {name: spec} }
+ else { return spec || {name: "null"} }
}
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
+ // Given a mode spec (anything that resolveMode accepts), find and
+ // initialize an actual mode object.
+ function getMode(options, spec) {
+ spec = resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) { return getMode(options, "text/plain") }
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) { continue }
+ if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ if (spec.helperType) { modeObj.helperType = spec.helperType; }
+ if (spec.modeProps) { for (var prop$1 in spec.modeProps)
+ { modeObj[prop$1] = spec.modeProps[prop$1]; } }
- // Detect buggy property enumeration order in older V8 versions.
+ return modeObj
+ }
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- }
+ // This can be used to attach properties to mode objects from
+ // outside the actual mode definition.
+ var modeExtensions = {};
+ function extendMode(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+ }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- }
+ function copyState(mode, state) {
+ if (state === true) { return state }
+ if (mode.copyState) { return mode.copyState(state) }
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) { val = val.concat([]); }
+ nstate[n] = val;
+ }
+ return nstate
+ }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !==
- 'abcdefghijklmnopqrst') {
- return false;
- }
+ // Given a mode and a state (for that mode), find the inner mode and
+ // state at the position that the state refers to.
+ function innerMode(mode, state) {
+ var info;
+ while (mode.innerMode) {
+ info = mode.innerMode(state);
+ if (!info || info.mode == mode) { break }
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state}
+ }
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
+ function startState(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true
}
- module.exports = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
+ // STRING STREAM
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
+ var StringStream = function(string, tabSize, lineOracle) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ this.lastColumnPos = this.lastColumnValue = 0;
+ this.lineStart = 0;
+ this.lineOracle = lineOracle;
+ };
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
+ StringStream.prototype.eol = function () {return this.pos >= this.string.length};
+ StringStream.prototype.sol = function () {return this.pos == this.lineStart};
+ StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
+ StringStream.prototype.next = function () {
+ if (this.pos < this.string.length)
+ { return this.string.charAt(this.pos++) }
+ };
+ StringStream.prototype.eat = function (match) {
+ var ch = this.string.charAt(this.pos);
+ var ok;
+ if (typeof match == "string") { ok = ch == match; }
+ else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
+ if (ok) {++this.pos; return ch}
+ };
+ StringStream.prototype.eatWhile = function (match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start
+ };
+ StringStream.prototype.eatSpace = function () {
+ var this$1 = this;
- return to;
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
+ return this.pos > start
+ };
+ StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
+ StringStream.prototype.skipTo = function (ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true}
+ };
+ StringStream.prototype.backUp = function (n) {this.pos -= n;};
+ StringStream.prototype.column = function () {
+ if (this.lastColumnPos < this.start) {
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+ this.lastColumnPos = this.start;
+ }
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+ };
+ StringStream.prototype.indentation = function () {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+ };
+ StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
+ if (typeof pattern == "string") {
+ var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
+ var substr = this.string.substr(this.pos, pattern.length);
+ if (cased(substr) == cased(pattern)) {
+ if (consume !== false) { this.pos += pattern.length; }
+ return true
+ }
+ } else {
+ var match = this.string.slice(this.pos).match(pattern);
+ if (match && match.index > 0) { return null }
+ if (match && consume !== false) { this.pos += match[0].length; }
+ return match
+ }
+ };
+ StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
+ StringStream.prototype.hideFirstChars = function (n, inner) {
+ this.lineStart += n;
+ try { return inner() }
+ finally { this.lineStart -= n; }
+ };
+ StringStream.prototype.lookAhead = function (n) {
+ var oracle = this.lineOracle;
+ return oracle && oracle.lookAhead(n)
};
-
-
-/***/ }),
-/* 318 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
- 'use strict';
+ var SavedContext = function(state, lookAhead) {
+ this.state = state;
+ this.lookAhead = lookAhead;
+ };
- var emptyObject = {};
+ var Context = function(doc, state, line, lookAhead) {
+ this.state = state;
+ this.doc = doc;
+ this.line = line;
+ this.maxLookAhead = lookAhead || 0;
+ };
- if (process.env.NODE_ENV !== 'production') {
- Object.freeze(emptyObject);
- }
+ Context.prototype.lookAhead = function (n) {
+ var line = this.doc.getLine(this.line + n);
+ if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
+ return line
+ };
- module.exports = emptyObject;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 319 */
-/***/ (function(module, exports, __webpack_require__) {
-
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: http://codemirror.net/LICENSE
+ Context.prototype.nextLine = function () {
+ this.line++;
+ if (this.maxLookAhead > 0) { this.maxLookAhead--; }
+ };
- // This is CodeMirror (http://codemirror.net), a code editor
- // implemented in JavaScript on top of the browser's DOM.
- //
- // You can find some technical background for some of the code below
- // at http://marijnhaverbeke.nl/blog/#cm-internals .
+ Context.fromSaved = function (doc, saved, line) {
+ if (saved instanceof SavedContext)
+ { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
+ else
+ { return new Context(doc, copyState(doc.mode, saved), line) }
+ };
- (function (global, factory) {
- true ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global.CodeMirror = factory());
- }(this, (function () { 'use strict';
+ Context.prototype.save = function (copy) {
+ var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
+ return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
+ };
- // Kludges for bugs and behavior differences that can't be feature
- // detected are enabled based on userAgent etc sniffing.
- var userAgent = navigator.userAgent;
- var platform = navigator.platform;
- var gecko = /gecko\/\d/i.test(userAgent);
- var ie_upto10 = /MSIE \d/.test(userAgent);
- var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
- var edge = /Edge\/(\d+)/.exec(userAgent);
- var ie = ie_upto10 || ie_11up || edge;
- var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
- var webkit = !edge && /WebKit\//.test(userAgent);
- var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
- var chrome = !edge && /Chrome\//.test(userAgent);
- var presto = /Opera\//.test(userAgent);
- var safari = /Apple Computer/.test(navigator.vendor);
- var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
- var phantom = /PhantomJS/.test(userAgent);
+ // Compute a style array (an array starting with a mode generation
+ // -- for invalidation -- followed by pairs of end positions and
+ // style strings), which is used to highlight the tokens on the
+ // line.
+ function highlightLine(cm, line, context, forceToEnd) {
+ // A styles array always starts with a number identifying the
+ // mode/overlays that it is based on (for easy invalidation).
+ var st = [cm.state.modeGen], lineClasses = {};
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
+ lineClasses, forceToEnd);
+ var state = context.state;
- var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
- var android = /Android/.test(userAgent);
- // This is woefully incomplete. Suggestions for alternative methods welcome.
- var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
- var mac = ios || /Mac/.test(platform);
- var chromeOS = /\bCrOS\b/.test(userAgent);
- var windows = /win/i.test(platform);
+ // Run overlays, adjust style array.
+ var loop = function ( o ) {
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ context.state = true;
+ runMode(cm, line.text, overlay.mode, context, function (end, style) {
+ var start = i;
+ // Ensure there's a token end at the current position, and that i points at it
+ while (at < end) {
+ var i_end = st[i];
+ if (i_end > end)
+ { st.splice(i, 1, end, st[i+1], i_end); }
+ i += 2;
+ at = Math.min(end, i_end);
+ }
+ if (!style) { return }
+ if (overlay.opaque) {
+ st.splice(start, i - start, end, "overlay " + style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
+ }
+ }
+ }, lineClasses);
+ };
- var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
- if (presto_version) { presto_version = Number(presto_version[1]); }
- if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
- // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
- var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
- var captureRightClick = gecko || (ie && ie_version >= 9);
+ for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
+ context.state = state;
- function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+ }
- var rmClass = function(node, cls) {
- var current = node.className;
- var match = classTest(cls).exec(current);
- if (match) {
- var after = current.slice(match.index + match[0].length);
- node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
+ function getLineStyles(cm, line, updateFrontier) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
+ var context = getContextBefore(cm, lineNo(line));
+ var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
+ var result = highlightLine(cm, line, context);
+ if (resetState) { context.state = resetState; }
+ line.stateAfter = context.save(!resetState);
+ line.styles = result.styles;
+ if (result.classes) { line.styleClasses = result.classes; }
+ else if (line.styleClasses) { line.styleClasses = null; }
+ if (updateFrontier === cm.doc.highlightFrontier)
+ { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
}
- };
-
- function removeChildren(e) {
- for (var count = e.childNodes.length; count > 0; --count)
- { e.removeChild(e.firstChild); }
- return e
+ return line.styles
}
- function removeChildrenAndAdd(parent, e) {
- return removeChildren(parent).appendChild(e)
+ function getContextBefore(cm, n, precise) {
+ var doc = cm.doc, display = cm.display;
+ if (!doc.mode.startState) { return new Context(doc, true, n) }
+ var start = findStartLine(cm, n, precise);
+ var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
+ var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
+
+ doc.iter(start, n, function (line) {
+ processLine(cm, line.text, context);
+ var pos = context.line;
+ line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
+ context.nextLine();
+ });
+ if (precise) { doc.modeFrontier = context.line; }
+ return context
}
- function elt(tag, content, className, style) {
- var e = document.createElement(tag);
- if (className) { e.className = className; }
- if (style) { e.style.cssText = style; }
- if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
- else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
- return e
+ // Lightweight form of highlight -- proceed over this line and
+ // update state, but don't save a style array. Used for lines that
+ // aren't currently visible.
+ function processLine(cm, text, context, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize, context);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "") { callBlankLine(mode, context.state); }
+ while (!stream.eol()) {
+ readToken(mode, stream, context.state);
+ stream.start = stream.pos;
+ }
}
- // wrapper for elt, which removes the elt from the accessibility tree
- function eltP(tag, content, className, style) {
- var e = elt(tag, content, className, style);
- e.setAttribute("role", "presentation");
- return e
+
+ function callBlankLine(mode, state) {
+ if (mode.blankLine) { return mode.blankLine(state) }
+ if (!mode.innerMode) { return }
+ var inner = innerMode(mode, state);
+ if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
}
- var range;
- if (document.createRange) { range = function(node, start, end, endNode) {
- var r = document.createRange();
- r.setEnd(endNode || node, end);
- r.setStart(node, start);
- return r
- }; }
- else { range = function(node, start, end) {
- var r = document.body.createTextRange();
- try { r.moveToElementText(node.parentNode); }
- catch(e) { return r }
- r.collapse(true);
- r.moveEnd("character", end);
- r.moveStart("character", start);
- return r
- }; }
-
- function contains(parent, child) {
- if (child.nodeType == 3) // Android browser always returns false when child is a textnode
- { child = child.parentNode; }
- if (parent.contains)
- { return parent.contains(child) }
- do {
- if (child.nodeType == 11) { child = child.host; }
- if (child == parent) { return true }
- } while (child = child.parentNode)
+ function readToken(mode, stream, state, inner) {
+ for (var i = 0; i < 10; i++) {
+ if (inner) { inner[0] = innerMode(mode, state).mode; }
+ var style = mode.token(stream, state);
+ if (stream.pos > stream.start) { return style }
+ }
+ throw new Error("Mode " + mode.name + " failed to advance stream.")
}
- function activeElt() {
- // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
- // IE < 10 will throw when accessed while the page is loading or in an iframe.
- // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
- var activeElement;
- try {
- activeElement = document.activeElement;
- } catch(e) {
- activeElement = document.body || null;
+ var Token = function(stream, type, state) {
+ this.start = stream.start; this.end = stream.pos;
+ this.string = stream.current();
+ this.type = type || null;
+ this.state = state;
+ };
+
+ // Utility for getTokenAt and getLineTokens
+ function takeToken(cm, pos, precise, asArray) {
+ var doc = cm.doc, mode = doc.mode, style;
+ pos = clipPos(doc, pos);
+ var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
+ var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
+ if (asArray) { tokens = []; }
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+ stream.start = stream.pos;
+ style = readToken(mode, stream, context.state);
+ if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
}
- while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
- { activeElement = activeElement.shadowRoot.activeElement; }
- return activeElement
+ return asArray ? tokens : new Token(stream, style, context.state)
}
- function addClass(node, cls) {
- var current = node.className;
- if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
- }
- function joinClasses(a, b) {
- var as = a.split(" ");
- for (var i = 0; i < as.length; i++)
- { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
- return b
+ function extractLineClasses(type, output) {
+ if (type) { for (;;) {
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) { break }
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (output[prop] == null)
+ { output[prop] = lineClass[2]; }
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
+ { output[prop] += " " + lineClass[2]; }
+ } }
+ return type
}
- var selectInput = function(node) { node.select(); };
- if (ios) // Mobile Safari apparently has a bug where select() is broken.
- { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
- else if (ie) // Suppress mysterious IE10 errors
- { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
-
- function bind(f) {
- var args = Array.prototype.slice.call(arguments, 1);
- return function(){return f.apply(null, args)}
+ // Run the given mode's parser over a line, calling f for each token.
+ function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
+ var flattenSpans = mode.flattenSpans;
+ if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
+ var curStart = 0, curStyle = null;
+ var stream = new StringStream(text, cm.options.tabSize, context), style;
+ var inner = cm.options.addModeClass && [null];
+ if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) { processLine(cm, text, context, stream.pos); }
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
+ }
+ if (inner) {
+ var mName = inner[0].name;
+ if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
+ }
+ if (!flattenSpans || curStyle != style) {
+ while (curStart < stream.start) {
+ curStart = Math.min(stream.start, curStart + 5000);
+ f(curStart, curStyle);
+ }
+ curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444
+ // characters, and returns inaccurate measurements in nodes
+ // starting around 5000 chars.
+ var pos = Math.min(stream.pos, curStart + 5000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
}
- function copyObj(obj, target, overwrite) {
- if (!target) { target = {}; }
- for (var prop in obj)
- { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
- { target[prop] = obj[prop]; } }
- return target
+ // Finds the line to start with when starting a parse. Tries to
+ // find a line with a stateAfter, so that it can start with a
+ // valid state. If that fails, it returns the line with the
+ // smallest indentation, which tends to need the least context to
+ // parse correctly.
+ function findStartLine(cm, n, precise) {
+ var minindent, minline, doc = cm.doc;
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
+ for (var search = n; search > lim; --search) {
+ if (search <= doc.first) { return doc.first }
+ var line = getLine(doc, search - 1), after = line.stateAfter;
+ if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
+ { return search }
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline
}
- // Counts the column offset in a string, taking tabs into account.
- // Used mostly to find indentation.
- function countColumn(string, end, tabSize, startIndex, startValue) {
- if (end == null) {
- end = string.search(/[^\s\u00a0]/);
- if (end == -1) { end = string.length; }
- }
- for (var i = startIndex || 0, n = startValue || 0;;) {
- var nextTab = string.indexOf("\t", i);
- if (nextTab < 0 || nextTab >= end)
- { return n + (end - i) }
- n += nextTab - i;
- n += tabSize - (n % tabSize);
- i = nextTab + 1;
+ function retreatFrontier(doc, n) {
+ doc.modeFrontier = Math.min(doc.modeFrontier, n);
+ if (doc.highlightFrontier < n - 10) { return }
+ var start = doc.first;
+ for (var line = n - 1; line > start; line--) {
+ var saved = getLine(doc, line).stateAfter;
+ // change is on 3
+ // state on line 1 looked ahead 2 -- so saw 3
+ // test 1 + 2 < 3 should cover this
+ if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
+ start = line + 1;
+ break
+ }
}
+ doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
}
- var Delayed = function() {this.id = null;};
- Delayed.prototype.set = function (ms, f) {
- clearTimeout(this.id);
- this.id = setTimeout(f, ms);
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ var Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
};
- function indexOf(array, elt) {
- for (var i = 0; i < array.length; ++i)
- { if (array[i] == elt) { return i } }
- return -1
+ Line.prototype.lineNo = function () { return lineNo(this) };
+ eventMixin(Line);
+
+ // Change the content (text, markers) of a line. Automatically
+ // invalidates cached information and tries to re-estimate the
+ // line's height.
+ function updateLine(line, text, markedSpans, estimateHeight) {
+ line.text = text;
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ if (line.order != null) { line.order = null; }
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
}
- // Number of pixels added to scroller and sizer to hide scrollbar
- var scrollerGap = 30;
+ // Detach a line from the document tree and its markers.
+ function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+ }
- // Returned or thrown by various protocols to signal 'I'm not
- // handling this'.
- var Pass = {toString: function(){return "CodeMirror.Pass"}};
+ // Convert a style as returned by a mode (either null, or a string
+ // containing one or more styles) to a CSS style. This is cached,
+ // and also looks for line-wide styles.
+ var styleToClassCache = {};
+ var styleToClassCacheWithMode = {};
+ function interpretTokenStyle(style, options) {
+ if (!style || /^\s*$/.test(style)) { return null }
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
+ return cache[style] ||
+ (cache[style] = style.replace(/\S+/g, "cm-$&"))
+ }
- // Reused option objects for setSelection & friends
- var sel_dontScroll = {scroll: false};
- var sel_mouse = {origin: "*mouse"};
- var sel_move = {origin: "+move"};
+ // Render the DOM representation of the text of a line. Also builds
+ // up a 'line map', which points at the DOM nodes that represent
+ // specific stretches of text, and is used by the measuring code.
+ // The returned object contains the DOM node, this map, and
+ // information about line-wide styles that were set by the mode.
+ function buildLineContent(cm, lineView) {
+ // The padding-right forces the element to have a 'border', which
+ // is needed on Webkit to be able to get line-level bounding
+ // rectangles for it (in measureChar).
+ var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
+ col: 0, pos: 0, cm: cm,
+ trailingSpace: false,
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
+ lineView.measure = {};
- // The inverse of countColumn -- find the offset that corresponds to
- // a particular column.
- function findColumn(string, goal, tabSize) {
- for (var pos = 0, col = 0;;) {
- var nextTab = string.indexOf("\t", pos);
- if (nextTab == -1) { nextTab = string.length; }
- var skipped = nextTab - pos;
- if (nextTab == string.length || col + skipped >= goal)
- { return pos + Math.min(skipped, goal - col) }
- col += nextTab - pos;
- col += tabSize - (col % tabSize);
- pos = nextTab + 1;
- if (col >= goal) { return pos }
+ // Iterate over the logical lines that make up this visual line.
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+ var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
+ { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
+ builder.map = [];
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
+ if (line.styleClasses) {
+ if (line.styleClasses.bgClass)
+ { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
+ if (line.styleClasses.textClass)
+ { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
+ }
+
+ // Ensure at least a single node is present, for measuring.
+ if (builder.map.length == 0)
+ { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
+
+ // Store the map and a cache object for the current logical line
+ if (i == 0) {
+ lineView.measure.map = builder.map;
+ lineView.measure.cache = {};
+ } else {
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
+ ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
+ }
}
- }
- var spaceStrs = [""];
- function spaceStr(n) {
- while (spaceStrs.length <= n)
- { spaceStrs.push(lst(spaceStrs) + " "); }
- return spaceStrs[n]
- }
+ // See issue #2901
+ if (webkit) {
+ var last = builder.content.lastChild;
+ if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
+ { builder.content.className = "cm-tab-wrap-hack"; }
+ }
- function lst(arr) { return arr[arr.length-1] }
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ if (builder.pre.className)
+ { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
- function map(array, f) {
- var out = [];
- for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
- return out
+ return builder
}
- function insertSorted(array, value, score) {
- var pos = 0, priority = score(value);
- while (pos < array.length && score(array[pos]) <= priority) { pos++; }
- array.splice(pos, 0, value);
+ function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ token.setAttribute("aria-label", token.title);
+ return token
}
- function nothing() {}
-
- function createObj(base, props) {
- var inst;
- if (Object.create) {
- inst = Object.create(base);
+ // Build up the DOM representation for a single token, and add it to
+ // the line map. Takes care to render special characters separately.
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
+ if (!text) { return }
+ var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
+ var special = builder.cm.state.specialChars, mustWrap = false;
+ var content;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ content = document.createTextNode(displayText);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie && ie_version < 9) { mustWrap = true; }
+ builder.pos += text.length;
} else {
- nothing.prototype = base;
- inst = new nothing();
+ content = document.createDocumentFragment();
+ var pos = 0;
+ while (true) {
+ special.lastIndex = pos;
+ var m = special.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
+ else { content.appendChild(txt); }
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
+ builder.col += skipped;
+ builder.pos += skipped;
+ }
+ if (!m) { break }
+ pos += skipped + 1;
+ var txt$1 = (void 0);
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ txt$1.setAttribute("role", "presentation");
+ txt$1.setAttribute("cm-text", "\t");
+ builder.col += tabWidth;
+ } else if (m[0] == "\r" || m[0] == "\n") {
+ txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
+ txt$1.setAttribute("cm-text", m[0]);
+ builder.col += 1;
+ } else {
+ txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
+ txt$1.setAttribute("cm-text", m[0]);
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
+ else { content.appendChild(txt$1); }
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt$1);
+ builder.pos++;
+ }
}
- if (props) { copyObj(props, inst); }
- return inst
+ builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
+ if (style || startStyle || endStyle || mustWrap || css) {
+ var fullStyle = style || "";
+ if (startStyle) { fullStyle += startStyle; }
+ if (endStyle) { fullStyle += endStyle; }
+ var token = elt("span", [content], fullStyle, css);
+ if (title) { token.title = title; }
+ return builder.content.appendChild(token)
+ }
+ builder.content.appendChild(content);
}
- var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
- function isWordCharBasic(ch) {
- return /\w/.test(ch) || ch > "\x80" &&
- (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
- }
- function isWordChar(ch, helper) {
- if (!helper) { return isWordCharBasic(ch) }
- if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
- return helper.test(ch)
+ function splitSpaces(text, trailingBefore) {
+ if (text.length > 1 && !/ /.test(text)) { return text }
+ var spaceBefore = trailingBefore, result = "";
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charAt(i);
+ if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+ { ch = "\u00a0"; }
+ result += ch;
+ spaceBefore = ch == " ";
+ }
+ return result
}
- function isEmpty(obj) {
- for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
- return true
+ // Work around nonsense dimensions being reported for stretches of
+ // right-to-left text.
+ function buildTokenBadBidi(inner, order) {
+ return function (builder, text, style, startStyle, endStyle, title, css) {
+ style = style ? style + " cm-force-border" : "cm-force-border";
+ var start = builder.pos, end = start + text.length;
+ for (;;) {
+ // Find the part that overlaps with the start of this text
+ var part = (void 0);
+ for (var i = 0; i < order.length; i++) {
+ part = order[i];
+ if (part.to > start && part.from <= start) { break }
+ }
+ if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
+ startStyle = null;
+ text = text.slice(part.to - start);
+ start = part.to;
+ }
+ }
}
- // Extending unicode characters. A series of a non-extending char +
- // any number of extending chars is treated as a single unit as far
- // as editing and measuring is concerned. This is not fully correct,
- // since some scripts/fonts/browsers also treat other configurations
- // of code points as a group.
- var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
- function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
-
- // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
- function skipExtendingChars(str, pos, dir) {
- while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
- return pos
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+ var widget = !ignoreWidget && marker.widgetNode;
+ if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+ if (!widget)
+ { widget = builder.content.appendChild(document.createElement("span")); }
+ widget.setAttribute("cm-marker", marker.id);
+ }
+ if (widget) {
+ builder.cm.display.input.setUneditable(widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ builder.trailingSpace = false;
}
- // Returns the value from the range [`from`; `to`] that satisfies
- // `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`.
- function findFirst(pred, from, to) {
+ // Outputs a number of spans to make up a line, taking highlighting
+ // and marked text into account.
+ function insertLineContent(line, builder, styles) {
+ var spans = line.markedSpans, allText = line.text, at = 0;
+ if (!spans) {
+ for (var i$1 = 1; i$1 < styles.length; i$1+=2)
+ { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
+ return
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
for (;;) {
- if (Math.abs(from - to) <= 1) { return pred(from) ? from : to }
- var mid = Math.floor((from + to) / 2);
- if (pred(mid)) { to = mid; }
- else { from = mid; }
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [], endStyles = (void 0);
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+ foundBookmarks.push(m);
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+ nextChange = sp.to;
+ spanEndStyle = "";
+ }
+ if (m.className) { spanStyle += " " + m.className; }
+ if (m.css) { css = (css ? css + ";" : "") + m.css; }
+ if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
+ if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
+ if (m.title && !title) { title = m.title; }
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ { collapsed = sp; }
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ }
+ if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
+ { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
+
+ if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
+ { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+ collapsed.marker, collapsed.from == null);
+ if (collapsed.to == null) { return }
+ if (collapsed.to == pos) { collapsed = false; }
+ }
+ }
+ if (pos >= len) { break }
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = allText.slice(at, at = styles[i++]);
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
+ }
}
}
- // The display handles the DOM integration, both for input reading
- // and content drawing. It holds references to DOM nodes and
- // display-related state.
-
- function Display(place, doc, input) {
- var d = this;
- this.input = input;
- // Covers bottom-right square when both scrollbars are present.
- d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
- d.scrollbarFiller.setAttribute("cm-not-content", "true");
- // Covers bottom of gutter when coverGutterNextToScrollbar is on
- // and h scrollbar is present.
- d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
- d.gutterFiller.setAttribute("cm-not-content", "true");
- // Will contain the actual code, positioned to cover the viewport.
- d.lineDiv = eltP("div", null, "CodeMirror-code");
- // Elements are added to these to represent selection and cursors.
- d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
- d.cursorDiv = elt("div", null, "CodeMirror-cursors");
- // A visibility: hidden element used to find the size of things.
- d.measure = elt("div", null, "CodeMirror-measure");
- // When lines outside of the viewport are measured, they are drawn in this.
- d.lineMeasure = elt("div", null, "CodeMirror-measure");
- // Wraps everything that needs to exist inside the vertically-padded coordinate system
- d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
- null, "position: relative; outline: none");
- var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
- // Moved around its parent to cover visible view.
- d.mover = elt("div", [lines], null, "position: relative");
- // Set to the height of the document, allowing scrolling.
- d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
- d.sizerWidth = null;
- // Behavior of elts with overflow: auto and padding is
- // inconsistent across browsers. This is used to ensure the
- // scrollable area is big enough.
- d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
- // Will contain the gutters, if any.
- d.gutters = elt("div", null, "CodeMirror-gutters");
- d.lineGutter = null;
- // Actual scrollable element.
- d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
- d.scroller.setAttribute("tabIndex", "-1");
- // The element in which the editor lives.
- d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
-
- // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
- if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
- if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
+ // These objects are used to represent the visible (currently drawn)
+ // part of the document. A LineView may correspond to multiple
+ // logical lines, if those are connected by collapsed ranges.
+ function LineView(doc, line, lineN) {
+ // The starting line
+ this.line = line;
+ // Continuing lines, if any
+ this.rest = visualLineContinued(line);
+ // Number of logical lines in this visual line
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
+ this.node = this.text = null;
+ this.hidden = lineIsHidden(doc, line);
+ }
- if (place) {
- if (place.appendChild) { place.appendChild(d.wrapper); }
- else { place(d.wrapper); }
+ // Create a range of LineView objects for the given lines.
+ function buildViewArray(cm, from, to) {
+ var array = [], nextPos;
+ for (var pos = from; pos < to; pos = nextPos) {
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
+ nextPos = pos + view.size;
+ array.push(view);
}
+ return array
+ }
- // Current rendered range (may be bigger than the view window).
- d.viewFrom = d.viewTo = doc.first;
- d.reportedViewFrom = d.reportedViewTo = doc.first;
- // Information about the rendered lines.
- d.view = [];
- d.renderedView = null;
- // Holds info about a single rendered line when it was rendered
- // for measurement, while not in view.
- d.externalMeasured = null;
- // Empty space (in pixels) above the view
- d.viewOffset = 0;
- d.lastWrapHeight = d.lastWrapWidth = 0;
- d.updateLineNumbers = null;
-
- d.nativeBarWidth = d.barHeight = d.barWidth = 0;
- d.scrollbarsClipped = false;
+ var operationGroup = null;
- // Used to only resize the line number gutter when necessary (when
- // the amount of lines crosses a boundary that makes its width change)
- d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
- // Set to true when a non-horizontal-scrolling line widget is
- // added. As an optimization, line widget aligning is skipped when
- // this is false.
- d.alignWidgets = false;
+ function pushOperation(op) {
+ if (operationGroup) {
+ operationGroup.ops.push(op);
+ } else {
+ op.ownsGroup = operationGroup = {
+ ops: [op],
+ delayedCallbacks: []
+ };
+ }
+ }
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+ function fireCallbacksForOps(group) {
+ // Calls delayed callbacks and cursorActivity handlers until no
+ // new ones appear
+ var callbacks = group.delayedCallbacks, i = 0;
+ do {
+ for (; i < callbacks.length; i++)
+ { callbacks[i].call(null); }
+ for (var j = 0; j < group.ops.length; j++) {
+ var op = group.ops[j];
+ if (op.cursorActivityHandlers)
+ { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
+ { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
+ }
+ } while (i < callbacks.length)
+ }
- // Tracks the maximum line length so that the horizontal scrollbar
- // can be kept static when scrolling.
- d.maxLine = null;
- d.maxLineLength = 0;
- d.maxLineChanged = false;
+ function finishOperation(op, endCb) {
+ var group = op.ownsGroup;
+ if (!group) { return }
- // Used for measuring wheel scrolling granularity
- d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
+ try { fireCallbacksForOps(group); }
+ finally {
+ operationGroup = null;
+ endCb(group);
+ }
+ }
- // True when shift is held down.
- d.shift = false;
+ var orphanDelayedCallbacks = null;
- // Used to track whether anything happened since the context menu
- // was opened.
- d.selForContextMenu = null;
+ // Often, we want to signal events at a point where we are in the
+ // middle of some work, but don't want the handler to start calling
+ // other methods on the editor, which might be in an inconsistent
+ // state or simply not expect any other events to happen.
+ // signalLater looks whether there are any handlers, and schedules
+ // them to be executed when the last operation ends, or, if no
+ // operation is active, when a timeout fires.
+ function signalLater(emitter, type /*, values...*/) {
+ var arr = getHandlers(emitter, type);
+ if (!arr.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2), list;
+ if (operationGroup) {
+ list = operationGroup.delayedCallbacks;
+ } else if (orphanDelayedCallbacks) {
+ list = orphanDelayedCallbacks;
+ } else {
+ list = orphanDelayedCallbacks = [];
+ setTimeout(fireOrphanDelayed, 0);
+ }
+ var loop = function ( i ) {
+ list.push(function () { return arr[i].apply(null, args); });
+ };
- d.activeTouch = null;
+ for (var i = 0; i < arr.length; ++i)
+ loop( i );
+ }
- input.init(d);
+ function fireOrphanDelayed() {
+ var delayed = orphanDelayedCallbacks;
+ orphanDelayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
}
- // Find the line object corresponding to the given line number.
- function getLine(doc, n) {
- n -= doc.first;
- if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
- var chunk = doc;
- while (!chunk.lines) {
- for (var i = 0;; ++i) {
- var child = chunk.children[i], sz = child.chunkSize();
- if (n < sz) { chunk = child; break }
- n -= sz;
- }
+ // When an aspect of a line changes, a string is added to
+ // lineView.changes. This updates the relevant part of the line's
+ // DOM structure.
+ function updateLineForChanges(cm, lineView, lineN, dims) {
+ for (var j = 0; j < lineView.changes.length; j++) {
+ var type = lineView.changes[j];
+ if (type == "text") { updateLineText(cm, lineView); }
+ else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
+ else if (type == "class") { updateLineClasses(cm, lineView); }
+ else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
}
- return chunk.lines[n]
+ lineView.changes = null;
}
- // Get the part of a document between two positions, as an array of
- // strings.
- function getBetween(doc, start, end) {
- var out = [], n = start.line;
- doc.iter(start.line, end.line + 1, function (line) {
- var text = line.text;
- if (n == end.line) { text = text.slice(0, end.ch); }
- if (n == start.line) { text = text.slice(start.ch); }
- out.push(text);
- ++n;
- });
- return out
- }
- // Get the lines between from and to, as array of strings.
- function getLines(doc, from, to) {
- var out = [];
- doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
- return out
+ // Lines with gutter elements, widgets or a background class need to
+ // be wrapped, and have the extra elements added to the wrapper div
+ function ensureLineWrapped(lineView) {
+ if (lineView.node == lineView.text) {
+ lineView.node = elt("div", null, null, "position: relative");
+ if (lineView.text.parentNode)
+ { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
+ lineView.node.appendChild(lineView.text);
+ if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
+ }
+ return lineView.node
}
- // Update the height of a line, propagating the height change
- // upwards to parent nodes.
- function updateLineHeight(line, height) {
- var diff = height - line.height;
- if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
+ function updateLineBackground(cm, lineView) {
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
+ if (cls) { cls += " CodeMirror-linebackground"; }
+ if (lineView.background) {
+ if (cls) { lineView.background.className = cls; }
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
+ } else if (cls) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
+ cm.display.input.setUneditable(lineView.background);
+ }
}
- // Given a line object, find its line number by walking up through
- // its parent links.
- function lineNo(line) {
- if (line.parent == null) { return null }
- var cur = line.parent, no = indexOf(cur.lines, line);
- for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
- for (var i = 0;; ++i) {
- if (chunk.children[i] == cur) { break }
- no += chunk.children[i].chunkSize();
- }
+ // Wrapper around buildLineContent which will reuse the structure
+ // in display.externalMeasured when possible.
+ function getLineContent(cm, lineView) {
+ var ext = cm.display.externalMeasured;
+ if (ext && ext.line == lineView.line) {
+ cm.display.externalMeasured = null;
+ lineView.measure = ext.measure;
+ return ext.built
}
- return no + cur.first
+ return buildLineContent(cm, lineView)
}
- // Find the line at the given vertical position, using the height
- // information in the document tree.
- function lineAtHeight(chunk, h) {
- var n = chunk.first;
- outer: do {
- for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
- var child = chunk.children[i$1], ch = child.height;
- if (h < ch) { chunk = child; continue outer }
- h -= ch;
- n += child.chunkSize();
- }
- return n
- } while (!chunk.lines)
- var i = 0;
- for (; i < chunk.lines.length; ++i) {
- var line = chunk.lines[i], lh = line.height;
- if (h < lh) { break }
- h -= lh;
+ // Redraw the line's text. Interacts with the background and text
+ // classes because the mode may output tokens that influence these
+ // classes.
+ function updateLineText(cm, lineView) {
+ var cls = lineView.text.className;
+ var built = getLineContent(cm, lineView);
+ if (lineView.text == lineView.node) { lineView.node = built.pre; }
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
+ lineView.text = built.pre;
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
+ lineView.bgClass = built.bgClass;
+ lineView.textClass = built.textClass;
+ updateLineClasses(cm, lineView);
+ } else if (cls) {
+ lineView.text.className = cls;
}
- return n + i
}
- function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
-
- function lineNumberFor(options, i) {
- return String(options.lineNumberFormatter(i + options.firstLineNumber))
+ function updateLineClasses(cm, lineView) {
+ updateLineBackground(cm, lineView);
+ if (lineView.line.wrapClass)
+ { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
+ else if (lineView.node != lineView.text)
+ { lineView.node.className = ""; }
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
+ lineView.text.className = textClass || "";
}
- // A Pos instance represents a position within the text.
- function Pos(line, ch, sticky) {
- if ( sticky === void 0 ) sticky = null;
-
- if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
- this.line = line;
- this.ch = ch;
- this.sticky = sticky;
+ function updateLineGutter(cm, lineView, lineN, dims) {
+ if (lineView.gutter) {
+ lineView.node.removeChild(lineView.gutter);
+ lineView.gutter = null;
+ }
+ if (lineView.gutterBackground) {
+ lineView.node.removeChild(lineView.gutterBackground);
+ lineView.gutterBackground = null;
+ }
+ if (lineView.line.gutterClass) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
+ ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(lineView.gutterBackground);
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
+ }
+ var markers = lineView.line.gutterMarkers;
+ if (cm.options.lineNumbers || markers) {
+ var wrap$1 = ensureLineWrapped(lineView);
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(gutterWrap);
+ wrap$1.insertBefore(gutterWrap, lineView.text);
+ if (lineView.line.gutterClass)
+ { gutterWrap.className += " " + lineView.line.gutterClass; }
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+ { lineView.lineNumber = gutterWrap.appendChild(
+ elt("div", lineNumberFor(cm.options, lineN),
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
+ if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
+ if (found)
+ { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
+ } }
+ }
}
- // Compare two positions, return 0 if they are the same, a negative
- // number when a is less, and a positive number otherwise.
- function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
-
- function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
+ function updateLineWidgets(cm, lineView, dims) {
+ if (lineView.alignable) { lineView.alignable = null; }
+ for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
+ next = node.nextSibling;
+ if (node.className == "CodeMirror-linewidget")
+ { lineView.node.removeChild(node); }
+ }
+ insertLineWidgets(cm, lineView, dims);
+ }
- function copyPos(x) {return Pos(x.line, x.ch)}
- function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
- function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
+ // Build a line's DOM representation from scratch
+ function buildLineElement(cm, lineView, lineN, dims) {
+ var built = getLineContent(cm, lineView);
+ lineView.text = lineView.node = built.pre;
+ if (built.bgClass) { lineView.bgClass = built.bgClass; }
+ if (built.textClass) { lineView.textClass = built.textClass; }
- // Most of the external API clips given positions to make sure they
- // actually exist within the document.
- function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
- function clipPos(doc, pos) {
- if (pos.line < doc.first) { return Pos(doc.first, 0) }
- var last = doc.first + doc.size - 1;
- if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
- return clipToLen(pos, getLine(doc, pos.line).text.length)
+ updateLineClasses(cm, lineView);
+ updateLineGutter(cm, lineView, lineN, dims);
+ insertLineWidgets(cm, lineView, dims);
+ return lineView.node
}
- function clipToLen(pos, linelen) {
- var ch = pos.ch;
- if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
- else if (ch < 0) { return Pos(pos.line, 0) }
- else { return pos }
+
+ // A lineView may contain multiple logical lines (when merged by
+ // collapsed spans). The widgets for all of them need to be drawn.
+ function insertLineWidgets(cm, lineView, dims) {
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
}
- function clipPosArray(doc, array) {
- var out = [];
- for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
- return out
+
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
+ if (!line.widgets) { return }
+ var wrap = ensureLineWrapped(lineView);
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
+ if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
+ positionLineWidget(widget, node, lineView, dims);
+ cm.display.input.setUneditable(node);
+ if (allowAbove && widget.above)
+ { wrap.insertBefore(node, lineView.gutter || lineView.text); }
+ else
+ { wrap.appendChild(node); }
+ signalLater(widget, "redraw");
+ }
}
- // Optimize some code when these features are not used.
- var sawReadOnlySpans = false;
- var sawCollapsedSpans = false;
+ function positionLineWidget(widget, node, lineView, dims) {
+ if (widget.noHScroll) {
+ (lineView.alignable || (lineView.alignable = [])).push(node);
+ var width = dims.wrapperWidth;
+ node.style.left = dims.fixedPos + "px";
+ if (!widget.coverGutter) {
+ width -= dims.gutterTotalWidth;
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ }
+ node.style.width = width + "px";
+ }
+ if (widget.coverGutter) {
+ node.style.zIndex = 5;
+ node.style.position = "relative";
+ if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
+ }
+ }
- function seeReadOnlySpans() {
- sawReadOnlySpans = true;
+ function widgetHeight(widget) {
+ if (widget.height != null) { return widget.height }
+ var cm = widget.doc.cm;
+ if (!cm) { return 0 }
+ if (!contains(document.body, widget.node)) {
+ var parentStyle = "position: relative;";
+ if (widget.coverGutter)
+ { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
+ if (widget.noHScroll)
+ { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ }
+ return widget.height = widget.node.parentNode.offsetHeight
}
- function seeCollapsedSpans() {
- sawCollapsedSpans = true;
+ // Return true when the given mouse event happened in a widget
+ function eventInWidget(display, e) {
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
+ (n.parentNode == display.sizer && n != display.mover))
+ { return true }
+ }
}
- // TEXTMARKER SPANS
+ // POSITION MEASUREMENT
- function MarkedSpan(marker, from, to) {
- this.marker = marker;
- this.from = from; this.to = to;
+ function paddingTop(display) {return display.lineSpace.offsetTop}
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
+ function paddingH(display) {
+ if (display.cachedPaddingH) { return display.cachedPaddingH }
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
+ if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
+ return data
}
- // Search an array of spans for a span matching the given marker.
- function getMarkedSpanFor(spans, marker) {
- if (spans) { for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if (span.marker == marker) { return span }
- } }
- }
- // Remove a span from an array, returning undefined if no spans are
- // left (we don't store arrays for lines without spans).
- function removeMarkedSpan(spans, span) {
- var r;
- for (var i = 0; i < spans.length; ++i)
- { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
- return r
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
+ function displayWidth(cm) {
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
}
- // Add a span to a line.
- function addMarkedSpan(line, span) {
- line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
- span.marker.attachLine(line);
+ function displayHeight(cm) {
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
}
- // Used for the algorithm that adjusts markers for a change in the
- // document. These functions cut an array of spans at a given
- // character position, returning an array of remaining chunks (or
- // undefined if nothing remains).
- function markedSpansBefore(old, startCh, isInsert) {
- var nw;
- if (old) { for (var i = 0; i < old.length; ++i) {
- var span = old[i], marker = span.marker;
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
- if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
- }
- } }
- return nw
- }
- function markedSpansAfter(old, endCh, isInsert) {
- var nw;
- if (old) { for (var i = 0; i < old.length; ++i) {
- var span = old[i], marker = span.marker;
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
- if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
- span.to == null ? null : span.to - endCh));
+ // Ensure the lineView.wrapping.heights array is populated. This is
+ // an array of bottom offsets for the lines that make up a drawn
+ // line. When lineWrapping is on, there might be more than one
+ // height.
+ function ensureLineHeights(cm, lineView, rect) {
+ var wrapping = cm.options.lineWrapping;
+ var curWidth = wrapping && displayWidth(cm);
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
+ var heights = lineView.measure.heights = [];
+ if (wrapping) {
+ lineView.measure.width = curWidth;
+ var rects = lineView.text.firstChild.getClientRects();
+ for (var i = 0; i < rects.length - 1; i++) {
+ var cur = rects[i], next = rects[i + 1];
+ if (Math.abs(cur.bottom - next.bottom) > 2)
+ { heights.push((cur.bottom + next.top) / 2 - rect.top); }
+ }
}
- } }
- return nw
+ heights.push(rect.bottom - rect.top);
+ }
}
- // Given a change object, compute the new set of marker spans that
- // cover the line in which the change took place. Removes spans
- // entirely within the change, reconnects spans belonging to the
- // same marker that appear on both sides of the change, and cuts off
- // spans partially within the change. Returns an array of span
- // arrays with one element for each line in (after) the change.
- function stretchSpansOverChange(doc, change) {
- if (change.full) { return null }
- var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
- var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
- if (!oldFirst && !oldLast) { return null }
+ // Find a line map (mapping character offsets to text nodes) and a
+ // measurement cache for the given line number. (A line view might
+ // contain multiple lines when collapsed ranges are present.)
+ function mapFromLineView(lineView, line, lineN) {
+ if (lineView.line == line)
+ { return {map: lineView.measure.map, cache: lineView.measure.cache} }
+ for (var i = 0; i < lineView.rest.length; i++)
+ { if (lineView.rest[i] == line)
+ { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
+ for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
+ { if (lineNo(lineView.rest[i$1]) > lineN)
+ { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
+ }
- var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
- // Get the spans that 'stick out' on both sides
- var first = markedSpansBefore(oldFirst, startCh, isInsert);
- var last = markedSpansAfter(oldLast, endCh, isInsert);
+ // Render a line into the hidden node display.externalMeasured. Used
+ // when measurement is needed for a line that's not in the viewport.
+ function updateExternalMeasurement(cm, line) {
+ line = visualLine(line);
+ var lineN = lineNo(line);
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
+ view.lineN = lineN;
+ var built = view.built = buildLineContent(cm, view);
+ view.text = built.pre;
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
+ return view
+ }
- // Next, merge those two ends
- var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
- if (first) {
- // Fix up .to properties of first
- for (var i = 0; i < first.length; ++i) {
- var span = first[i];
- if (span.to == null) {
- var found = getMarkedSpanFor(last, span.marker);
- if (!found) { span.to = startCh; }
- else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
- }
- }
- }
- if (last) {
- // Fix up .from in last (or move them into first in case of sameLine)
- for (var i$1 = 0; i$1 < last.length; ++i$1) {
- var span$1 = last[i$1];
- if (span$1.to != null) { span$1.to += offset; }
- if (span$1.from == null) {
- var found$1 = getMarkedSpanFor(first, span$1.marker);
- if (!found$1) {
- span$1.from = offset;
- if (sameLine) { (first || (first = [])).push(span$1); }
- }
- } else {
- span$1.from += offset;
- if (sameLine) { (first || (first = [])).push(span$1); }
- }
- }
- }
- // Make sure we didn't create any zero-length spans
- if (first) { first = clearEmptySpans(first); }
- if (last && last != first) { last = clearEmptySpans(last); }
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
+ // for a given character.
+ function measureChar(cm, line, ch, bias) {
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
+ }
- var newMarkers = [first];
- if (!sameLine) {
- // Fill gap with whole-line-spans
- var gap = change.text.length - 2, gapMarkers;
- if (gap > 0 && first)
- { for (var i$2 = 0; i$2 < first.length; ++i$2)
- { if (first[i$2].to == null)
- { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
- for (var i$3 = 0; i$3 < gap; ++i$3)
- { newMarkers.push(gapMarkers); }
- newMarkers.push(last);
- }
- return newMarkers
+ // Find a line view that corresponds to the given line number.
+ function findViewForLine(cm, lineN) {
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
+ { return cm.display.view[findViewIndex(cm, lineN)] }
+ var ext = cm.display.externalMeasured;
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
+ { return ext }
}
- // Remove spans that are empty and don't have a clearWhenEmpty
- // option of false.
- function clearEmptySpans(spans) {
- for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
- { spans.splice(i--, 1); }
+ // Measurement can be split in two steps, the set-up work that
+ // applies to the whole line, and the measurement of the actual
+ // character. Functions like coordsChar, that need to do a lot of
+ // measurements in a row, can thus ensure that the set-up work is
+ // only done once.
+ function prepareMeasureForLine(cm, line) {
+ var lineN = lineNo(line);
+ var view = findViewForLine(cm, lineN);
+ if (view && !view.text) {
+ view = null;
+ } else if (view && view.changes) {
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
+ cm.curOp.forceUpdate = true;
}
- if (!spans.length) { return null }
- return spans
- }
+ if (!view)
+ { view = updateExternalMeasurement(cm, line); }
- // Used to 'clip' out readOnly ranges when making a change.
- function removeReadOnlyRanges(doc, from, to) {
- var markers = null;
- doc.iter(from.line, to.line + 1, function (line) {
- if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
- var mark = line.markedSpans[i].marker;
- if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
- { (markers || (markers = [])).push(mark); }
- } }
- });
- if (!markers) { return null }
- var parts = [{from: from, to: to}];
- for (var i = 0; i < markers.length; ++i) {
- var mk = markers[i], m = mk.find(0);
- for (var j = 0; j < parts.length; ++j) {
- var p = parts[j];
- if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
- var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
- if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
- { newParts.push({from: p.from, to: m.from}); }
- if (dto > 0 || !mk.inclusiveRight && !dto)
- { newParts.push({from: m.to, to: p.to}); }
- parts.splice.apply(parts, newParts);
- j += newParts.length - 3;
- }
+ var info = mapFromLineView(view, line, lineN);
+ return {
+ line: line, view: view, rect: null,
+ map: info.map, cache: info.cache, before: info.before,
+ hasHeights: false
}
- return parts
}
- // Connect or disconnect spans from a line.
- function detachMarkedSpans(line) {
- var spans = line.markedSpans;
- if (!spans) { return }
- for (var i = 0; i < spans.length; ++i)
- { spans[i].marker.detachLine(line); }
- line.markedSpans = null;
- }
- function attachMarkedSpans(line, spans) {
- if (!spans) { return }
- for (var i = 0; i < spans.length; ++i)
- { spans[i].marker.attachLine(line); }
- line.markedSpans = spans;
+ // Given a prepared measurement object, measures the position of an
+ // actual character (or fetches it from the cache).
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
+ if (prepared.before) { ch = -1; }
+ var key = ch + (bias || ""), found;
+ if (prepared.cache.hasOwnProperty(key)) {
+ found = prepared.cache[key];
+ } else {
+ if (!prepared.rect)
+ { prepared.rect = prepared.view.text.getBoundingClientRect(); }
+ if (!prepared.hasHeights) {
+ ensureLineHeights(cm, prepared.view, prepared.rect);
+ prepared.hasHeights = true;
+ }
+ found = measureCharInner(cm, prepared, ch, bias);
+ if (!found.bogus) { prepared.cache[key] = found; }
+ }
+ return {left: found.left, right: found.right,
+ top: varHeight ? found.rtop : found.top,
+ bottom: varHeight ? found.rbottom : found.bottom}
}
- // Helpers used when computing which overlapping collapsed span
- // counts as the larger one.
- function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
- function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
- // Returns a number indicating which of two overlapping collapsed
- // spans is larger (and thus includes the other). Falls back to
- // comparing ids when the spans cover exactly the same range.
- function compareCollapsedMarkers(a, b) {
- var lenDiff = a.lines.length - b.lines.length;
- if (lenDiff != 0) { return lenDiff }
- var aPos = a.find(), bPos = b.find();
- var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
- if (fromCmp) { return -fromCmp }
- var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
- if (toCmp) { return toCmp }
- return b.id - a.id
+ function nodeAndOffsetInLineMap(map$$1, ch, bias) {
+ var node, start, end, collapse, mStart, mEnd;
+ // First, search the line map for the text node corresponding to,
+ // or closest to, the target character.
+ for (var i = 0; i < map$$1.length; i += 3) {
+ mStart = map$$1[i];
+ mEnd = map$$1[i + 1];
+ if (ch < mStart) {
+ start = 0; end = 1;
+ collapse = "left";
+ } else if (ch < mEnd) {
+ start = ch - mStart;
+ end = start + 1;
+ } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
+ end = mEnd - mStart;
+ start = end - 1;
+ if (ch >= mEnd) { collapse = "right"; }
+ }
+ if (start != null) {
+ node = map$$1[i + 2];
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
+ { collapse = bias; }
+ if (bias == "left" && start == 0)
+ { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
+ node = map$$1[(i -= 3) + 2];
+ collapse = "left";
+ } }
+ if (bias == "right" && start == mEnd - mStart)
+ { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
+ node = map$$1[(i += 3) + 2];
+ collapse = "right";
+ } }
+ break
+ }
+ }
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
}
- // Find out whether a line ends or starts in a collapsed span. If
- // so, return the marker for that span.
- function collapsedSpanAtSide(line, start) {
- var sps = sawCollapsedSpans && line.markedSpans, found;
- if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
- sp = sps[i];
- if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
- (!found || compareCollapsedMarkers(found, sp.marker) < 0))
- { found = sp.marker; }
+ function getUsefulRect(rects, bias) {
+ var rect = nullRect;
+ if (bias == "left") { for (var i = 0; i < rects.length; i++) {
+ if ((rect = rects[i]).left != rect.right) { break }
+ } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
+ if ((rect = rects[i$1]).left != rect.right) { break }
} }
- return found
+ return rect
}
- function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
- function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
- // Test whether there exists a collapsed span that partially
- // overlaps (covers the start or end, but not both) of a new span.
- // Such overlap is not allowed.
- function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
- var line = getLine(doc, lineNo$$1);
- var sps = sawCollapsedSpans && line.markedSpans;
- if (sps) { for (var i = 0; i < sps.length; ++i) {
- var sp = sps[i];
- if (!sp.marker.collapsed) { continue }
- var found = sp.marker.find(0);
- var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
- var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
- if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
- if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
- fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
- { return true }
- } }
- }
+ function measureCharInner(cm, prepared, ch, bias) {
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
- // A visual line is a line as drawn on the screen. Folding, for
- // example, can cause multiple logical lines to appear on the same
- // visual line. This finds the start of the visual line that the
- // given line is part of (usually that is the line itself).
- function visualLine(line) {
- var merged;
- while (merged = collapsedSpanAtStart(line))
- { line = merged.find(-1, true).line; }
- return line
+ var rect;
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+ for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
+ { rect = node.parentNode.getBoundingClientRect(); }
+ else
+ { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
+ if (rect.left || rect.right || start == 0) { break }
+ end = start;
+ start = start - 1;
+ collapse = "right";
+ }
+ if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
+ } else { // If it is a widget, simply get the box for the whole widget.
+ if (start > 0) { collapse = bias = "right"; }
+ var rects;
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
+ { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
+ else
+ { rect = node.getBoundingClientRect(); }
+ }
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
+ var rSpan = node.parentNode.getClientRects()[0];
+ if (rSpan)
+ { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
+ else
+ { rect = nullRect; }
+ }
+
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
+ var mid = (rtop + rbot) / 2;
+ var heights = prepared.view.measure.heights;
+ var i = 0;
+ for (; i < heights.length - 1; i++)
+ { if (mid < heights[i]) { break } }
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
+ top: top, bottom: bot};
+ if (!rect.left && !rect.right) { result.bogus = true; }
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
+
+ return result
}
- function visualLineEnd(line) {
- var merged;
- while (merged = collapsedSpanAtEnd(line))
- { line = merged.find(1, true).line; }
- return line
+ // Work around problem with bounding client rects on ranges being
+ // returned incorrectly when zoomed on IE10 and below.
+ function maybeUpdateRectForZooming(measure, rect) {
+ if (!window.screen || screen.logicalXDPI == null ||
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
+ { return rect }
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY}
}
- // Returns an array of logical lines that continue the visual line
- // started by the argument, or undefined if there are no such lines.
- function visualLineContinued(line) {
- var merged, lines;
- while (merged = collapsedSpanAtEnd(line)) {
- line = merged.find(1, true).line
- ;(lines || (lines = [])).push(line);
+ function clearLineMeasurementCacheFor(lineView) {
+ if (lineView.measure) {
+ lineView.measure.cache = {};
+ lineView.measure.heights = null;
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { lineView.measure.caches[i] = {}; } }
}
- return lines
}
- // Get the line number of the start of the visual line that the
- // given line number is part of.
- function visualLineNo(doc, lineN) {
- var line = getLine(doc, lineN), vis = visualLine(line);
- if (line == vis) { return lineN }
- return lineNo(vis)
+ function clearLineMeasurementCache(cm) {
+ cm.display.externalMeasure = null;
+ removeChildren(cm.display.lineMeasure);
+ for (var i = 0; i < cm.display.view.length; i++)
+ { clearLineMeasurementCacheFor(cm.display.view[i]); }
}
- // Get the line number of the start of the next visual line after
- // the given line.
- function visualLineEndNo(doc, lineN) {
- if (lineN > doc.lastLine()) { return lineN }
- var line = getLine(doc, lineN), merged;
- if (!lineIsHidden(doc, line)) { return lineN }
- while (merged = collapsedSpanAtEnd(line))
- { line = merged.find(1, true).line; }
- return lineNo(line) + 1
+ function clearCaches(cm) {
+ clearLineMeasurementCache(cm);
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
+ if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
+ cm.display.lineNumChars = null;
}
- // Compute whether a line is hidden. Lines count as hidden when they
- // are part of a visual line that starts with another line, or when
- // they are entirely covered by collapsed, non-widget span.
- function lineIsHidden(doc, line) {
- var sps = sawCollapsedSpans && line.markedSpans;
- if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
- sp = sps[i];
- if (!sp.marker.collapsed) { continue }
- if (sp.from == null) { return true }
- if (sp.marker.widgetNode) { continue }
- if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
- { return true }
- } }
+ function pageScrollX() {
+ // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
+ // which causes page_Offset and bounding client rects to use
+ // different reference viewports and invalidate our calculations.
+ if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
+ return window.pageXOffset || (document.documentElement || document.body).scrollLeft
}
- function lineIsHiddenInner(doc, line, span) {
- if (span.to == null) {
- var end = span.marker.find(1, true);
- return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
- }
- if (span.marker.inclusiveRight && span.to == line.text.length)
- { return true }
- for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
- sp = line.markedSpans[i];
- if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
- (sp.to == null || sp.to != span.from) &&
- (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
- lineIsHiddenInner(doc, line, sp)) { return true }
- }
+ function pageScrollY() {
+ if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
+ return window.pageYOffset || (document.documentElement || document.body).scrollTop
}
- // Find the height above the given line.
- function heightAtLine(lineObj) {
- lineObj = visualLine(lineObj);
-
- var h = 0, chunk = lineObj.parent;
- for (var i = 0; i < chunk.lines.length; ++i) {
- var line = chunk.lines[i];
- if (line == lineObj) { break }
- else { h += line.height; }
- }
- for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
- for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
- var cur = p.children[i$1];
- if (cur == chunk) { break }
- else { h += cur.height; }
- }
- }
- return h
+ function widgetTopHeight(lineObj) {
+ var height = 0;
+ if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
+ { height += widgetHeight(lineObj.widgets[i]); } } }
+ return height
}
- // Compute the character length of a line, taking into account
- // collapsed ranges (see markText) that might hide parts, and join
- // other lines onto it.
- function lineLength(line) {
- if (line.height == 0) { return 0 }
- var len = line.text.length, merged, cur = line;
- while (merged = collapsedSpanAtStart(cur)) {
- var found = merged.find(0, true);
- cur = found.from.line;
- len += found.from.ch - found.to.ch;
+ // Converts a {top, bottom, left, right} box from line-local
+ // coordinates into another coordinate system. Context may be one of
+ // "line", "div" (display.lineDiv), "local"./null (editor), "window",
+ // or "page".
+ function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+ if (!includeWidgets) {
+ var height = widgetTopHeight(lineObj);
+ rect.top += height; rect.bottom += height;
}
- cur = line;
- while (merged = collapsedSpanAtEnd(cur)) {
- var found$1 = merged.find(0, true);
- len -= cur.text.length - found$1.from.ch;
- cur = found$1.to.line;
- len += cur.text.length - found$1.to.ch;
+ if (context == "line") { return rect }
+ if (!context) { context = "local"; }
+ var yOff = heightAtLine(lineObj);
+ if (context == "local") { yOff += paddingTop(cm.display); }
+ else { yOff -= cm.display.viewOffset; }
+ if (context == "page" || context == "window") {
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
+ rect.left += xOff; rect.right += xOff;
}
- return len
+ rect.top += yOff; rect.bottom += yOff;
+ return rect
}
- // Find the longest line in the document.
- function findMaxLine(cm) {
- var d = cm.display, doc = cm.doc;
- d.maxLine = getLine(doc, doc.first);
- d.maxLineLength = lineLength(d.maxLine);
- d.maxLineChanged = true;
- doc.iter(function (line) {
- var len = lineLength(line);
- if (len > d.maxLineLength) {
- d.maxLineLength = len;
- d.maxLine = line;
- }
- });
+ // Coverts a box from "div" coords to another coordinate system.
+ // Context may be "window", "page", "div", or "local"./null.
+ function fromCoordSystem(cm, coords, context) {
+ if (context == "div") { return coords }
+ var left = coords.left, top = coords.top;
+ // First move into "page" coordinate system
+ if (context == "page") {
+ left -= pageScrollX();
+ top -= pageScrollY();
+ } else if (context == "local" || !context) {
+ var localBox = cm.display.sizer.getBoundingClientRect();
+ left += localBox.left;
+ top += localBox.top;
+ }
+
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
}
- // BIDI HELPERS
+ function charCoords(cm, pos, context, lineObj, bias) {
+ if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
+ }
- function iterateBidiSections(order, from, to, f) {
- if (!order) { return f(from, to, "ltr") }
- var found = false;
- for (var i = 0; i < order.length; ++i) {
- var part = order[i];
- if (part.from < to && part.to > from || from == to && part.to == from) {
- f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
- found = true;
- }
+ // Returns a box for a given cursor position, which may have an
+ // 'other' property containing the position of the secondary cursor
+ // on a bidi boundary.
+ // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
+ // and after `char - 1` in writing order of `char - 1`
+ // A cursor Pos(line, char, "after") is on the same visual line as `char`
+ // and before `char` in writing order of `char`
+ // Examples (upper-case letters are RTL, lower-case are LTR):
+ // Pos(0, 1, ...)
+ // before after
+ // ab a|b a|b
+ // aB a|B aB|
+ // Ab |Ab A|b
+ // AB B|A B|A
+ // Every position after the last character on a line is considered to stick
+ // to the last character on the line.
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
+ lineObj = lineObj || getLine(cm.doc, pos.line);
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ function get(ch, right) {
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
+ if (right) { m.left = m.right; } else { m.right = m.left; }
+ return intoCoordSystem(cm, lineObj, m, context)
}
- if (!found) { f(from, to, "ltr"); }
- }
+ var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
+ if (ch >= lineObj.text.length) {
+ ch = lineObj.text.length;
+ sticky = "before";
+ } else if (ch <= 0) {
+ ch = 0;
+ sticky = "after";
+ }
+ if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
- var bidiOther = null;
- function getBidiPartAt(order, ch, sticky) {
- var found;
- bidiOther = null;
- for (var i = 0; i < order.length; ++i) {
- var cur = order[i];
- if (cur.from < ch && cur.to > ch) { return i }
- if (cur.to == ch) {
- if (cur.from != cur.to && sticky == "before") { found = i; }
- else { bidiOther = i; }
- }
- if (cur.from == ch) {
- if (cur.from != cur.to && sticky != "before") { found = i; }
- else { bidiOther = i; }
- }
+ function getBidi(ch, partPos, invert) {
+ var part = order[partPos], right = part.level == 1;
+ return get(invert ? ch - 1 : ch, right != invert)
}
- return found != null ? found : bidiOther
+ var partPos = getBidiPartAt(order, ch, sticky);
+ var other = bidiOther;
+ var val = getBidi(ch, partPos, sticky == "before");
+ if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
+ return val
}
- // Bidirectional ordering algorithm
- // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
- // that this (partially) implements.
-
- // One-char codes used for character types:
- // L (L): Left-to-Right
- // R (R): Right-to-Left
- // r (AL): Right-to-Left Arabic
- // 1 (EN): European Number
- // + (ES): European Number Separator
- // % (ET): European Number Terminator
- // n (AN): Arabic Number
- // , (CS): Common Number Separator
- // m (NSM): Non-Spacing Mark
- // b (BN): Boundary Neutral
- // s (B): Paragraph Separator
- // t (S): Segment Separator
- // w (WS): Whitespace
- // N (ON): Other Neutrals
+ // Used to cheaply estimate the coordinates for a position. Used for
+ // intermediate scroll updates.
+ function estimateCoords(cm, pos) {
+ var left = 0;
+ pos = clipPos(cm.doc, pos);
+ if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
+ var lineObj = getLine(cm.doc, pos.line);
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
+ return {left: left, right: left, top: top, bottom: top + lineObj.height}
+ }
- // Returns null if characters are ordered as they appear
- // (left-to-right), or an array of sections ({from, to, level}
- // objects) in the order in which they occur visually.
- var bidiOrdering = (function() {
- // Character types for codepoints 0 to 0xff
- var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
- // Character types for codepoints 0x600 to 0x6f9
- var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
- function charType(code) {
- if (code <= 0xf7) { return lowTypes.charAt(code) }
- else if (0x590 <= code && code <= 0x5f4) { return "R" }
- else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
- else if (0x6ee <= code && code <= 0x8ac) { return "r" }
- else if (0x2000 <= code && code <= 0x200b) { return "w" }
- else if (code == 0x200c) { return "b" }
- else { return "L" }
- }
+ // Positions returned by coordsChar contain some extra information.
+ // xRel is the relative x position of the input coordinates compared
+ // to the found position (so xRel > 0 means the coordinates are to
+ // the right of the character position, for example). When outside
+ // is true, that means the coordinates lie outside the line's
+ // vertical range.
+ function PosWithInfo(line, ch, sticky, outside, xRel) {
+ var pos = Pos(line, ch, sticky);
+ pos.xRel = xRel;
+ if (outside) { pos.outside = true; }
+ return pos
+ }
- var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
- var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+ // Compute the character position closest to the given coordinates.
+ // Input must be lineSpace-local ("div" coordinate system).
+ function coordsChar(cm, x, y) {
+ var doc = cm.doc;
+ y += cm.display.viewOffset;
+ if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
+ if (lineN > last)
+ { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
+ if (x < 0) { x = 0; }
- function BidiSpan(level, from, to) {
- this.level = level;
- this.from = from; this.to = to;
+ var lineObj = getLine(doc, lineN);
+ for (;;) {
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
+ var merged = collapsedSpanAtEnd(lineObj);
+ var mergedPos = merged && merged.find(0, true);
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
+ { lineN = lineNo(lineObj = mergedPos.to.line); }
+ else
+ { return found }
}
+ }
- return function(str, direction) {
- var outerType = direction == "ltr" ? "L" : "R";
-
- if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
- var len = str.length, types = [];
- for (var i = 0; i < len; ++i)
- { types.push(charType(str.charCodeAt(i))); }
-
- // W1. Examine each non-spacing mark (NSM) in the level run, and
- // change the type of the NSM to the type of the previous
- // character. If the NSM is at the start of the level run, it will
- // get the type of sor.
- for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
- var type = types[i$1];
- if (type == "m") { types[i$1] = prev; }
- else { prev = type; }
- }
-
- // W2. Search backwards from each instance of a European number
- // until the first strong type (R, L, AL, or sor) is found. If an
- // AL is found, change the type of the European number to Arabic
- // number.
- // W3. Change all ALs to R.
- for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
- var type$1 = types[i$2];
- if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
- else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
- }
+ function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
+ y -= widgetTopHeight(lineObj);
+ var end = lineObj.text.length;
+ var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
+ end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
+ return {begin: begin, end: end}
+ }
- // W4. A single European separator between two European numbers
- // changes to a European number. A single common separator between
- // two numbers of the same type changes to that type.
- for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
- var type$2 = types[i$3];
- if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
- else if (type$2 == "," && prev$1 == types[i$3+1] &&
- (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
- prev$1 = type$2;
- }
+ function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
+ return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
+ }
- // W5. A sequence of European terminators adjacent to European
- // numbers changes to all European numbers.
- // W6. Otherwise, separators and terminators change to Other
- // Neutral.
- for (var i$4 = 0; i$4 < len; ++i$4) {
- var type$3 = types[i$4];
- if (type$3 == ",") { types[i$4] = "N"; }
- else if (type$3 == "%") {
- var end = (void 0);
- for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
- var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
- for (var j = i$4; j < end; ++j) { types[j] = replace; }
- i$4 = end - 1;
- }
- }
+ // Returns true if the given side of a box is after the given
+ // coordinates, in top-to-bottom, left-to-right order.
+ function boxIsAfter(box, x, y, left) {
+ return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
+ }
- // W7. Search backwards from each instance of a European number
- // until the first strong type (R, L, or sor) is found. If an L is
- // found, then change the type of the European number to L.
- for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
- var type$4 = types[i$5];
- if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
- else if (isStrong.test(type$4)) { cur$1 = type$4; }
- }
+ function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
+ // Move y into line-local coordinate space
+ y -= heightAtLine(lineObj);
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
+ // When directly calling `measureCharPrepared`, we have to adjust
+ // for the widgets at this line.
+ var widgetHeight$$1 = widgetTopHeight(lineObj);
+ var begin = 0, end = lineObj.text.length, ltr = true;
- // N1. A sequence of neutrals takes the direction of the
- // surrounding strong text if the text on both sides has the same
- // direction. European and Arabic numbers act as if they were R in
- // terms of their influence on neutrals. Start-of-level-run (sor)
- // and end-of-level-run (eor) are used at level run boundaries.
- // N2. Any remaining neutrals take the embedding direction.
- for (var i$6 = 0; i$6 < len; ++i$6) {
- if (isNeutral.test(types[i$6])) {
- var end$1 = (void 0);
- for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
- var before = (i$6 ? types[i$6-1] : outerType) == "L";
- var after = (end$1 < len ? types[end$1] : outerType) == "L";
- var replace$1 = before == after ? (before ? "L" : "R") : outerType;
- for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
- i$6 = end$1 - 1;
- }
+ var order = getOrder(lineObj, cm.doc.direction);
+ // If the line isn't plain left-to-right text, first figure out
+ // which bidi section the coordinates fall into.
+ if (order) {
+ var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
+ (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
+ ltr = part.level != 1;
+ // The awkward -1 offsets are needed because findFirst (called
+ // on these below) will treat its first bound as inclusive,
+ // second as exclusive, but we want to actually address the
+ // characters in the part's range
+ begin = ltr ? part.from : part.to - 1;
+ end = ltr ? part.to : part.from - 1;
+ }
+
+ // A binary search to find the first character whose bounding box
+ // starts after the coordinates. If we run across any whose box wrap
+ // the coordinates, store that.
+ var chAround = null, boxAround = null;
+ var ch = findFirst(function (ch) {
+ var box = measureCharPrepared(cm, preparedMeasure, ch);
+ box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
+ if (!boxIsAfter(box, x, y, false)) { return false }
+ if (box.top <= y && box.left <= x) {
+ chAround = ch;
+ boxAround = box;
}
+ return true
+ }, begin, end);
+
+ var baseX, sticky, outside = false;
+ // If a box around the coordinates was found, use that
+ if (boxAround) {
+ // Distinguish coordinates nearer to the left or right side of the box
+ var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
+ ch = chAround + (atStart ? 0 : 1);
+ sticky = atStart ? "after" : "before";
+ baseX = atLeft ? boxAround.left : boxAround.right;
+ } else {
+ // (Adjust for extended bound, if necessary.)
+ if (!ltr && (ch == end || ch == begin)) { ch++; }
+ // To determine which side to associate with, get the box to the
+ // left of the character and compare it's vertical position to the
+ // coordinates
+ sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
+ (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
+ "after" : "before";
+ // Now get accurate coordinates for this place, in order to get a
+ // base X position
+ var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
+ baseX = coords.left;
+ outside = y < coords.top || y >= coords.bottom;
+ }
+
+ ch = skipExtendingChars(lineObj.text, ch, 1);
+ return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
+ }
+
+ function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
+ // Bidi parts are sorted left-to-right, and in a non-line-wrapping
+ // situation, we can take this ordering to correspond to the visual
+ // ordering. This finds the first part whose end is after the given
+ // coordinates.
+ var index = findFirst(function (i) {
+ var part = order[i], ltr = part.level != 1;
+ return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
+ "line", lineObj, preparedMeasure), x, y, true)
+ }, 0, order.length - 1);
+ var part = order[index];
+ // If this isn't the first part, the part's start is also after
+ // the coordinates, and the coordinates aren't on the same line as
+ // that start, move one part back.
+ if (index > 0) {
+ var ltr = part.level != 1;
+ var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
+ "line", lineObj, preparedMeasure);
+ if (boxIsAfter(start, x, y, true) && start.top > y)
+ { part = order[index - 1]; }
+ }
+ return part
+ }
+
+ function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
+ // In a wrapped line, rtl text on wrapping boundaries can do things
+ // that don't correspond to the ordering in our `order` array at
+ // all, so a binary search doesn't work, and we want to return a
+ // part that only spans one line so that the binary search in
+ // coordsCharInner is safe. As such, we first find the extent of the
+ // wrapped line, and then do a flat search in which we discard any
+ // spans that aren't on the line.
+ var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
+ var begin = ref.begin;
+ var end = ref.end;
+ var part = null, closestDist = null;
+ for (var i = 0; i < order.length; i++) {
+ var p = order[i];
+ if (p.from >= end || p.to <= begin) { continue }
+ var ltr = p.level != 1;
+ var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
+ // Weigh against spans ending before this, so that they are only
+ // picked if nothing ends after
+ var dist = endX < x ? x - endX + 1e9 : endX - x;
+ if (!part || closestDist > dist) {
+ part = p;
+ closestDist = dist;
+ }
+ }
+ if (!part) { part = order[order.length - 1]; }
+ // Clip the part to the wrapped line.
+ if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
+ if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
+ return part
+ }
- // Here we depart from the documented algorithm, in order to avoid
- // building up an actual levels array. Since there are only three
- // levels (0, 1, 2) in an implementation that doesn't take
- // explicit embedding into account, we can build up the order on
- // the fly, without following the level-based algorithm.
- var order = [], m;
- for (var i$7 = 0; i$7 < len;) {
- if (countsAsLeft.test(types[i$7])) {
- var start = i$7;
- for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
- order.push(new BidiSpan(0, start, i$7));
- } else {
- var pos = i$7, at = order.length;
- for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
- for (var j$2 = pos; j$2 < i$7;) {
- if (countsAsNum.test(types[j$2])) {
- if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
- var nstart = j$2;
- for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
- order.splice(at, 0, new BidiSpan(2, nstart, j$2));
- pos = j$2;
- } else { ++j$2; }
- }
- if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
- }
- }
- if (order[0].level == 1 && (m = str.match(/^\s+/))) {
- order[0].from = m[0].length;
- order.unshift(new BidiSpan(0, 0, m[0].length));
- }
- if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
- lst(order).to -= m[0].length;
- order.push(new BidiSpan(0, len - m[0].length, len));
+ var measureText;
+ // Compute the default text height.
+ function textHeight(display) {
+ if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+ if (measureText == null) {
+ measureText = elt("pre");
+ // Measure a bunch of lines, for browsers that compute
+ // fractional heights.
+ for (var i = 0; i < 49; ++i) {
+ measureText.appendChild(document.createTextNode("x"));
+ measureText.appendChild(elt("br"));
}
-
- return direction == "rtl" ? order.reverse() : order
+ measureText.appendChild(document.createTextNode("x"));
}
- })();
-
- // Get the bidi ordering for the given line (and cache it). Returns
- // false for lines that are fully left-to-right, and an array of
- // BidiSpan objects otherwise.
- function getOrder(line, direction) {
- var order = line.order;
- if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
- return order
+ removeChildrenAndAdd(display.measure, measureText);
+ var height = measureText.offsetHeight / 50;
+ if (height > 3) { display.cachedTextHeight = height; }
+ removeChildren(display.measure);
+ return height || 1
}
- function moveCharLogically(line, ch, dir) {
- var target = skipExtendingChars(line.text, ch + dir, dir);
- return target < 0 || target > line.text.length ? null : target
+ // Compute the default character width.
+ function charWidth(display) {
+ if (display.cachedCharWidth != null) { return display.cachedCharWidth }
+ var anchor = elt("span", "xxxxxxxxxx");
+ var pre = elt("pre", [anchor]);
+ removeChildrenAndAdd(display.measure, pre);
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
+ if (width > 2) { display.cachedCharWidth = width; }
+ return width || 10
}
- function moveLogically(line, start, dir) {
- var ch = moveCharLogically(line, start.ch, dir);
- return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
+ // view, so that we don't interleave reading and writing to the DOM.
+ function getDimensions(cm) {
+ var d = cm.display, left = {}, width = {};
+ var gutterLeft = d.gutters.clientLeft;
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
+ width[cm.options.gutters[i]] = n.clientWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth}
}
- function endOfLine(visually, cm, lineObj, lineNo, dir) {
- if (visually) {
- var order = getOrder(lineObj, cm.doc.direction);
- if (order) {
- var part = dir < 0 ? lst(order) : order[0];
- var moveInStorageOrder = (dir < 0) == (part.level == 1);
- var sticky = moveInStorageOrder ? "after" : "before";
- var ch;
- // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
- // it could be that the last bidi part is not on the last visual line,
- // since visual lines contain content order-consecutive chunks.
- // Thus, in rtl, we are looking for the first (content-order) character
- // in the rtl chunk that is on the last line (that is, the same line
- // as the last (content-order) character).
- if (part.level > 0) {
- var prep = prepareMeasureForLine(cm, lineObj);
- ch = dir < 0 ? lineObj.text.length - 1 : 0;
- var targetTop = measureCharPrepared(cm, prep, ch).top;
- ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
- if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1, true); }
- } else { ch = dir < 0 ? part.to : part.from; }
- return new Pos(lineNo, ch, sticky)
- }
- }
- return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
+ // but using getBoundingClientRect to get a sub-pixel-accurate
+ // result.
+ function compensateForHScroll(display) {
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
}
- function moveVisually(cm, line, start, dir) {
- var bidi = getOrder(line, cm.doc.direction);
- if (!bidi) { return moveLogically(line, start, dir) }
- if (start.ch >= line.text.length) {
- start.ch = line.text.length;
- start.sticky = "before";
- } else if (start.ch <= 0) {
- start.ch = 0;
- start.sticky = "after";
- }
- var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
- if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
- // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
- // nothing interesting happens.
- return moveLogically(line, start, dir)
- }
+ // Returns a function that estimates the height of a line, to use as
+ // first approximation until the line becomes visible (and is thus
+ // properly measurable).
+ function estimateHeight(cm) {
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
+ return function (line) {
+ if (lineIsHidden(cm.doc, line)) { return 0 }
- var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
- var prep;
- var getWrappedLineExtent = function (ch) {
- if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
- prep = prep || prepareMeasureForLine(cm, line);
- return wrappedLineExtentChar(cm, line, prep, ch)
- };
- var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
+ var widgetsHeight = 0;
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
+ if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
+ } }
- if (cm.doc.direction == "rtl" || part.level == 1) {
- var moveInStorageOrder = (part.level == 1) == (dir < 0);
- var ch = mv(start, moveInStorageOrder ? 1 : -1);
- if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
- // Case 2: We move within an rtl part or in an rtl editor on the same visual line
- var sticky = moveInStorageOrder ? "before" : "after";
- return new Pos(start.line, ch, sticky)
- }
+ if (wrapping)
+ { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
+ else
+ { return widgetsHeight + th }
}
+ }
- // Case 3: Could not move within this bidi part in this visual line, so leave
- // the current bidi part
-
- var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
- var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
- ? new Pos(start.line, mv(ch, 1), "before")
- : new Pos(start.line, ch, "after"); };
-
- for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
- var part = bidi[partPos];
- var moveInStorageOrder = (dir > 0) == (part.level != 1);
- var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
- if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
- ch = moveInStorageOrder ? part.from : mv(part.to, -1);
- if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
- }
- };
+ function estimateLineHeights(cm) {
+ var doc = cm.doc, est = estimateHeight(cm);
+ doc.iter(function (line) {
+ var estHeight = est(line);
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
+ });
+ }
- // Case 3a: Look for other bidi parts on the same visual line
- var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
- if (res) { return res }
+ // Given a mouse event, find the corresponding position. If liberal
+ // is false, it checks whether a gutter or scrollbar was clicked,
+ // and returns null if it was. forRect is used by rectangular
+ // selections, and tries to estimate a character position even for
+ // coordinates beyond the right of the text.
+ function posFromMouse(cm, e, liberal, forRect) {
+ var display = cm.display;
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
- // Case 3b: Look for other bidi parts on the next visual line
- var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
- if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
- res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
- if (res) { return res }
+ var x, y, space = display.lineSpace.getBoundingClientRect();
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
+ catch (e) { return null }
+ var coords = coordsChar(cm, x, y), line;
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
}
+ return coords
+ }
- // Case 4: Nowhere to move
- return null
+ // Find the view element corresponding to a given line. Return null
+ // when the line isn't visible.
+ function findViewIndex(cm, n) {
+ if (n >= cm.display.viewTo) { return null }
+ n -= cm.display.viewFrom;
+ if (n < 0) { return null }
+ var view = cm.display.view;
+ for (var i = 0; i < view.length; i++) {
+ n -= view[i].size;
+ if (n < 0) { return i }
+ }
}
- // EVENT HANDLING
+ function updateSelection(cm) {
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
+ }
- // Lightweight event framework. on/off also work on DOM nodes,
- // registering native DOM handlers.
+ function prepareSelection(cm, primary) {
+ if ( primary === void 0 ) primary = true;
- var noHandlers = [];
+ var doc = cm.doc, result = {};
+ var curFragment = result.cursors = document.createDocumentFragment();
+ var selFragment = result.selection = document.createDocumentFragment();
- var on = function(emitter, type, f) {
- if (emitter.addEventListener) {
- emitter.addEventListener(type, f, false);
- } else if (emitter.attachEvent) {
- emitter.attachEvent("on" + type, f);
- } else {
- var map$$1 = emitter._handlers || (emitter._handlers = {});
- map$$1[type] = (map$$1[type] || noHandlers).concat(f);
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ if (!primary && i == doc.sel.primIndex) { continue }
+ var range$$1 = doc.sel.ranges[i];
+ if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
+ var collapsed = range$$1.empty();
+ if (collapsed || cm.options.showCursorWhenSelecting)
+ { drawSelectionCursor(cm, range$$1.head, curFragment); }
+ if (!collapsed)
+ { drawSelectionRange(cm, range$$1, selFragment); }
}
- };
-
- function getHandlers(emitter, type) {
- return emitter._handlers && emitter._handlers[type] || noHandlers
+ return result
}
- function off(emitter, type, f) {
- if (emitter.removeEventListener) {
- emitter.removeEventListener(type, f, false);
- } else if (emitter.detachEvent) {
- emitter.detachEvent("on" + type, f);
- } else {
- var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
- if (arr) {
- var index = indexOf(arr, f);
- if (index > -1)
- { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
- }
+ // Draws a cursor for the given range
+ function drawSelectionCursor(cm, head, output) {
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
+
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
+ cursor.style.left = pos.left + "px";
+ cursor.style.top = pos.top + "px";
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+
+ if (pos.other) {
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
+ otherCursor.style.display = "";
+ otherCursor.style.left = pos.other.left + "px";
+ otherCursor.style.top = pos.other.top + "px";
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
}
- function signal(emitter, type /*, values...*/) {
- var handlers = getHandlers(emitter, type);
- if (!handlers.length) { return }
- var args = Array.prototype.slice.call(arguments, 2);
- for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
- }
+ function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
- // The DOM events that CodeMirror handles can be overridden by
- // registering a (non-DOM) handler on the editor for the event name,
- // and preventDefault-ing the event in that handler.
- function signalDOMEvent(cm, e, override) {
- if (typeof e == "string")
- { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
- signal(cm, override || e.type, cm, e);
- return e_defaultPrevented(e) || e.codemirrorIgnore
- }
+ // Draws the given range as a highlighted selection
+ function drawSelectionRange(cm, range$$1, output) {
+ var display = cm.display, doc = cm.doc;
+ var fragment = document.createDocumentFragment();
+ var padding = paddingH(cm.display), leftSide = padding.left;
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
- function signalCursorActivity(cm) {
- var arr = cm._handlers && cm._handlers.cursorActivity;
- if (!arr) { return }
- var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
- for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
- { set.push(arr[i]); } }
- }
+ function add(left, top, width, bottom) {
+ if (top < 0) { top = 0; }
+ top = Math.round(top);
+ bottom = Math.round(bottom);
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
+ }
- function hasHandler(emitter, type) {
- return getHandlers(emitter, type).length > 0
- }
+ function drawForLine(line, fromArg, toArg) {
+ var lineObj = getLine(doc, line);
+ var lineLen = lineObj.text.length;
+ var start, end;
+ function coords(ch, bias) {
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
+ }
- // Add on and off methods to a constructor's prototype, to make
- // registering events on such objects more convenient.
- function eventMixin(ctor) {
- ctor.prototype.on = function(type, f) {on(this, type, f);};
- ctor.prototype.off = function(type, f) {off(this, type, f);};
- }
+ var order = getOrder(lineObj, doc.direction);
+ iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
+ var fromPos = coords(from, dir == "ltr" ? "left" : "right");
+ var toPos = coords(to - 1, dir == "ltr" ? "right" : "left");
+ if (dir == "ltr") {
+ var fromLeft = fromArg == null && from == 0 ? leftSide : fromPos.left;
+ var toRight = toArg == null && to == lineLen ? rightSide : toPos.right;
+ if (toPos.top - fromPos.top <= 3) { // Single line
+ add(fromLeft, toPos.top, toRight - fromLeft, toPos.bottom);
+ } else { // Multiple lines
+ add(fromLeft, fromPos.top, null, fromPos.bottom);
+ if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
+ add(leftSide, toPos.top, toPos.right, toPos.bottom);
+ }
+ } else if (from < to) { // RTL
+ var fromRight = fromArg == null && from == 0 ? rightSide : fromPos.right;
+ var toLeft = toArg == null && to == lineLen ? leftSide : toPos.left;
+ if (toPos.top - fromPos.top <= 3) { // Single line
+ add(toLeft, toPos.top, fromRight - toLeft, toPos.bottom);
+ } else { // Multiple lines
+ var topLeft = leftSide;
+ if (i) {
+ var topEnd = wrappedLineExtentChar(cm, lineObj, null, from).end;
+ // The coordinates returned for an RTL wrapped space tend to
+ // be complete bogus, so try to skip that here.
+ topLeft = coords(topEnd - (/\s/.test(lineObj.text.charAt(topEnd - 1)) ? 2 : 1), "left").left;
+ }
+ add(topLeft, fromPos.top, fromRight - topLeft, fromPos.bottom);
+ if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
+ var botWidth = null;
+ if (i < order.length - 1 || true) {
+ var botStart = wrappedLineExtentChar(cm, lineObj, null, to).begin;
+ botWidth = coords(botStart, "right").right - toLeft;
+ }
+ add(toLeft, toPos.top, botWidth, toPos.bottom);
+ }
+ }
- // Due to the fact that we still support jurassic IE versions, some
- // compatibility wrappers are needed.
+ if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
+ if (cmpCoords(toPos, start) < 0) { start = toPos; }
+ if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
+ if (cmpCoords(toPos, end) < 0) { end = toPos; }
+ });
+ return {start: start, end: end}
+ }
- function e_preventDefault(e) {
- if (e.preventDefault) { e.preventDefault(); }
- else { e.returnValue = false; }
+ var sFrom = range$$1.from(), sTo = range$$1.to();
+ if (sFrom.line == sTo.line) {
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
+ } else {
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
+ if (singleVLine) {
+ if (leftEnd.top < rightStart.top - 2) {
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
+ } else {
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
+ }
+ }
+ if (leftEnd.bottom < rightStart.top)
+ { add(leftSide, leftEnd.bottom, null, rightStart.top); }
+ }
+
+ output.appendChild(fragment);
}
- function e_stopPropagation(e) {
- if (e.stopPropagation) { e.stopPropagation(); }
- else { e.cancelBubble = true; }
+
+ // Cursor-blinking
+ function restartBlink(cm) {
+ if (!cm.state.focused) { return }
+ var display = cm.display;
+ clearInterval(display.blinker);
+ var on = true;
+ display.cursorDiv.style.visibility = "";
+ if (cm.options.cursorBlinkRate > 0)
+ { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
+ cm.options.cursorBlinkRate); }
+ else if (cm.options.cursorBlinkRate < 0)
+ { display.cursorDiv.style.visibility = "hidden"; }
}
- function e_defaultPrevented(e) {
- return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+
+ function ensureFocus(cm) {
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
}
- function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
- function e_target(e) {return e.target || e.srcElement}
- function e_button(e) {
- var b = e.which;
- if (b == null) {
- if (e.button & 1) { b = 1; }
- else if (e.button & 2) { b = 3; }
- else if (e.button & 4) { b = 2; }
- }
- if (mac && e.ctrlKey && b == 1) { b = 3; }
- return b
+ function delayBlurEvent(cm) {
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function () { if (cm.state.delayingBlurEvent) {
+ cm.state.delayingBlurEvent = false;
+ onBlur(cm);
+ } }, 100);
}
- // Detect drag-and-drop
- var dragAndDrop = function() {
- // There is *some* kind of drag-and-drop support in IE6-8, but I
- // couldn't get it to work yet.
- if (ie && ie_version < 9) { return false }
- var div = elt('div');
- return "draggable" in div || "dragDrop" in div
- }();
+ function onFocus(cm, e) {
+ if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
- var zwspSupported;
- function zeroWidthElement(measure) {
- if (zwspSupported == null) {
- var test = elt("span", "\u200b");
- removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
- if (measure.firstChild.offsetHeight != 0)
- { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
+ if (cm.options.readOnly == "nocursor") { return }
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm, e);
+ cm.state.focused = true;
+ addClass(cm.display.wrapper, "CodeMirror-focused");
+ // This test prevents this from firing when a context
+ // menu is closed (since the input reset would kill the
+ // select-all detection hack)
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+ cm.display.input.reset();
+ if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
+ }
+ cm.display.input.receivedFocus();
}
- var node = zwspSupported ? elt("span", "\u200b") :
- elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
- node.setAttribute("cm-text", "");
- return node
+ restartBlink(cm);
}
+ function onBlur(cm, e) {
+ if (cm.state.delayingBlurEvent) { return }
- // Feature-detect IE's crummy client rect reporting for bidi text
- var badBidiRects;
- function hasBadBidiRects(measure) {
- if (badBidiRects != null) { return badBidiRects }
- var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
- var r0 = range(txt, 0, 1).getBoundingClientRect();
- var r1 = range(txt, 1, 2).getBoundingClientRect();
- removeChildren(measure);
- if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
- return badBidiRects = (r1.right - r0.right < 3)
+ if (cm.state.focused) {
+ signal(cm, "blur", cm, e);
+ cm.state.focused = false;
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
}
- // See if "".split is the broken IE version, if so, provide an
- // alternative way to split lines.
- var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
- var pos = 0, result = [], l = string.length;
- while (pos <= l) {
- var nl = string.indexOf("\n", pos);
- if (nl == -1) { nl = string.length; }
- var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
- var rt = line.indexOf("\r");
- if (rt != -1) {
- result.push(line.slice(0, rt));
- pos += rt + 1;
+ // Read the actual heights of the rendered lines, and update their
+ // stored heights to match.
+ function updateHeightsInViewport(cm) {
+ var display = cm.display;
+ var prevBottom = display.lineDiv.offsetTop;
+ for (var i = 0; i < display.view.length; i++) {
+ var cur = display.view[i], height = (void 0);
+ if (cur.hidden) { continue }
+ if (ie && ie_version < 8) {
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
} else {
- result.push(line);
- pos = nl + 1;
+ var box = cur.node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ }
+ var diff = cur.line.height - height;
+ if (height < 2) { height = textHeight(display); }
+ if (diff > .005 || diff < -.005) {
+ updateLineHeight(cur.line, height);
+ updateWidgetHeight(cur.line);
+ if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
+ { updateWidgetHeight(cur.rest[j]); } }
}
}
- return result
- } : function (string) { return string.split(/\r\n?|\n/); };
+ }
- var hasSelection = window.getSelection ? function (te) {
- try { return te.selectionStart != te.selectionEnd }
- catch(e) { return false }
- } : function (te) {
- var range$$1;
- try {range$$1 = te.ownerDocument.selection.createRange();}
- catch(e) {}
- if (!range$$1 || range$$1.parentElement() != te) { return false }
- return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
- };
+ // Read and store the height of line widgets associated with the
+ // given line.
+ function updateWidgetHeight(line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
+ { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } }
+ }
- var hasCopyEvent = (function () {
- var e = elt("div");
- if ("oncopy" in e) { return true }
- e.setAttribute("oncopy", "return;");
- return typeof e.oncopy == "function"
- })();
+ // Compute the lines that are visible in a given viewport (defaults
+ // the the current scroll position). viewport may contain top,
+ // height, and ensure (see op.scrollToPos) properties.
+ function visibleLines(display, doc, viewport) {
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
+ top = Math.floor(top - paddingTop(display));
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
- var badZoomedRects = null;
- function hasBadZoomedRects(measure) {
- if (badZoomedRects != null) { return badZoomedRects }
- var node = removeChildrenAndAdd(measure, elt("span", "x"));
- var normal = node.getBoundingClientRect();
- var fromRange = range(node, 0, 1).getBoundingClientRect();
- return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
+ // forces those lines into the viewport (if possible).
+ if (viewport && viewport.ensure) {
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
+ if (ensureFrom < from) {
+ from = ensureFrom;
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
+ to = ensureTo;
+ }
+ }
+ return {from: from, to: Math.max(to, from + 1)}
}
- // Known modes, by name and by MIME
- var modes = {};
- var mimeModes = {};
-
- // Extra arguments are stored as the mode's dependencies, which is
- // used by (legacy) mechanisms like loadmode.js to automatically
- // load a mode. (Preferred mechanism is the require/define calls.)
- function defineMode(name, mode) {
- if (arguments.length > 2)
- { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
- modes[name] = mode;
+ // Re-align line numbers and gutter marks to compensate for
+ // horizontal scrolling.
+ function alignHorizontally(cm) {
+ var display = cm.display, view = display.view;
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
+ for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
+ if (cm.options.fixedGutter) {
+ if (view[i].gutter)
+ { view[i].gutter.style.left = left; }
+ if (view[i].gutterBackground)
+ { view[i].gutterBackground.style.left = left; }
+ }
+ var align = view[i].alignable;
+ if (align) { for (var j = 0; j < align.length; j++)
+ { align[j].style.left = left; } }
+ } }
+ if (cm.options.fixedGutter)
+ { display.gutters.style.left = (comp + gutterW) + "px"; }
}
- function defineMIME(mime, spec) {
- mimeModes[mime] = spec;
+ // Used to ensure that the line number gutter is still the right
+ // size for the current document size. Returns true when an update
+ // is needed.
+ function maybeUpdateLineNumberWidth(cm) {
+ if (!cm.options.lineNumbers) { return false }
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
+ if (last.length != display.lineNumChars) {
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+ display.lineGutter.style.width = "";
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ updateGutterSpace(cm);
+ return true
+ }
+ return false
}
- // Given a MIME type, a {name, ...options} config object, or a name
- // string, return a mode config object.
- function resolveMode(spec) {
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
- spec = mimeModes[spec];
- } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
- var found = mimeModes[spec.name];
- if (typeof found == "string") { found = {name: found}; }
- spec = createObj(found, spec);
- spec.name = found.name;
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
- return resolveMode("application/xml")
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
- return resolveMode("application/json")
+ // SCROLLING THINGS INTO VIEW
+
+ // If an editor sits on the top or bottom of the window, partially
+ // scrolled out of view, this ensures that the cursor is visible.
+ function maybeScrollWindow(cm, rect) {
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (rect.top + box.top < 0) { doScroll = true; }
+ else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
+ cm.display.lineSpace.appendChild(scrollNode);
+ scrollNode.scrollIntoView(doScroll);
+ cm.display.lineSpace.removeChild(scrollNode);
}
- if (typeof spec == "string") { return {name: spec} }
- else { return spec || {name: "null"} }
}
- // Given a mode spec (anything that resolveMode accepts), find and
- // initialize an actual mode object.
- function getMode(options, spec) {
- spec = resolveMode(spec);
- var mfactory = modes[spec.name];
- if (!mfactory) { return getMode(options, "text/plain") }
- var modeObj = mfactory(options, spec);
- if (modeExtensions.hasOwnProperty(spec.name)) {
- var exts = modeExtensions[spec.name];
- for (var prop in exts) {
- if (!exts.hasOwnProperty(prop)) { continue }
- if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
- modeObj[prop] = exts[prop];
+ // Scroll a given position into view (immediately), verifying that
+ // it actually became visible (as line heights are accurately
+ // measured, the position of something may 'drift' during drawing).
+ function scrollPosIntoView(cm, pos, end, margin) {
+ if (margin == null) { margin = 0; }
+ var rect;
+ if (!cm.options.lineWrapping && pos == end) {
+ // Set pos and end to the cursor positions around the character pos sticks to
+ // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
+ // If pos == Pos(_, 0, "before"), pos and end are unchanged
+ pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
+ end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
+ }
+ for (var limit = 0; limit < 5; limit++) {
+ var changed = false;
+ var coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ rect = {left: Math.min(coords.left, endCoords.left),
+ top: Math.min(coords.top, endCoords.top) - margin,
+ right: Math.max(coords.left, endCoords.left),
+ bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
+ var scrollPos = calculateScrollPos(cm, rect);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ updateScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
}
+ if (!changed) { break }
}
- modeObj.name = spec.name;
- if (spec.helperType) { modeObj.helperType = spec.helperType; }
- if (spec.modeProps) { for (var prop$1 in spec.modeProps)
- { modeObj[prop$1] = spec.modeProps[prop$1]; } }
-
- return modeObj
+ return rect
}
- // This can be used to attach properties to mode objects from
- // outside the actual mode definition.
- var modeExtensions = {};
- function extendMode(mode, properties) {
- var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
- copyObj(properties, exts);
+ // Scroll a given set of coordinates into view (immediately).
+ function scrollIntoView(cm, rect) {
+ var scrollPos = calculateScrollPos(cm, rect);
+ if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
+ if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
}
- function copyState(mode, state) {
- if (state === true) { return state }
- if (mode.copyState) { return mode.copyState(state) }
- var nstate = {};
- for (var n in state) {
- var val = state[n];
- if (val instanceof Array) { val = val.concat([]); }
- nstate[n] = val;
+ // Calculate a new scroll position needed to scroll the given
+ // rectangle into view. Returns an object with scrollTop and
+ // scrollLeft properties. When these are undefined, the
+ // vertical/horizontal position does not need to be adjusted.
+ function calculateScrollPos(cm, rect) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (rect.top < 0) { rect.top = 0; }
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = displayHeight(cm), result = {};
+ if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
+ if (rect.top < screentop) {
+ result.scrollTop = atTop ? 0 : rect.top;
+ } else if (rect.bottom > screentop + screen) {
+ var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
+ if (newTop != screentop) { result.scrollTop = newTop; }
}
- return nstate
+
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
+ var tooWide = rect.right - rect.left > screenw;
+ if (tooWide) { rect.right = rect.left + screenw; }
+ if (rect.left < 10)
+ { result.scrollLeft = 0; }
+ else if (rect.left < screenleft)
+ { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
+ else if (rect.right > screenw + screenleft - 3)
+ { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
+ return result
}
- // Given a mode and a state (for that mode), find the inner mode and
- // state at the position that the state refers to.
- function innerMode(mode, state) {
- var info;
- while (mode.innerMode) {
- info = mode.innerMode(state);
- if (!info || info.mode == mode) { break }
- state = info.state;
- mode = info.mode;
- }
- return info || {mode: mode, state: state}
+ // Store a relative adjustment to the scroll position in the current
+ // operation (to be applied when the operation finishes).
+ function addToScrollTop(cm, top) {
+ if (top == null) { return }
+ resolveScrollToPos(cm);
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}
- function startState(mode, a1, a2) {
- return mode.startState ? mode.startState(a1, a2) : true
+ // Make sure that at the end of the operation the current cursor is
+ // shown.
+ function ensureCursorVisible(cm) {
+ resolveScrollToPos(cm);
+ var cur = cm.getCursor();
+ cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
}
- // STRING STREAM
+ function scrollToCoords(cm, x, y) {
+ if (x != null || y != null) { resolveScrollToPos(cm); }
+ if (x != null) { cm.curOp.scrollLeft = x; }
+ if (y != null) { cm.curOp.scrollTop = y; }
+ }
- // Fed to the mode parsers, provides helper functions to make
- // parsers more succinct.
+ function scrollToRange(cm, range$$1) {
+ resolveScrollToPos(cm);
+ cm.curOp.scrollToPos = range$$1;
+ }
- var StringStream = function(string, tabSize) {
- this.pos = this.start = 0;
- this.string = string;
- this.tabSize = tabSize || 8;
- this.lastColumnPos = this.lastColumnValue = 0;
- this.lineStart = 0;
- };
-
- StringStream.prototype.eol = function () {return this.pos >= this.string.length};
- StringStream.prototype.sol = function () {return this.pos == this.lineStart};
- StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
- StringStream.prototype.next = function () {
- if (this.pos < this.string.length)
- { return this.string.charAt(this.pos++) }
- };
- StringStream.prototype.eat = function (match) {
- var ch = this.string.charAt(this.pos);
- var ok;
- if (typeof match == "string") { ok = ch == match; }
- else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
- if (ok) {++this.pos; return ch}
- };
- StringStream.prototype.eatWhile = function (match) {
- var start = this.pos;
- while (this.eat(match)){}
- return this.pos > start
- };
- StringStream.prototype.eatSpace = function () {
- var this$1 = this;
-
- var start = this.pos;
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
- return this.pos > start
- };
- StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
- StringStream.prototype.skipTo = function (ch) {
- var found = this.string.indexOf(ch, this.pos);
- if (found > -1) {this.pos = found; return true}
- };
- StringStream.prototype.backUp = function (n) {this.pos -= n;};
- StringStream.prototype.column = function () {
- if (this.lastColumnPos < this.start) {
- this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
- this.lastColumnPos = this.start;
- }
- return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
- };
- StringStream.prototype.indentation = function () {
- return countColumn(this.string, null, this.tabSize) -
- (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
- };
- StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
- if (typeof pattern == "string") {
- var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
- var substr = this.string.substr(this.pos, pattern.length);
- if (cased(substr) == cased(pattern)) {
- if (consume !== false) { this.pos += pattern.length; }
- return true
- }
- } else {
- var match = this.string.slice(this.pos).match(pattern);
- if (match && match.index > 0) { return null }
- if (match && consume !== false) { this.pos += match[0].length; }
- return match
- }
- };
- StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
- StringStream.prototype.hideFirstChars = function (n, inner) {
- this.lineStart += n;
- try { return inner() }
- finally { this.lineStart -= n; }
- };
-
- // Compute a style array (an array starting with a mode generation
- // -- for invalidation -- followed by pairs of end positions and
- // style strings), which is used to highlight the tokens on the
- // line.
- function highlightLine(cm, line, state, forceToEnd) {
- // A styles array always starts with a number identifying the
- // mode/overlays that it is based on (for easy invalidation).
- var st = [cm.state.modeGen], lineClasses = {};
- // Compute the base array of styles
- runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
- lineClasses, forceToEnd);
-
- // Run overlays, adjust style array.
- var loop = function ( o ) {
- var overlay = cm.state.overlays[o], i = 1, at = 0;
- runMode(cm, line.text, overlay.mode, true, function (end, style) {
- var start = i;
- // Ensure there's a token end at the current position, and that i points at it
- while (at < end) {
- var i_end = st[i];
- if (i_end > end)
- { st.splice(i, 1, end, st[i+1], i_end); }
- i += 2;
- at = Math.min(end, i_end);
- }
- if (!style) { return }
- if (overlay.opaque) {
- st.splice(start, i - start, end, "overlay " + style);
- i = start + 2;
- } else {
- for (; start < i; start += 2) {
- var cur = st[start+1];
- st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
- }
- }
- }, lineClasses);
- };
-
- for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
-
- return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
- }
-
- function getLineStyles(cm, line, updateFrontier) {
- if (!line.styles || line.styles[0] != cm.state.modeGen) {
- var state = getStateBefore(cm, lineNo(line));
- var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
- line.stateAfter = state;
- line.styles = result.styles;
- if (result.classes) { line.styleClasses = result.classes; }
- else if (line.styleClasses) { line.styleClasses = null; }
- if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++; }
+ // When an operation has its scrollToPos property set, and another
+ // scroll action is applied before the end of the operation, this
+ // 'simulates' scrolling that position into view in a cheap way, so
+ // that the effect of intermediate scroll commands is not ignored.
+ function resolveScrollToPos(cm) {
+ var range$$1 = cm.curOp.scrollToPos;
+ if (range$$1) {
+ cm.curOp.scrollToPos = null;
+ var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
+ scrollToCoordsRange(cm, from, to, range$$1.margin);
}
- return line.styles
}
- function getStateBefore(cm, n, precise) {
- var doc = cm.doc, display = cm.display;
- if (!doc.mode.startState) { return true }
- var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
- if (!state) { state = startState(doc.mode); }
- else { state = copyState(doc.mode, state); }
- doc.iter(pos, n, function (line) {
- processLine(cm, line.text, state);
- var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
- line.stateAfter = save ? copyState(doc.mode, state) : null;
- ++pos;
+ function scrollToCoordsRange(cm, from, to, margin) {
+ var sPos = calculateScrollPos(cm, {
+ left: Math.min(from.left, to.left),
+ top: Math.min(from.top, to.top) - margin,
+ right: Math.max(from.right, to.right),
+ bottom: Math.max(from.bottom, to.bottom) + margin
});
- if (precise) { doc.frontier = pos; }
- return state
+ scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
}
- // Lightweight form of highlight -- proceed over this line and
- // update state, but don't save a style array. Used for lines that
- // aren't currently visible.
- function processLine(cm, text, state, startAt) {
- var mode = cm.doc.mode;
- var stream = new StringStream(text, cm.options.tabSize);
- stream.start = stream.pos = startAt || 0;
- if (text == "") { callBlankLine(mode, state); }
- while (!stream.eol()) {
- readToken(mode, stream, state);
- stream.start = stream.pos;
- }
+ // Sync the scrollable area and scrollbars, ensure the viewport
+ // covers the visible area.
+ function updateScrollTop(cm, val) {
+ if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
+ if (!gecko) { updateDisplaySimple(cm, {top: val}); }
+ setScrollTop(cm, val, true);
+ if (gecko) { updateDisplaySimple(cm); }
+ startWorker(cm, 100);
}
- function callBlankLine(mode, state) {
- if (mode.blankLine) { return mode.blankLine(state) }
- if (!mode.innerMode) { return }
- var inner = innerMode(mode, state);
- if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
+ function setScrollTop(cm, val, forceScroll) {
+ val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
+ if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
+ cm.doc.scrollTop = val;
+ cm.display.scrollbars.setScrollTop(val);
+ if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
}
- function readToken(mode, stream, state, inner) {
- for (var i = 0; i < 10; i++) {
- if (inner) { inner[0] = innerMode(mode, state).mode; }
- var style = mode.token(stream, state);
- if (stream.pos > stream.start) { return style }
- }
- throw new Error("Mode " + mode.name + " failed to advance stream.")
+ // Sync scroller and scrollbar, ensure the gutter elements are
+ // aligned.
+ function setScrollLeft(cm, val, isScroller, forceScroll) {
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
+ if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
+ cm.doc.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
+ cm.display.scrollbars.setScrollLeft(val);
}
- // Utility for getTokenAt and getLineTokens
- function takeToken(cm, pos, precise, asArray) {
- var getObj = function (copy) { return ({
- start: stream.start, end: stream.pos,
- string: stream.current(),
- type: style || null,
- state: copy ? copyState(doc.mode, state) : state
- }); };
+ // SCROLLBARS
- var doc = cm.doc, mode = doc.mode, style;
- pos = clipPos(doc, pos);
- var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
- var stream = new StringStream(line.text, cm.options.tabSize), tokens;
- if (asArray) { tokens = []; }
- while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
- stream.start = stream.pos;
- style = readToken(mode, stream, state);
- if (asArray) { tokens.push(getObj(true)); }
+ // Prepare DOM reads needed to update the scrollbars. Done in one
+ // shot to minimize update/measure roundtrips.
+ function measureForScrollbars(cm) {
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
+ return {
+ clientHeight: d.scroller.clientHeight,
+ viewHeight: d.wrapper.clientHeight,
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
+ viewWidth: d.wrapper.clientWidth,
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
+ docHeight: docH,
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
+ nativeBarWidth: d.nativeBarWidth,
+ gutterWidth: gutterW
}
- return asArray ? tokens : getObj()
}
- function extractLineClasses(type, output) {
- if (type) { for (;;) {
- var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
- if (!lineClass) { break }
- type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
- var prop = lineClass[1] ? "bgClass" : "textClass";
- if (output[prop] == null)
- { output[prop] = lineClass[2]; }
- else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
- { output[prop] += " " + lineClass[2]; }
- } }
- return type
- }
+ var NativeScrollbars = function(place, scroll, cm) {
+ this.cm = cm;
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
+ place(vert); place(horiz);
- // Run the given mode's parser over a line, calling f for each token.
- function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
- var flattenSpans = mode.flattenSpans;
- if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
- var curStart = 0, curStyle = null;
- var stream = new StringStream(text, cm.options.tabSize), style;
- var inner = cm.options.addModeClass && [null];
- if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses); }
- while (!stream.eol()) {
- if (stream.pos > cm.options.maxHighlightLength) {
- flattenSpans = false;
- if (forceToEnd) { processLine(cm, text, state, stream.pos); }
- stream.pos = text.length;
- style = null;
- } else {
- style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
- }
- if (inner) {
- var mName = inner[0].name;
- if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
- }
- if (!flattenSpans || curStyle != style) {
- while (curStart < stream.start) {
- curStart = Math.min(stream.start, curStart + 5000);
- f(curStart, curStyle);
- }
- curStyle = style;
- }
- stream.start = stream.pos;
+ on(vert, "scroll", function () {
+ if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
+ });
+ on(horiz, "scroll", function () {
+ if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
+ });
+
+ this.checkedZeroWidth = false;
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
+ };
+
+ NativeScrollbars.prototype.update = function (measure) {
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
+ var sWidth = measure.nativeBarWidth;
+
+ if (needsV) {
+ this.vert.style.display = "block";
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
+ // A bug in IE8 can cause this value to be negative, so guard it.
+ this.vert.firstChild.style.height =
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
+ } else {
+ this.vert.style.display = "";
+ this.vert.firstChild.style.height = "0";
}
- while (curStart < stream.pos) {
- // Webkit seems to refuse to render text nodes longer than 57444
- // characters, and returns inaccurate measurements in nodes
- // starting around 5000 chars.
- var pos = Math.min(stream.pos, curStart + 5000);
- f(pos, curStyle);
- curStart = pos;
+
+ if (needsH) {
+ this.horiz.style.display = "block";
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
+ this.horiz.style.left = measure.barLeft + "px";
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
+ this.horiz.firstChild.style.width =
+ Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
+ } else {
+ this.horiz.style.display = "";
+ this.horiz.firstChild.style.width = "0";
}
- }
- // Finds the line to start with when starting a parse. Tries to
- // find a line with a stateAfter, so that it can start with a
- // valid state. If that fails, it returns the line with the
- // smallest indentation, which tends to need the least context to
- // parse correctly.
- function findStartLine(cm, n, precise) {
- var minindent, minline, doc = cm.doc;
- var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
- for (var search = n; search > lim; --search) {
- if (search <= doc.first) { return doc.first }
- var line = getLine(doc, search - 1);
- if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
- var indented = countColumn(line.text, null, cm.options.tabSize);
- if (minline == null || minindent > indented) {
- minline = search - 1;
- minindent = indented;
- }
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
+ if (sWidth == 0) { this.zeroWidthHack(); }
+ this.checkedZeroWidth = true;
}
- return minline
- }
- // LINE DATA STRUCTURE
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+ };
- // Line objects. These hold state related to a line, including
- // highlighting info (the styles array).
- var Line = function(text, markedSpans, estimateHeight) {
- this.text = text;
- attachMarkedSpans(this, markedSpans);
- this.height = estimateHeight ? estimateHeight(this) : 1;
+ NativeScrollbars.prototype.setScrollLeft = function (pos) {
+ if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
+ if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
};
- Line.prototype.lineNo = function () { return lineNo(this) };
- eventMixin(Line);
+ NativeScrollbars.prototype.setScrollTop = function (pos) {
+ if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
+ if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
+ };
- // Change the content (text, markers) of a line. Automatically
- // invalidates cached information and tries to re-estimate the
- // line's height.
- function updateLine(line, text, markedSpans, estimateHeight) {
- line.text = text;
- if (line.stateAfter) { line.stateAfter = null; }
- if (line.styles) { line.styles = null; }
- if (line.order != null) { line.order = null; }
- detachMarkedSpans(line);
- attachMarkedSpans(line, markedSpans);
- var estHeight = estimateHeight ? estimateHeight(line) : 1;
- if (estHeight != line.height) { updateLineHeight(line, estHeight); }
- }
+ NativeScrollbars.prototype.zeroWidthHack = function () {
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
+ this.horiz.style.height = this.vert.style.width = w;
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
+ this.disableHoriz = new Delayed;
+ this.disableVert = new Delayed;
+ };
- // Detach a line from the document tree and its markers.
- function cleanUpLine(line) {
- line.parent = null;
- detachMarkedSpans(line);
- }
+ NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
+ bar.style.pointerEvents = "auto";
+ function maybeDisable() {
+ // To find out whether the scrollbar is still visible, we
+ // check whether the element under the pixel in the bottom
+ // right corner of the scrollbar box is the scrollbar box
+ // itself (when the bar is still visible) or its filler child
+ // (when the bar is hidden). If it is still visible, we keep
+ // it enabled, if it's hidden, we disable pointer events.
+ var box = bar.getBoundingClientRect();
+ var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
+ : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
+ if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
+ else { delay.set(1000, maybeDisable); }
+ }
+ delay.set(1000, maybeDisable);
+ };
- // Convert a style as returned by a mode (either null, or a string
- // containing one or more styles) to a CSS style. This is cached,
- // and also looks for line-wide styles.
- var styleToClassCache = {};
- var styleToClassCacheWithMode = {};
- function interpretTokenStyle(style, options) {
- if (!style || /^\s*$/.test(style)) { return null }
- var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
- return cache[style] ||
- (cache[style] = style.replace(/\S+/g, "cm-$&"))
+ NativeScrollbars.prototype.clear = function () {
+ var parent = this.horiz.parentNode;
+ parent.removeChild(this.horiz);
+ parent.removeChild(this.vert);
+ };
+
+ var NullScrollbars = function () {};
+
+ NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+ NullScrollbars.prototype.setScrollLeft = function () {};
+ NullScrollbars.prototype.setScrollTop = function () {};
+ NullScrollbars.prototype.clear = function () {};
+
+ function updateScrollbars(cm, measure) {
+ if (!measure) { measure = measureForScrollbars(cm); }
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
+ updateScrollbarsInner(cm, measure);
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
+ { updateHeightsInViewport(cm); }
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
+ }
}
- // Render the DOM representation of the text of a line. Also builds
- // up a 'line map', which points at the DOM nodes that represent
- // specific stretches of text, and is used by the measuring code.
- // The returned object contains the DOM node, this map, and
- // information about line-wide styles that were set by the mode.
- function buildLineContent(cm, lineView) {
- // The padding-right forces the element to have a 'border', which
- // is needed on Webkit to be able to get line-level bounding
- // rectangles for it (in measureChar).
- var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
- var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
- col: 0, pos: 0, cm: cm,
- trailingSpace: false,
- splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
- lineView.measure = {};
+ // Re-synchronize the fake scrollbars with the actual size of the
+ // content.
+ function updateScrollbarsInner(cm, measure) {
+ var d = cm.display;
+ var sizes = d.scrollbars.update(measure);
- // Iterate over the logical lines that make up this visual line.
- for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
- var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
- builder.pos = 0;
- builder.addToken = buildToken;
- // Optionally wire in some hacks into the token-rendering
- // algorithm, to deal with browser quirks.
- if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
- { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
- builder.map = [];
- var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
- insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
- if (line.styleClasses) {
- if (line.styleClasses.bgClass)
- { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
- if (line.styleClasses.textClass)
- { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
- }
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
- // Ensure at least a single node is present, for measuring.
- if (builder.map.length == 0)
- { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
+ if (sizes.right && sizes.bottom) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
+ d.scrollbarFiller.style.width = sizes.right + "px";
+ } else { d.scrollbarFiller.style.display = ""; }
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+ d.gutterFiller.style.display = "block";
+ d.gutterFiller.style.height = sizes.bottom + "px";
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
+ } else { d.gutterFiller.style.display = ""; }
+ }
- // Store the map and a cache object for the current logical line
- if (i == 0) {
- lineView.measure.map = builder.map;
- lineView.measure.cache = {};
- } else {
- (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
- ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
- }
- }
+ var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
- // See issue #2901
- if (webkit) {
- var last = builder.content.lastChild;
- if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
- { builder.content.className = "cm-tab-wrap-hack"; }
+ function initScrollbars(cm) {
+ if (cm.display.scrollbars) {
+ cm.display.scrollbars.clear();
+ if (cm.display.scrollbars.addClass)
+ { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
- signal(cm, "renderLine", cm, lineView.line, builder.pre);
- if (builder.pre.className)
- { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
-
- return builder
+ cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
+ // Prevent clicks in the scrollbars from killing focus
+ on(node, "mousedown", function () {
+ if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
+ });
+ node.setAttribute("cm-not-content", "true");
+ }, function (pos, axis) {
+ if (axis == "horizontal") { setScrollLeft(cm, pos); }
+ else { updateScrollTop(cm, pos); }
+ }, cm);
+ if (cm.display.scrollbars.addClass)
+ { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
- function defaultSpecialCharPlaceholder(ch) {
- var token = elt("span", "\u2022", "cm-invalidchar");
- token.title = "\\u" + ch.charCodeAt(0).toString(16);
- token.setAttribute("aria-label", token.title);
- return token
+ // Operations are used to wrap a series of changes to the editor
+ // state in such a way that each change won't have to update the
+ // cursor and display (which would be awkward, slow, and
+ // error-prone). Instead, display updates are batched and then all
+ // combined and executed at once.
+
+ var nextOpId = 0;
+ // Start a new operation.
+ function startOperation(cm) {
+ cm.curOp = {
+ cm: cm,
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
+ forceUpdate: false, // Used to force a redraw
+ updateInput: null, // Whether to reset the input textarea
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
+ changeObjs: null, // Accumulated changes, for firing change events
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
+ selectionChanged: false, // Whether the selection needs to be redrawn
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
+ scrollToPos: null, // Used to scroll to a specific position
+ focus: false,
+ id: ++nextOpId // Unique ID
+ };
+ pushOperation(cm.curOp);
}
- // Build up the DOM representation for a single token, and add it to
- // the line map. Takes care to render special characters separately.
- function buildToken(builder, text, style, startStyle, endStyle, title, css) {
- if (!text) { return }
- var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
- var special = builder.cm.state.specialChars, mustWrap = false;
- var content;
- if (!special.test(text)) {
- builder.col += text.length;
- content = document.createTextNode(displayText);
- builder.map.push(builder.pos, builder.pos + text.length, content);
- if (ie && ie_version < 9) { mustWrap = true; }
- builder.pos += text.length;
- } else {
- content = document.createDocumentFragment();
- var pos = 0;
- while (true) {
- special.lastIndex = pos;
- var m = special.exec(text);
- var skipped = m ? m.index - pos : text.length - pos;
- if (skipped) {
- var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
- if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
- else { content.appendChild(txt); }
- builder.map.push(builder.pos, builder.pos + skipped, txt);
- builder.col += skipped;
- builder.pos += skipped;
- }
- if (!m) { break }
- pos += skipped + 1;
- var txt$1 = (void 0);
- if (m[0] == "\t") {
- var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
- txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
- txt$1.setAttribute("role", "presentation");
- txt$1.setAttribute("cm-text", "\t");
- builder.col += tabWidth;
- } else if (m[0] == "\r" || m[0] == "\n") {
- txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
- txt$1.setAttribute("cm-text", m[0]);
- builder.col += 1;
- } else {
- txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
- txt$1.setAttribute("cm-text", m[0]);
- if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
- else { content.appendChild(txt$1); }
- builder.col += 1;
- }
- builder.map.push(builder.pos, builder.pos + 1, txt$1);
- builder.pos++;
- }
- }
- builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
- if (style || startStyle || endStyle || mustWrap || css) {
- var fullStyle = style || "";
- if (startStyle) { fullStyle += startStyle; }
- if (endStyle) { fullStyle += endStyle; }
- var token = elt("span", [content], fullStyle, css);
- if (title) { token.title = title; }
- return builder.content.appendChild(token)
- }
- builder.content.appendChild(content);
+ // Finish an operation, updating the display and signalling delayed events
+ function endOperation(cm) {
+ var op = cm.curOp;
+ finishOperation(op, function (group) {
+ for (var i = 0; i < group.ops.length; i++)
+ { group.ops[i].cm.curOp = null; }
+ endOperations(group);
+ });
}
- function splitSpaces(text, trailingBefore) {
- if (text.length > 1 && !/ /.test(text)) { return text }
- var spaceBefore = trailingBefore, result = "";
- for (var i = 0; i < text.length; i++) {
- var ch = text.charAt(i);
- if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
- { ch = "\u00a0"; }
- result += ch;
- spaceBefore = ch == " ";
- }
- return result
+ // The DOM updates done when an operation finishes are batched so
+ // that the minimum number of relayouts are required.
+ function endOperations(group) {
+ var ops = group.ops;
+ for (var i = 0; i < ops.length; i++) // Read DOM
+ { endOperation_R1(ops[i]); }
+ for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
+ { endOperation_W1(ops[i$1]); }
+ for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
+ { endOperation_R2(ops[i$2]); }
+ for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
+ { endOperation_W2(ops[i$3]); }
+ for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
+ { endOperation_finish(ops[i$4]); }
}
- // Work around nonsense dimensions being reported for stretches of
- // right-to-left text.
- function buildTokenBadBidi(inner, order) {
- return function (builder, text, style, startStyle, endStyle, title, css) {
- style = style ? style + " cm-force-border" : "cm-force-border";
- var start = builder.pos, end = start + text.length;
- for (;;) {
- // Find the part that overlaps with the start of this text
- var part = (void 0);
- for (var i = 0; i < order.length; i++) {
- part = order[i];
- if (part.to > start && part.from <= start) { break }
- }
- if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
- inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
- startStyle = null;
- text = text.slice(part.to - start);
- start = part.to;
- }
- }
+ function endOperation_R1(op) {
+ var cm = op.cm, display = cm.display;
+ maybeClipScrollbars(cm);
+ if (op.updateMaxLine) { findMaxLine(cm); }
+
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
+ op.scrollToPos.to.line >= display.viewTo) ||
+ display.maxLineChanged && cm.options.lineWrapping;
+ op.update = op.mustUpdate &&
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
}
- function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
- var widget = !ignoreWidget && marker.widgetNode;
- if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
- if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
- if (!widget)
- { widget = builder.content.appendChild(document.createElement("span")); }
- widget.setAttribute("cm-marker", marker.id);
- }
- if (widget) {
- builder.cm.display.input.setUneditable(widget);
- builder.content.appendChild(widget);
- }
- builder.pos += size;
- builder.trailingSpace = false;
+ function endOperation_W1(op) {
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
}
- // Outputs a number of spans to make up a line, taking highlighting
- // and marked text into account.
- function insertLineContent(line, builder, styles) {
- var spans = line.markedSpans, allText = line.text, at = 0;
- if (!spans) {
- for (var i$1 = 1; i$1 < styles.length; i$1+=2)
- { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
- return
+ function endOperation_R2(op) {
+ var cm = op.cm, display = cm.display;
+ if (op.updatedDisplay) { updateHeightsInViewport(cm); }
+
+ op.barMeasure = measureForScrollbars(cm);
+
+ // If the max line changed since it was last measured, measure it,
+ // and ensure the document's width matches it.
+ // updateDisplay_W2 will use these properties to do the actual resizing
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
+ cm.display.sizerWidth = op.adjustWidthTo;
+ op.barMeasure.scrollWidth =
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
}
- var len = allText.length, pos = 0, i = 1, text = "", style, css;
- var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
- for (;;) {
- if (nextChange == pos) { // Update current marker set
- spanStyle = spanEndStyle = spanStartStyle = title = css = "";
- collapsed = null; nextChange = Infinity;
- var foundBookmarks = [], endStyles = (void 0);
- for (var j = 0; j < spans.length; ++j) {
- var sp = spans[j], m = sp.marker;
- if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
- foundBookmarks.push(m);
- } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
- if (sp.to != null && sp.to != pos && nextChange > sp.to) {
- nextChange = sp.to;
- spanEndStyle = "";
- }
- if (m.className) { spanStyle += " " + m.className; }
- if (m.css) { css = (css ? css + ";" : "") + m.css; }
- if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
- if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
- if (m.title && !title) { title = m.title; }
- if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
- { collapsed = sp; }
- } else if (sp.from > pos && nextChange > sp.from) {
- nextChange = sp.from;
- }
- }
- if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
- { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
+ if (op.updatedDisplay || op.selectionChanged)
+ { op.preparedSelection = display.input.prepareSelection(); }
+ }
- if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
- { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
- if (collapsed && (collapsed.from || 0) == pos) {
- buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
- collapsed.marker, collapsed.from == null);
- if (collapsed.to == null) { return }
- if (collapsed.to == pos) { collapsed = false; }
- }
- }
- if (pos >= len) { break }
+ function endOperation_W2(op) {
+ var cm = op.cm;
- var upto = Math.min(len, nextChange);
- while (true) {
- if (text) {
- var end = pos + text.length;
- if (!collapsed) {
- var tokenText = end > upto ? text.slice(0, upto - pos) : text;
- builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
- spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
- }
- if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
- pos = end;
- spanStartStyle = "";
- }
- text = allText.slice(at, at = styles[i++]);
- style = interpretTokenStyle(styles[i++], builder.cm.options);
- }
+ if (op.adjustWidthTo != null) {
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
+ { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
+ cm.display.maxLineChanged = false;
}
- }
+ var takeFocus = op.focus && op.focus == activeElt();
+ if (op.preparedSelection)
+ { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
+ { updateScrollbars(cm, op.barMeasure); }
+ if (op.updatedDisplay)
+ { setDocumentHeight(cm, op.barMeasure); }
- // These objects are used to represent the visible (currently drawn)
- // part of the document. A LineView may correspond to multiple
- // logical lines, if those are connected by collapsed ranges.
- function LineView(doc, line, lineN) {
- // The starting line
- this.line = line;
- // Continuing lines, if any
- this.rest = visualLineContinued(line);
- // Number of logical lines in this visual line
- this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
- this.node = this.text = null;
- this.hidden = lineIsHidden(doc, line);
- }
+ if (op.selectionChanged) { restartBlink(cm); }
- // Create a range of LineView objects for the given lines.
- function buildViewArray(cm, from, to) {
- var array = [], nextPos;
- for (var pos = from; pos < to; pos = nextPos) {
- var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
- nextPos = pos + view.size;
- array.push(view);
- }
- return array
+ if (cm.state.focused && op.updateInput)
+ { cm.display.input.reset(op.typing); }
+ if (takeFocus) { ensureFocus(op.cm); }
}
- var operationGroup = null;
+ function endOperation_finish(op) {
+ var cm = op.cm, display = cm.display, doc = cm.doc;
- function pushOperation(op) {
- if (operationGroup) {
- operationGroup.ops.push(op);
- } else {
- op.ownsGroup = operationGroup = {
- ops: [op],
- delayedCallbacks: []
- };
- }
- }
+ if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
- function fireCallbacksForOps(group) {
- // Calls delayed callbacks and cursorActivity handlers until no
- // new ones appear
- var callbacks = group.delayedCallbacks, i = 0;
- do {
- for (; i < callbacks.length; i++)
- { callbacks[i].call(null); }
- for (var j = 0; j < group.ops.length; j++) {
- var op = group.ops[j];
- if (op.cursorActivityHandlers)
- { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
- { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
- }
- } while (i < callbacks.length)
- }
+ // Abort mouse wheel delta measurement, when scrolling explicitly
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
+ { display.wheelStartX = display.wheelStartY = null; }
- function finishOperation(op, endCb) {
- var group = op.ownsGroup;
- if (!group) { return }
+ // Propagate the scroll position to the actual DOM scroller
+ if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
- try { fireCallbacksForOps(group); }
- finally {
- operationGroup = null;
- endCb(group);
+ if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
+ // If we need to scroll a specific position into view, do so.
+ if (op.scrollToPos) {
+ var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
+ maybeScrollWindow(cm, rect);
}
- }
- var orphanDelayedCallbacks = null;
+ // Fire events for markers that are hidden/unidden by editing or
+ // undoing
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
+ if (hidden) { for (var i = 0; i < hidden.length; ++i)
+ { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
+ if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
+ { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
- // Often, we want to signal events at a point where we are in the
- // middle of some work, but don't want the handler to start calling
- // other methods on the editor, which might be in an inconsistent
- // state or simply not expect any other events to happen.
- // signalLater looks whether there are any handlers, and schedules
- // them to be executed when the last operation ends, or, if no
- // operation is active, when a timeout fires.
- function signalLater(emitter, type /*, values...*/) {
- var arr = getHandlers(emitter, type);
- if (!arr.length) { return }
- var args = Array.prototype.slice.call(arguments, 2), list;
- if (operationGroup) {
- list = operationGroup.delayedCallbacks;
- } else if (orphanDelayedCallbacks) {
- list = orphanDelayedCallbacks;
- } else {
- list = orphanDelayedCallbacks = [];
- setTimeout(fireOrphanDelayed, 0);
- }
- var loop = function ( i ) {
- list.push(function () { return arr[i].apply(null, args); });
- };
+ if (display.wrapper.offsetHeight)
+ { doc.scrollTop = cm.display.scroller.scrollTop; }
- for (var i = 0; i < arr.length; ++i)
- loop( i );
+ // Fire change events, and delayed event handlers
+ if (op.changeObjs)
+ { signal(cm, "changes", cm, op.changeObjs); }
+ if (op.update)
+ { op.update.finish(); }
}
- function fireOrphanDelayed() {
- var delayed = orphanDelayedCallbacks;
- orphanDelayedCallbacks = null;
- for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
+ // Run the given function in an operation
+ function runInOp(cm, f) {
+ if (cm.curOp) { return f() }
+ startOperation(cm);
+ try { return f() }
+ finally { endOperation(cm); }
}
-
- // When an aspect of a line changes, a string is added to
- // lineView.changes. This updates the relevant part of the line's
- // DOM structure.
- function updateLineForChanges(cm, lineView, lineN, dims) {
- for (var j = 0; j < lineView.changes.length; j++) {
- var type = lineView.changes[j];
- if (type == "text") { updateLineText(cm, lineView); }
- else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
- else if (type == "class") { updateLineClasses(cm, lineView); }
- else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
+ // Wraps a function in an operation. Returns the wrapped function.
+ function operation(cm, f) {
+ return function() {
+ if (cm.curOp) { return f.apply(cm, arguments) }
+ startOperation(cm);
+ try { return f.apply(cm, arguments) }
+ finally { endOperation(cm); }
}
- lineView.changes = null;
}
-
- // Lines with gutter elements, widgets or a background class need to
- // be wrapped, and have the extra elements added to the wrapper div
- function ensureLineWrapped(lineView) {
- if (lineView.node == lineView.text) {
- lineView.node = elt("div", null, null, "position: relative");
- if (lineView.text.parentNode)
- { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
- lineView.node.appendChild(lineView.text);
- if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
+ // Used to add methods to editor and doc instances, wrapping them in
+ // operations.
+ function methodOp(f) {
+ return function() {
+ if (this.curOp) { return f.apply(this, arguments) }
+ startOperation(this);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(this); }
}
- return lineView.node
}
-
- function updateLineBackground(cm, lineView) {
- var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
- if (cls) { cls += " CodeMirror-linebackground"; }
- if (lineView.background) {
- if (cls) { lineView.background.className = cls; }
- else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
- } else if (cls) {
- var wrap = ensureLineWrapped(lineView);
- lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
- cm.display.input.setUneditable(lineView.background);
+ function docMethodOp(f) {
+ return function() {
+ var cm = this.cm;
+ if (!cm || cm.curOp) { return f.apply(this, arguments) }
+ startOperation(cm);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(cm); }
}
}
- // Wrapper around buildLineContent which will reuse the structure
- // in display.externalMeasured when possible.
- function getLineContent(cm, lineView) {
- var ext = cm.display.externalMeasured;
- if (ext && ext.line == lineView.line) {
- cm.display.externalMeasured = null;
- lineView.measure = ext.measure;
- return ext.built
- }
- return buildLineContent(cm, lineView)
- }
+ // Updates the display.view data structure for a given change to the
+ // document. From and to are in pre-change coordinates. Lendiff is
+ // the amount of lines added or subtracted by the change. This is
+ // used for changes that span multiple lines, or change the way
+ // lines are divided into visual lines. regLineChange (below)
+ // registers single-line changes.
+ function regChange(cm, from, to, lendiff) {
+ if (from == null) { from = cm.doc.first; }
+ if (to == null) { to = cm.doc.first + cm.doc.size; }
+ if (!lendiff) { lendiff = 0; }
- // Redraw the line's text. Interacts with the background and text
- // classes because the mode may output tokens that influence these
- // classes.
- function updateLineText(cm, lineView) {
- var cls = lineView.text.className;
- var built = getLineContent(cm, lineView);
- if (lineView.text == lineView.node) { lineView.node = built.pre; }
- lineView.text.parentNode.replaceChild(built.pre, lineView.text);
- lineView.text = built.pre;
- if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
- lineView.bgClass = built.bgClass;
- lineView.textClass = built.textClass;
- updateLineClasses(cm, lineView);
- } else if (cls) {
- lineView.text.className = cls;
+ var display = cm.display;
+ if (lendiff && to < display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
+ { display.updateLineNumbers = from; }
+
+ cm.curOp.viewChanged = true;
+
+ if (from >= display.viewTo) { // Change after
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
+ { resetView(cm); }
+ } else if (to <= display.viewFrom) { // Change before
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
+ resetView(cm);
+ } else {
+ display.viewFrom += lendiff;
+ display.viewTo += lendiff;
+ }
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
+ resetView(cm);
+ } else if (from <= display.viewFrom) { // Top overlap
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cut) {
+ display.view = display.view.slice(cut.index);
+ display.viewFrom = cut.lineN;
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ } else if (to >= display.viewTo) { // Bottom overlap
+ var cut$1 = viewCuttingPoint(cm, from, from, -1);
+ if (cut$1) {
+ display.view = display.view.slice(0, cut$1.index);
+ display.viewTo = cut$1.lineN;
+ } else {
+ resetView(cm);
+ }
+ } else { // Gap in the middle
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cutTop && cutBot) {
+ display.view = display.view.slice(0, cutTop.index)
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
+ .concat(display.view.slice(cutBot.index));
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
}
- }
- function updateLineClasses(cm, lineView) {
- updateLineBackground(cm, lineView);
- if (lineView.line.wrapClass)
- { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
- else if (lineView.node != lineView.text)
- { lineView.node.className = ""; }
- var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
- lineView.text.className = textClass || "";
+ var ext = display.externalMeasured;
+ if (ext) {
+ if (to < ext.lineN)
+ { ext.lineN += lendiff; }
+ else if (from < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
+ }
}
- function updateLineGutter(cm, lineView, lineN, dims) {
- if (lineView.gutter) {
- lineView.node.removeChild(lineView.gutter);
- lineView.gutter = null;
- }
- if (lineView.gutterBackground) {
- lineView.node.removeChild(lineView.gutterBackground);
- lineView.gutterBackground = null;
- }
- if (lineView.line.gutterClass) {
- var wrap = ensureLineWrapped(lineView);
- lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
- ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
- cm.display.input.setUneditable(lineView.gutterBackground);
- wrap.insertBefore(lineView.gutterBackground, lineView.text);
- }
- var markers = lineView.line.gutterMarkers;
- if (cm.options.lineNumbers || markers) {
- var wrap$1 = ensureLineWrapped(lineView);
- var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
- cm.display.input.setUneditable(gutterWrap);
- wrap$1.insertBefore(gutterWrap, lineView.text);
- if (lineView.line.gutterClass)
- { gutterWrap.className += " " + lineView.line.gutterClass; }
- if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
- { lineView.lineNumber = gutterWrap.appendChild(
- elt("div", lineNumberFor(cm.options, lineN),
- "CodeMirror-linenumber CodeMirror-gutter-elt",
- ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
- if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
- var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
- if (found)
- { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
- ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
- } }
- }
- }
-
- function updateLineWidgets(cm, lineView, dims) {
- if (lineView.alignable) { lineView.alignable = null; }
- for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
- next = node.nextSibling;
- if (node.className == "CodeMirror-linewidget")
- { lineView.node.removeChild(node); }
- }
- insertLineWidgets(cm, lineView, dims);
- }
-
- // Build a line's DOM representation from scratch
- function buildLineElement(cm, lineView, lineN, dims) {
- var built = getLineContent(cm, lineView);
- lineView.text = lineView.node = built.pre;
- if (built.bgClass) { lineView.bgClass = built.bgClass; }
- if (built.textClass) { lineView.textClass = built.textClass; }
-
- updateLineClasses(cm, lineView);
- updateLineGutter(cm, lineView, lineN, dims);
- insertLineWidgets(cm, lineView, dims);
- return lineView.node
- }
+ // Register a change to a single line. Type must be one of "text",
+ // "gutter", "class", "widget"
+ function regLineChange(cm, line, type) {
+ cm.curOp.viewChanged = true;
+ var display = cm.display, ext = cm.display.externalMeasured;
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
- // A lineView may contain multiple logical lines (when merged by
- // collapsed spans). The widgets for all of them need to be drawn.
- function insertLineWidgets(cm, lineView, dims) {
- insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
- if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
- { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
+ if (line < display.viewFrom || line >= display.viewTo) { return }
+ var lineView = display.view[findViewIndex(cm, line)];
+ if (lineView.node == null) { return }
+ var arr = lineView.changes || (lineView.changes = []);
+ if (indexOf(arr, type) == -1) { arr.push(type); }
}
- function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
- if (!line.widgets) { return }
- var wrap = ensureLineWrapped(lineView);
- for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
- var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
- if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
- positionLineWidget(widget, node, lineView, dims);
- cm.display.input.setUneditable(node);
- if (allowAbove && widget.above)
- { wrap.insertBefore(node, lineView.gutter || lineView.text); }
- else
- { wrap.appendChild(node); }
- signalLater(widget, "redraw");
- }
+ // Clear the view.
+ function resetView(cm) {
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
+ cm.display.view = [];
+ cm.display.viewOffset = 0;
}
- function positionLineWidget(widget, node, lineView, dims) {
- if (widget.noHScroll) {
- (lineView.alignable || (lineView.alignable = [])).push(node);
- var width = dims.wrapperWidth;
- node.style.left = dims.fixedPos + "px";
- if (!widget.coverGutter) {
- width -= dims.gutterTotalWidth;
- node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ function viewCuttingPoint(cm, oldN, newN, dir) {
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
+ { return {index: index, lineN: newN} }
+ var n = cm.display.viewFrom;
+ for (var i = 0; i < index; i++)
+ { n += view[i].size; }
+ if (n != oldN) {
+ if (dir > 0) {
+ if (index == view.length - 1) { return null }
+ diff = (n + view[index].size) - oldN;
+ index++;
+ } else {
+ diff = n - oldN;
}
- node.style.width = width + "px";
+ oldN += diff; newN += diff;
}
- if (widget.coverGutter) {
- node.style.zIndex = 5;
- node.style.position = "relative";
- if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
+ while (visualLineNo(cm.doc, newN) != newN) {
+ if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
+ index += dir;
}
+ return {index: index, lineN: newN}
}
- function widgetHeight(widget) {
- if (widget.height != null) { return widget.height }
- var cm = widget.doc.cm;
- if (!cm) { return 0 }
- if (!contains(document.body, widget.node)) {
- var parentStyle = "position: relative;";
- if (widget.coverGutter)
- { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
- if (widget.noHScroll)
- { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
- removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ // Force the view to cover a given range, adding empty view element
+ // or clipping off existing ones as needed.
+ function adjustView(cm, from, to) {
+ var display = cm.display, view = display.view;
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
+ display.view = buildViewArray(cm, from, to);
+ display.viewFrom = from;
+ } else {
+ if (display.viewFrom > from)
+ { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
+ else if (display.viewFrom < from)
+ { display.view = display.view.slice(findViewIndex(cm, from)); }
+ display.viewFrom = from;
+ if (display.viewTo < to)
+ { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
+ else if (display.viewTo > to)
+ { display.view = display.view.slice(0, findViewIndex(cm, to)); }
}
- return widget.height = widget.node.parentNode.offsetHeight
+ display.viewTo = to;
}
- // Return true when the given mouse event happened in a widget
- function eventInWidget(display, e) {
- for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
- if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
- (n.parentNode == display.sizer && n != display.mover))
- { return true }
+ // Count the number of lines in the view whose DOM representation is
+ // out of date (or nonexistent).
+ function countDirtyView(cm) {
+ var view = cm.display.view, dirty = 0;
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
}
+ return dirty
}
- // POSITION MEASUREMENT
+ // HIGHLIGHT WORKER
- function paddingTop(display) {return display.lineSpace.offsetTop}
- function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
- function paddingH(display) {
- if (display.cachedPaddingH) { return display.cachedPaddingH }
- var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
- var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
- var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
- if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
- return data
+ function startWorker(cm, time) {
+ if (cm.doc.highlightFrontier < cm.display.viewTo)
+ { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
}
- function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
- function displayWidth(cm) {
- return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
- }
- function displayHeight(cm) {
- return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
- }
+ function highlightWorker(cm) {
+ var doc = cm.doc;
+ if (doc.highlightFrontier >= cm.display.viewTo) { return }
+ var end = +new Date + cm.options.workTime;
+ var context = getContextBefore(cm, doc.highlightFrontier);
+ var changedLines = [];
- // Ensure the lineView.wrapping.heights array is populated. This is
- // an array of bottom offsets for the lines that make up a drawn
- // line. When lineWrapping is on, there might be more than one
- // height.
- function ensureLineHeights(cm, lineView, rect) {
- var wrapping = cm.options.lineWrapping;
- var curWidth = wrapping && displayWidth(cm);
- if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
- var heights = lineView.measure.heights = [];
- if (wrapping) {
- lineView.measure.width = curWidth;
- var rects = lineView.text.firstChild.getClientRects();
- for (var i = 0; i < rects.length - 1; i++) {
- var cur = rects[i], next = rects[i + 1];
- if (Math.abs(cur.bottom - next.bottom) > 2)
- { heights.push((cur.bottom + next.top) / 2 - rect.top); }
- }
+ doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
+ if (context.line >= cm.display.viewFrom) { // Visible
+ var oldStyles = line.styles;
+ var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
+ var highlighted = highlightLine(cm, line, context, true);
+ if (resetState) { context.state = resetState; }
+ line.styles = highlighted.styles;
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
+ if (newCls) { line.styleClasses = newCls; }
+ else if (oldCls) { line.styleClasses = null; }
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
+ if (ischange) { changedLines.push(context.line); }
+ line.stateAfter = context.save();
+ context.nextLine();
+ } else {
+ if (line.text.length <= cm.options.maxHighlightLength)
+ { processLine(cm, line.text, context); }
+ line.stateAfter = context.line % 5 == 0 ? context.save() : null;
+ context.nextLine();
}
- heights.push(rect.bottom - rect.top);
- }
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true
+ }
+ });
+ doc.highlightFrontier = context.line;
+ doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
+ if (changedLines.length) { runInOp(cm, function () {
+ for (var i = 0; i < changedLines.length; i++)
+ { regLineChange(cm, changedLines[i], "text"); }
+ }); }
}
- // Find a line map (mapping character offsets to text nodes) and a
- // measurement cache for the given line number. (A line view might
- // contain multiple lines when collapsed ranges are present.)
- function mapFromLineView(lineView, line, lineN) {
- if (lineView.line == line)
- { return {map: lineView.measure.map, cache: lineView.measure.cache} }
- for (var i = 0; i < lineView.rest.length; i++)
- { if (lineView.rest[i] == line)
- { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
- for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
- { if (lineNo(lineView.rest[i$1]) > lineN)
- { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
- }
+ // DISPLAY DRAWING
- // Render a line into the hidden node display.externalMeasured. Used
- // when measurement is needed for a line that's not in the viewport.
- function updateExternalMeasurement(cm, line) {
- line = visualLine(line);
- var lineN = lineNo(line);
- var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
- view.lineN = lineN;
- var built = view.built = buildLineContent(cm, view);
- view.text = built.pre;
- removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
- return view
- }
+ var DisplayUpdate = function(cm, viewport, force) {
+ var display = cm.display;
- // Get a {top, bottom, left, right} box (in line-local coordinates)
- // for a given character.
- function measureChar(cm, line, ch, bias) {
- return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
- }
+ this.viewport = viewport;
+ // Store some values that we'll need later (but don't want to force a relayout for)
+ this.visible = visibleLines(display, cm.doc, viewport);
+ this.editorIsHidden = !display.wrapper.offsetWidth;
+ this.wrapperHeight = display.wrapper.clientHeight;
+ this.wrapperWidth = display.wrapper.clientWidth;
+ this.oldDisplayWidth = displayWidth(cm);
+ this.force = force;
+ this.dims = getDimensions(cm);
+ this.events = [];
+ };
- // Find a line view that corresponds to the given line number.
- function findViewForLine(cm, lineN) {
- if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
- { return cm.display.view[findViewIndex(cm, lineN)] }
- var ext = cm.display.externalMeasured;
- if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
- { return ext }
- }
+ DisplayUpdate.prototype.signal = function (emitter, type) {
+ if (hasHandler(emitter, type))
+ { this.events.push(arguments); }
+ };
+ DisplayUpdate.prototype.finish = function () {
+ var this$1 = this;
- // Measurement can be split in two steps, the set-up work that
- // applies to the whole line, and the measurement of the actual
- // character. Functions like coordsChar, that need to do a lot of
- // measurements in a row, can thus ensure that the set-up work is
- // only done once.
- function prepareMeasureForLine(cm, line) {
- var lineN = lineNo(line);
- var view = findViewForLine(cm, lineN);
- if (view && !view.text) {
- view = null;
- } else if (view && view.changes) {
- updateLineForChanges(cm, view, lineN, getDimensions(cm));
- cm.curOp.forceUpdate = true;
- }
- if (!view)
- { view = updateExternalMeasurement(cm, line); }
+ for (var i = 0; i < this.events.length; i++)
+ { signal.apply(null, this$1.events[i]); }
+ };
- var info = mapFromLineView(view, line, lineN);
- return {
- line: line, view: view, rect: null,
- map: info.map, cache: info.cache, before: info.before,
- hasHeights: false
+ function maybeClipScrollbars(cm) {
+ var display = cm.display;
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
+ display.heightForcer.style.height = scrollGap(cm) + "px";
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
+ display.scrollbarsClipped = true;
}
}
- // Given a prepared measurement object, measures the position of an
- // actual character (or fetches it from the cache).
- function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
- if (prepared.before) { ch = -1; }
- var key = ch + (bias || ""), found;
- if (prepared.cache.hasOwnProperty(key)) {
- found = prepared.cache[key];
- } else {
- if (!prepared.rect)
- { prepared.rect = prepared.view.text.getBoundingClientRect(); }
- if (!prepared.hasHeights) {
- ensureLineHeights(cm, prepared.view, prepared.rect);
- prepared.hasHeights = true;
+ function selectionSnapshot(cm) {
+ if (cm.hasFocus()) { return null }
+ var active = activeElt();
+ if (!active || !contains(cm.display.lineDiv, active)) { return null }
+ var result = {activeElt: active};
+ if (window.getSelection) {
+ var sel = window.getSelection();
+ if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
+ result.anchorNode = sel.anchorNode;
+ result.anchorOffset = sel.anchorOffset;
+ result.focusNode = sel.focusNode;
+ result.focusOffset = sel.focusOffset;
}
- found = measureCharInner(cm, prepared, ch, bias);
- if (!found.bogus) { prepared.cache[key] = found; }
}
- return {left: found.left, right: found.right,
- top: varHeight ? found.rtop : found.top,
- bottom: varHeight ? found.rbottom : found.bottom}
+ return result
}
- var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
-
- function nodeAndOffsetInLineMap(map$$1, ch, bias) {
- var node, start, end, collapse, mStart, mEnd;
- // First, search the line map for the text node corresponding to,
- // or closest to, the target character.
- for (var i = 0; i < map$$1.length; i += 3) {
- mStart = map$$1[i];
- mEnd = map$$1[i + 1];
- if (ch < mStart) {
- start = 0; end = 1;
- collapse = "left";
- } else if (ch < mEnd) {
- start = ch - mStart;
- end = start + 1;
- } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
- end = mEnd - mStart;
- start = end - 1;
- if (ch >= mEnd) { collapse = "right"; }
- }
- if (start != null) {
- node = map$$1[i + 2];
- if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
- { collapse = bias; }
- if (bias == "left" && start == 0)
- { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
- node = map$$1[(i -= 3) + 2];
- collapse = "left";
- } }
- if (bias == "right" && start == mEnd - mStart)
- { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
- node = map$$1[(i += 3) + 2];
- collapse = "right";
- } }
- break
- }
+ function restoreSelection(snapshot) {
+ if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
+ snapshot.activeElt.focus();
+ if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
+ var sel = window.getSelection(), range$$1 = document.createRange();
+ range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
+ range$$1.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range$$1);
+ sel.extend(snapshot.focusNode, snapshot.focusOffset);
}
- return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
}
- function getUsefulRect(rects, bias) {
- var rect = nullRect;
- if (bias == "left") { for (var i = 0; i < rects.length; i++) {
- if ((rect = rects[i]).left != rect.right) { break }
- } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
- if ((rect = rects[i$1]).left != rect.right) { break }
- } }
- return rect
- }
+ // Does the actual updating of the line display. Bails out
+ // (returning false) when there is nothing to be done and forced is
+ // false.
+ function updateDisplayIfNeeded(cm, update) {
+ var display = cm.display, doc = cm.doc;
- function measureCharInner(cm, prepared, ch, bias) {
- var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
- var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
+ if (update.editorIsHidden) {
+ resetView(cm);
+ return false
+ }
- var rect;
- if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
- for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
- while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
- while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
- if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
- { rect = node.parentNode.getBoundingClientRect(); }
- else
- { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
- if (rect.left || rect.right || start == 0) { break }
- end = start;
- start = start - 1;
- collapse = "right";
- }
- if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
- } else { // If it is a widget, simply get the box for the whole widget.
- if (start > 0) { collapse = bias = "right"; }
- var rects;
- if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
- { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
- else
- { rect = node.getBoundingClientRect(); }
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (!update.force &&
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
+ display.renderedView == display.view && countDirtyView(cm) == 0)
+ { return false }
+
+ if (maybeUpdateLineNumberWidth(cm)) {
+ resetView(cm);
+ update.dims = getDimensions(cm);
}
- if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
- var rSpan = node.parentNode.getClientRects()[0];
- if (rSpan)
- { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
- else
- { rect = nullRect; }
+
+ // Compute a suitable new viewport (from & to)
+ var end = doc.first + doc.size;
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
+ if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
+ if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
+ if (sawCollapsedSpans) {
+ from = visualLineNo(cm.doc, from);
+ to = visualLineEndNo(cm.doc, to);
}
- var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
- var mid = (rtop + rbot) / 2;
- var heights = prepared.view.measure.heights;
- var i = 0;
- for (; i < heights.length - 1; i++)
- { if (mid < heights[i]) { break } }
- var top = i ? heights[i - 1] : 0, bot = heights[i];
- var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
- right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
- top: top, bottom: bot};
- if (!rect.left && !rect.right) { result.bogus = true; }
- if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
+ var different = from != display.viewFrom || to != display.viewTo ||
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
+ adjustView(cm, from, to);
- return result
- }
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
+ // Position the mover div to align with the current scroll position
+ cm.display.mover.style.top = display.viewOffset + "px";
- // Work around problem with bounding client rects on ranges being
- // returned incorrectly when zoomed on IE10 and below.
- function maybeUpdateRectForZooming(measure, rect) {
- if (!window.screen || screen.logicalXDPI == null ||
- screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
- { return rect }
- var scaleX = screen.logicalXDPI / screen.deviceXDPI;
- var scaleY = screen.logicalYDPI / screen.deviceYDPI;
- return {left: rect.left * scaleX, right: rect.right * scaleX,
- top: rect.top * scaleY, bottom: rect.bottom * scaleY}
- }
+ var toUpdate = countDirtyView(cm);
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
+ { return false }
- function clearLineMeasurementCacheFor(lineView) {
- if (lineView.measure) {
- lineView.measure.cache = {};
- lineView.measure.heights = null;
- if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
- { lineView.measure.caches[i] = {}; } }
- }
- }
+ // For big changes, we hide the enclosing element during the
+ // update, since that speeds up the operations on most browsers.
+ var selSnapshot = selectionSnapshot(cm);
+ if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
+ if (toUpdate > 4) { display.lineDiv.style.display = ""; }
+ display.renderedView = display.view;
+ // There might have been a widget with a focused element that got
+ // hidden or updated, if so re-focus it.
+ restoreSelection(selSnapshot);
- function clearLineMeasurementCache(cm) {
- cm.display.externalMeasure = null;
- removeChildren(cm.display.lineMeasure);
- for (var i = 0; i < cm.display.view.length; i++)
- { clearLineMeasurementCacheFor(cm.display.view[i]); }
- }
+ // Prevent selection and cursors from interfering with the scroll
+ // width and height.
+ removeChildren(display.cursorDiv);
+ removeChildren(display.selectionDiv);
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
- function clearCaches(cm) {
- clearLineMeasurementCache(cm);
- cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
- if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
- cm.display.lineNumChars = null;
- }
-
- function pageScrollX() {
- // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
- // which causes page_Offset and bounding client rects to use
- // different reference viewports and invalidate our calculations.
- if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
- return window.pageXOffset || (document.documentElement || document.body).scrollLeft
- }
- function pageScrollY() {
- if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
- return window.pageYOffset || (document.documentElement || document.body).scrollTop
- }
-
- // Converts a {top, bottom, left, right} box from line-local
- // coordinates into another coordinate system. Context may be one of
- // "line", "div" (display.lineDiv), "local"./null (editor), "window",
- // or "page".
- function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
- if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
- var size = widgetHeight(lineObj.widgets[i]);
- rect.top += size; rect.bottom += size;
- } } }
- if (context == "line") { return rect }
- if (!context) { context = "local"; }
- var yOff = heightAtLine(lineObj);
- if (context == "local") { yOff += paddingTop(cm.display); }
- else { yOff -= cm.display.viewOffset; }
- if (context == "page" || context == "window") {
- var lOff = cm.display.lineSpace.getBoundingClientRect();
- yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
- var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
- rect.left += xOff; rect.right += xOff;
+ if (different) {
+ display.lastWrapHeight = update.wrapperHeight;
+ display.lastWrapWidth = update.wrapperWidth;
+ startWorker(cm, 400);
}
- rect.top += yOff; rect.bottom += yOff;
- return rect
- }
- // Coverts a box from "div" coords to another coordinate system.
- // Context may be "window", "page", "div", or "local"./null.
- function fromCoordSystem(cm, coords, context) {
- if (context == "div") { return coords }
- var left = coords.left, top = coords.top;
- // First move into "page" coordinate system
- if (context == "page") {
- left -= pageScrollX();
- top -= pageScrollY();
- } else if (context == "local" || !context) {
- var localBox = cm.display.sizer.getBoundingClientRect();
- left += localBox.left;
- top += localBox.top;
- }
+ display.updateLineNumbers = null;
- var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
- return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
+ return true
}
- function charCoords(cm, pos, context, lineObj, bias) {
- if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
- return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
- }
+ function postUpdateDisplay(cm, update) {
+ var viewport = update.viewport;
- // Returns a box for a given cursor position, which may have an
- // 'other' property containing the position of the secondary cursor
- // on a bidi boundary.
- // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
- // and after `char - 1` in writing order of `char - 1`
- // A cursor Pos(line, char, "after") is on the same visual line as `char`
- // and before `char` in writing order of `char`
- // Examples (upper-case letters are RTL, lower-case are LTR):
- // Pos(0, 1, ...)
- // before after
- // ab a|b a|b
- // aB a|B aB|
- // Ab |Ab A|b
- // AB B|A B|A
- // Every position after the last character on a line is considered to stick
- // to the last character on the line.
- function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
- lineObj = lineObj || getLine(cm.doc, pos.line);
- if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
- function get(ch, right) {
- var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
- if (right) { m.left = m.right; } else { m.right = m.left; }
- return intoCoordSystem(cm, lineObj, m, context)
- }
- var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
- if (ch >= lineObj.text.length) {
- ch = lineObj.text.length;
- sticky = "before";
- } else if (ch <= 0) {
- ch = 0;
- sticky = "after";
+ for (var first = true;; first = false) {
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
+ // Clip forced viewport to actual scrollable area.
+ if (viewport && viewport.top != null)
+ { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
+ // Updated line heights might result in the drawn area not
+ // actually covering the viewport. Keep looping until it does.
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
+ { break }
+ }
+ if (!updateDisplayIfNeeded(cm, update)) { break }
+ updateHeightsInViewport(cm);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.force = false;
}
- if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
- function getBidi(ch, partPos, invert) {
- var part = order[partPos], right = (part.level % 2) != 0;
- return get(invert ? ch - 1 : ch, right != invert)
+ update.signal(cm, "update", cm);
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
}
- var partPos = getBidiPartAt(order, ch, sticky);
- var other = bidiOther;
- var val = getBidi(ch, partPos, sticky == "before");
- if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
- return val
- }
-
- // Used to cheaply estimate the coordinates for a position. Used for
- // intermediate scroll updates.
- function estimateCoords(cm, pos) {
- var left = 0;
- pos = clipPos(cm.doc, pos);
- if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
- var lineObj = getLine(cm.doc, pos.line);
- var top = heightAtLine(lineObj) + paddingTop(cm.display);
- return {left: left, right: left, top: top, bottom: top + lineObj.height}
}
- // Positions returned by coordsChar contain some extra information.
- // xRel is the relative x position of the input coordinates compared
- // to the found position (so xRel > 0 means the coordinates are to
- // the right of the character position, for example). When outside
- // is true, that means the coordinates lie outside the line's
- // vertical range.
- function PosWithInfo(line, ch, sticky, outside, xRel) {
- var pos = Pos(line, ch, sticky);
- pos.xRel = xRel;
- if (outside) { pos.outside = true; }
- return pos
+ function updateDisplaySimple(cm, viewport) {
+ var update = new DisplayUpdate(cm, viewport);
+ if (updateDisplayIfNeeded(cm, update)) {
+ updateHeightsInViewport(cm);
+ postUpdateDisplay(cm, update);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.finish();
+ }
}
- // Compute the character position closest to the given coordinates.
- // Input must be lineSpace-local ("div" coordinate system).
- function coordsChar(cm, x, y) {
- var doc = cm.doc;
- y += cm.display.viewOffset;
- if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
- var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
- if (lineN > last)
- { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
- if (x < 0) { x = 0; }
+ // Sync the actual display DOM structure with display.view, removing
+ // nodes for lines that are no longer in view, and creating the ones
+ // that are not there yet, and updating the ones that are out of
+ // date.
+ function patchDisplay(cm, updateNumbersFrom, dims) {
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
+ var container = display.lineDiv, cur = container.firstChild;
- var lineObj = getLine(doc, lineN);
- for (;;) {
- var found = coordsCharInner(cm, lineObj, lineN, x, y);
- var merged = collapsedSpanAtEnd(lineObj);
- var mergedPos = merged && merged.find(0, true);
- if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
- { lineN = lineNo(lineObj = mergedPos.to.line); }
+ function rm(node) {
+ var next = node.nextSibling;
+ // Works around a throw-scroll bug in OS X Webkit
+ if (webkit && mac && cm.display.currentWheelTarget == node)
+ { node.style.display = "none"; }
else
- { return found }
+ { node.parentNode.removeChild(node); }
+ return next
}
- }
-
- function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
- var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); };
- var end = lineObj.text.length;
- var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0);
- end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end);
- return {begin: begin, end: end}
- }
-
- function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
- var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
- return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
- }
- function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
- y -= heightAtLine(lineObj);
- var begin = 0, end = lineObj.text.length;
- var preparedMeasure = prepareMeasureForLine(cm, lineObj);
- var pos;
- var order = getOrder(lineObj, cm.doc.direction);
- if (order) {
- if (cm.options.lineWrapping) {
- var assign;
- ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign));
- }
- pos = new Pos(lineNo$$1, begin);
- var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left;
- var dir = beginLeft < x ? 1 : -1;
- var prevDiff, diff = beginLeft - x, prevPos;
- do {
- prevDiff = diff;
- prevPos = pos;
- pos = moveVisually(cm, lineObj, pos, dir);
- if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) {
- pos = prevPos;
- break
+ var view = display.view, lineN = display.viewFrom;
+ // Loop over the elements in the view, syncing cur (the DOM nodes
+ // in display.lineDiv) with the view as we go.
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (lineView.hidden) {
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
+ var node = buildLineElement(cm, lineView, lineN, dims);
+ container.insertBefore(node, cur);
+ } else { // Already drawn
+ while (cur != lineView.node) { cur = rm(cur); }
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
+ updateNumbersFrom <= lineN && lineView.lineNumber;
+ if (lineView.changes) {
+ if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
+ updateLineForChanges(cm, lineView, lineN, dims);
}
- diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x;
- } while ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff)))
- if (Math.abs(diff) > Math.abs(prevDiff)) {
- if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") }
- pos = prevPos;
- }
- } else {
- var ch = findFirst(function (ch) {
- var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line");
- if (box.top > y) {
- // For the cursor stickiness
- end = Math.min(ch, end);
- return true
+ if (updateNumber) {
+ removeChildren(lineView.lineNumber);
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
}
- else if (box.bottom <= y) { return false }
- else if (box.left > x) { return true }
- else if (box.right < x) { return false }
- else { return (x - box.left < box.right - x) }
- }, begin, end);
- ch = skipExtendingChars(lineObj.text, ch, 1);
- pos = new Pos(lineNo$$1, ch, ch == end ? "before" : "after");
- }
- var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure);
- if (y < coords.top || coords.bottom < y) { pos.outside = true; }
- pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0);
- return pos
- }
-
- var measureText;
- // Compute the default text height.
- function textHeight(display) {
- if (display.cachedTextHeight != null) { return display.cachedTextHeight }
- if (measureText == null) {
- measureText = elt("pre");
- // Measure a bunch of lines, for browsers that compute
- // fractional heights.
- for (var i = 0; i < 49; ++i) {
- measureText.appendChild(document.createTextNode("x"));
- measureText.appendChild(elt("br"));
+ cur = lineView.node.nextSibling;
}
- measureText.appendChild(document.createTextNode("x"));
+ lineN += lineView.size;
}
- removeChildrenAndAdd(display.measure, measureText);
- var height = measureText.offsetHeight / 50;
- if (height > 3) { display.cachedTextHeight = height; }
- removeChildren(display.measure);
- return height || 1
+ while (cur) { cur = rm(cur); }
}
- // Compute the default character width.
- function charWidth(display) {
- if (display.cachedCharWidth != null) { return display.cachedCharWidth }
- var anchor = elt("span", "xxxxxxxxxx");
- var pre = elt("pre", [anchor]);
- removeChildrenAndAdd(display.measure, pre);
- var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
- if (width > 2) { display.cachedCharWidth = width; }
- return width || 10
+ function updateGutterSpace(cm) {
+ var width = cm.display.gutters.offsetWidth;
+ cm.display.sizer.style.marginLeft = width + "px";
}
- // Do a bulk-read of the DOM positions and sizes needed to draw the
- // view, so that we don't interleave reading and writing to the DOM.
- function getDimensions(cm) {
- var d = cm.display, left = {}, width = {};
- var gutterLeft = d.gutters.clientLeft;
- for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
- left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
- width[cm.options.gutters[i]] = n.clientWidth;
- }
- return {fixedPos: compensateForHScroll(d),
- gutterTotalWidth: d.gutters.offsetWidth,
- gutterLeft: left,
- gutterWidth: width,
- wrapperWidth: d.wrapper.clientWidth}
+ function setDocumentHeight(cm, measure) {
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
}
- // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
- // but using getBoundingClientRect to get a sub-pixel-accurate
- // result.
- function compensateForHScroll(display) {
- return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
+ // Rebuild the gutter elements, ensure the margin to the left of the
+ // code matches their width.
+ function updateGutters(cm) {
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
+ removeChildren(gutters);
+ var i = 0;
+ for (; i < specs.length; ++i) {
+ var gutterClass = specs[i];
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
+ if (gutterClass == "CodeMirror-linenumbers") {
+ cm.display.lineGutter = gElt;
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = i ? "" : "none";
+ updateGutterSpace(cm);
}
- // Returns a function that estimates the height of a line, to use as
- // first approximation until the line becomes visible (and is thus
- // properly measurable).
- function estimateHeight(cm) {
- var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
- var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
- return function (line) {
- if (lineIsHidden(cm.doc, line)) { return 0 }
-
- var widgetsHeight = 0;
- if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
- if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
- } }
-
- if (wrapping)
- { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
- else
- { return widgetsHeight + th }
+ // Make sure the gutters options contains the element
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
+ function setGuttersForLineNumbers(options) {
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
+ if (found == -1 && options.lineNumbers) {
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
+ } else if (found > -1 && !options.lineNumbers) {
+ options.gutters = options.gutters.slice(0);
+ options.gutters.splice(found, 1);
}
}
- function estimateLineHeights(cm) {
- var doc = cm.doc, est = estimateHeight(cm);
- doc.iter(function (line) {
- var estHeight = est(line);
- if (estHeight != line.height) { updateLineHeight(line, estHeight); }
- });
- }
+ // Since the delta values reported on mouse wheel events are
+ // unstandardized between browsers and even browser versions, and
+ // generally horribly unpredictable, this code starts by measuring
+ // the scroll effect that the first few mouse wheel events have,
+ // and, from that, detects the way it can convert deltas to pixel
+ // offsets afterwards.
+ //
+ // The reason we want to know the amount a wheel event will scroll
+ // is that it gives us a chance to update the display before the
+ // actual scrolling happens, reducing flickering.
- // Given a mouse event, find the corresponding position. If liberal
- // is false, it checks whether a gutter or scrollbar was clicked,
- // and returns null if it was. forRect is used by rectangular
- // selections, and tries to estimate a character position even for
- // coordinates beyond the right of the text.
- function posFromMouse(cm, e, liberal, forRect) {
- var display = cm.display;
- if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
+ var wheelSamples = 0;
+ var wheelPixelsPerUnit = null;
+ // Fill in a browser-detected starting value on browsers where we
+ // know one. These don't have to be accurate -- the result of them
+ // being wrong would just be a slight flicker on the first wheel
+ // scroll (if it is large enough).
+ if (ie) { wheelPixelsPerUnit = -.53; }
+ else if (gecko) { wheelPixelsPerUnit = 15; }
+ else if (chrome) { wheelPixelsPerUnit = -.7; }
+ else if (safari) { wheelPixelsPerUnit = -1/3; }
- var x, y, space = display.lineSpace.getBoundingClientRect();
- // Fails unpredictably on IE[67] when mouse is dragged around quickly.
- try { x = e.clientX - space.left; y = e.clientY - space.top; }
- catch (e) { return null }
- var coords = coordsChar(cm, x, y), line;
- if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
- var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
- coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
- }
- return coords
+ function wheelEventDelta(e) {
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
+ else if (dy == null) { dy = e.wheelDelta; }
+ return {x: dx, y: dy}
}
-
- // Find the view element corresponding to a given line. Return null
- // when the line isn't visible.
- function findViewIndex(cm, n) {
- if (n >= cm.display.viewTo) { return null }
- n -= cm.display.viewFrom;
- if (n < 0) { return null }
- var view = cm.display.view;
- for (var i = 0; i < view.length; i++) {
- n -= view[i].size;
- if (n < 0) { return i }
- }
+ function wheelEventPixels(e) {
+ var delta = wheelEventDelta(e);
+ delta.x *= wheelPixelsPerUnit;
+ delta.y *= wheelPixelsPerUnit;
+ return delta
}
- function updateSelection(cm) {
- cm.display.input.showSelection(cm.display.input.prepareSelection());
- }
+ function onScrollWheel(cm, e) {
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
- function prepareSelection(cm, primary) {
- var doc = cm.doc, result = {};
- var curFragment = result.cursors = document.createDocumentFragment();
- var selFragment = result.selection = document.createDocumentFragment();
+ var display = cm.display, scroll = display.scroller;
+ // Quit if there's nothing to scroll here
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
+ if (!(dx && canScrollX || dy && canScrollY)) { return }
- for (var i = 0; i < doc.sel.ranges.length; i++) {
- if (primary === false && i == doc.sel.primIndex) { continue }
- var range$$1 = doc.sel.ranges[i];
- if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
- var collapsed = range$$1.empty();
- if (collapsed || cm.options.showCursorWhenSelecting)
- { drawSelectionCursor(cm, range$$1.head, curFragment); }
- if (!collapsed)
- { drawSelectionRange(cm, range$$1, selFragment); }
+ // Webkit browsers on OS X abort momentum scrolls when the target
+ // of the scroll event is removed from the scrollable element.
+ // This hack (see related code in patchDisplay) makes sure the
+ // element is kept around.
+ if (dy && mac && webkit) {
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
+ for (var i = 0; i < view.length; i++) {
+ if (view[i].node == cur) {
+ cm.display.currentWheelTarget = cur;
+ break outer
+ }
+ }
+ }
}
- return result
- }
- // Draws a cursor for the given range
- function drawSelectionCursor(cm, head, output) {
- var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
+ // On some browsers, horizontal scrolling will cause redraws to
+ // happen before the gutter has been realigned, causing it to
+ // wriggle around in a most unseemly way. When we have an
+ // estimated pixels/delta value, we just handle horizontal
+ // scrolling entirely here. It'll be slightly off from native, but
+ // better than glitching out.
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
+ if (dy && canScrollY)
+ { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
+ setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
+ // Only prevent default scrolling if vertical scrolling is
+ // actually possible. Otherwise, it causes vertical scroll
+ // jitter on OSX trackpads when deltaX is small and deltaY
+ // is large (issue #3579)
+ if (!dy || (dy && canScrollY))
+ { e_preventDefault(e); }
+ display.wheelStartX = null; // Abort measurement, if in progress
+ return
+ }
- var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
- cursor.style.left = pos.left + "px";
- cursor.style.top = pos.top + "px";
- cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+ // 'Project' the visible viewport to cover the area that is being
+ // scrolled into view (if we know enough to estimate it).
+ if (dy && wheelPixelsPerUnit != null) {
+ var pixels = dy * wheelPixelsPerUnit;
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
+ if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
+ else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
+ updateDisplaySimple(cm, {top: top, bottom: bot});
+ }
- if (pos.other) {
- // Secondary cursor, shown when on a 'jump' in bi-directional text
- var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
- otherCursor.style.display = "";
- otherCursor.style.left = pos.other.left + "px";
- otherCursor.style.top = pos.other.top + "px";
- otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+ if (wheelSamples < 20) {
+ if (display.wheelStartX == null) {
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
+ display.wheelDX = dx; display.wheelDY = dy;
+ setTimeout(function () {
+ if (display.wheelStartX == null) { return }
+ var movedX = scroll.scrollLeft - display.wheelStartX;
+ var movedY = scroll.scrollTop - display.wheelStartY;
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
+ (movedX && display.wheelDX && movedX / display.wheelDX);
+ display.wheelStartX = display.wheelStartY = null;
+ if (!sample) { return }
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+ ++wheelSamples;
+ }, 200);
+ } else {
+ display.wheelDX += dx; display.wheelDY += dy;
+ }
}
}
- // Draws the given range as a highlighted selection
- function drawSelectionRange(cm, range$$1, output) {
- var display = cm.display, doc = cm.doc;
- var fragment = document.createDocumentFragment();
- var padding = paddingH(cm.display), leftSide = padding.left;
- var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
+ // Selection objects are immutable. A new one is created every time
+ // the selection changes. A selection is one or more non-overlapping
+ // (and non-touching) ranges, sorted, and an integer that indicates
+ // which one is the primary selection (the one that's scrolled into
+ // view, that getCursor returns, etc).
+ var Selection = function(ranges, primIndex) {
+ this.ranges = ranges;
+ this.primIndex = primIndex;
+ };
- function add(left, top, width, bottom) {
- if (top < 0) { top = 0; }
- top = Math.round(top);
- bottom = Math.round(bottom);
- fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
- }
+ Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
- function drawForLine(line, fromArg, toArg) {
- var lineObj = getLine(doc, line);
- var lineLen = lineObj.text.length;
- var start, end;
- function coords(ch, bias) {
- return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
- }
+ Selection.prototype.equals = function (other) {
+ var this$1 = this;
- iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
- var leftPos = coords(from, "left"), rightPos, left, right;
- if (from == to) {
- rightPos = leftPos;
- left = right = leftPos.left;
- } else {
- rightPos = coords(to - 1, "right");
- if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
- left = leftPos.left;
- right = rightPos.right;
- }
- if (fromArg == null && from == 0) { left = leftSide; }
- if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
- add(left, leftPos.top, null, leftPos.bottom);
- left = leftSide;
- if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top); }
- }
- if (toArg == null && to == lineLen) { right = rightSide; }
- if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
- { start = leftPos; }
- if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
- { end = rightPos; }
- if (left < leftSide + 1) { left = leftSide; }
- add(left, rightPos.top, right - left, rightPos.bottom);
- });
- return {start: start, end: end}
+ if (other == this) { return true }
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var here = this$1.ranges[i], there = other.ranges[i];
+ if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
}
+ return true
+ };
- var sFrom = range$$1.from(), sTo = range$$1.to();
- if (sFrom.line == sTo.line) {
- drawForLine(sFrom.line, sFrom.ch, sTo.ch);
- } else {
- var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
- var singleVLine = visualLine(fromLine) == visualLine(toLine);
- var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
- var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
- if (singleVLine) {
- if (leftEnd.top < rightStart.top - 2) {
- add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
- add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
- } else {
- add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
- }
- }
- if (leftEnd.bottom < rightStart.top)
- { add(leftSide, leftEnd.bottom, null, rightStart.top); }
- }
+ Selection.prototype.deepCopy = function () {
+ var this$1 = this;
- output.appendChild(fragment);
- }
+ var out = [];
+ for (var i = 0; i < this.ranges.length; i++)
+ { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
+ return new Selection(out, this.primIndex)
+ };
- // Cursor-blinking
- function restartBlink(cm) {
- if (!cm.state.focused) { return }
- var display = cm.display;
- clearInterval(display.blinker);
- var on = true;
- display.cursorDiv.style.visibility = "";
- if (cm.options.cursorBlinkRate > 0)
- { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
- cm.options.cursorBlinkRate); }
- else if (cm.options.cursorBlinkRate < 0)
- { display.cursorDiv.style.visibility = "hidden"; }
- }
+ Selection.prototype.somethingSelected = function () {
+ var this$1 = this;
- function ensureFocus(cm) {
- if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
- }
+ for (var i = 0; i < this.ranges.length; i++)
+ { if (!this$1.ranges[i].empty()) { return true } }
+ return false
+ };
- function delayBlurEvent(cm) {
- cm.state.delayingBlurEvent = true;
- setTimeout(function () { if (cm.state.delayingBlurEvent) {
- cm.state.delayingBlurEvent = false;
- onBlur(cm);
- } }, 100);
- }
+ Selection.prototype.contains = function (pos, end) {
+ var this$1 = this;
- function onFocus(cm, e) {
- if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
+ if (!end) { end = pos; }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var range = this$1.ranges[i];
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
+ { return i }
+ }
+ return -1
+ };
- if (cm.options.readOnly == "nocursor") { return }
- if (!cm.state.focused) {
- signal(cm, "focus", cm, e);
- cm.state.focused = true;
- addClass(cm.display.wrapper, "CodeMirror-focused");
- // This test prevents this from firing when a context
- // menu is closed (since the input reset would kill the
- // select-all detection hack)
- if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
- cm.display.input.reset();
- if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
+ var Range = function(anchor, head) {
+ this.anchor = anchor; this.head = head;
+ };
+
+ Range.prototype.from = function () { return minPos(this.anchor, this.head) };
+ Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
+ Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
+
+ // Take an unsorted, potentially overlapping set of ranges, and
+ // build a selection out of it. 'Consumes' ranges array (modifying
+ // it).
+ function normalizeSelection(ranges, primIndex) {
+ var prim = ranges[primIndex];
+ ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
+ primIndex = indexOf(ranges, prim);
+ for (var i = 1; i < ranges.length; i++) {
+ var cur = ranges[i], prev = ranges[i - 1];
+ if (cmp(prev.to(), cur.from()) >= 0) {
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
+ if (i <= primIndex) { --primIndex; }
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
}
- cm.display.input.receivedFocus();
}
- restartBlink(cm);
+ return new Selection(ranges, primIndex)
}
- function onBlur(cm, e) {
- if (cm.state.delayingBlurEvent) { return }
- if (cm.state.focused) {
- signal(cm, "blur", cm, e);
- cm.state.focused = false;
- rmClass(cm.display.wrapper, "CodeMirror-focused");
- }
- clearInterval(cm.display.blinker);
- setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
+ function simpleSelection(anchor, head) {
+ return new Selection([new Range(anchor, head || anchor)], 0)
}
- // Re-align line numbers and gutter marks to compensate for
- // horizontal scrolling.
- function alignHorizontally(cm) {
- var display = cm.display, view = display.view;
- if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
- var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
- var gutterW = display.gutters.offsetWidth, left = comp + "px";
- for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
- if (cm.options.fixedGutter) {
- if (view[i].gutter)
- { view[i].gutter.style.left = left; }
- if (view[i].gutterBackground)
- { view[i].gutterBackground.style.left = left; }
- }
- var align = view[i].alignable;
- if (align) { for (var j = 0; j < align.length; j++)
- { align[j].style.left = left; } }
- } }
- if (cm.options.fixedGutter)
- { display.gutters.style.left = (comp + gutterW) + "px"; }
+ // Compute the position of the end of a change (its 'to' property
+ // refers to the pre-change end).
+ function changeEnd(change) {
+ if (!change.text) { return change.to }
+ return Pos(change.from.line + change.text.length - 1,
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
}
- // Used to ensure that the line number gutter is still the right
- // size for the current document size. Returns true when an update
- // is needed.
- function maybeUpdateLineNumberWidth(cm) {
- if (!cm.options.lineNumbers) { return false }
- var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
- if (last.length != display.lineNumChars) {
- var test = display.measure.appendChild(elt("div", [elt("div", last)],
- "CodeMirror-linenumber CodeMirror-gutter-elt"));
- var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
- display.lineGutter.style.width = "";
- display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
- display.lineNumWidth = display.lineNumInnerWidth + padding;
- display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
- display.lineGutter.style.width = display.lineNumWidth + "px";
- updateGutterSpace(cm);
- return true
- }
- return false
+ // Adjust a position to refer to the post-change position of the
+ // same text, or the end of the change if the change covers it.
+ function adjustForChange(pos, change) {
+ if (cmp(pos, change.from) < 0) { return pos }
+ if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
+
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+ if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
+ return Pos(line, ch)
}
- // Read the actual heights of the rendered lines, and update their
- // stored heights to match.
- function updateHeightsInViewport(cm) {
- var display = cm.display;
- var prevBottom = display.lineDiv.offsetTop;
- for (var i = 0; i < display.view.length; i++) {
- var cur = display.view[i], height = (void 0);
- if (cur.hidden) { continue }
- if (ie && ie_version < 8) {
- var bot = cur.node.offsetTop + cur.node.offsetHeight;
- height = bot - prevBottom;
- prevBottom = bot;
- } else {
- var box = cur.node.getBoundingClientRect();
- height = box.bottom - box.top;
- }
- var diff = cur.line.height - height;
- if (height < 2) { height = textHeight(display); }
- if (diff > .001 || diff < -.001) {
- updateLineHeight(cur.line, height);
- updateWidgetHeight(cur.line);
- if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
- { updateWidgetHeight(cur.rest[j]); } }
- }
+ function computeSelAfterChange(doc, change) {
+ var out = [];
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ out.push(new Range(adjustForChange(range.anchor, change),
+ adjustForChange(range.head, change)));
}
+ return normalizeSelection(out, doc.sel.primIndex)
}
- // Read and store the height of line widgets associated with the
- // given line.
- function updateWidgetHeight(line) {
- if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
- { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } }
+ function offsetPos(pos, old, nw) {
+ if (pos.line == old.line)
+ { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
+ else
+ { return Pos(nw.line + (pos.line - old.line), pos.ch) }
}
- // Compute the lines that are visible in a given viewport (defaults
- // the the current scroll position). viewport may contain top,
- // height, and ensure (see op.scrollToPos) properties.
- function visibleLines(display, doc, viewport) {
- var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
- top = Math.floor(top - paddingTop(display));
- var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
-
- var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
- // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
- // forces those lines into the viewport (if possible).
- if (viewport && viewport.ensure) {
- var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
- if (ensureFrom < from) {
- from = ensureFrom;
- to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
- } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
- from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
- to = ensureTo;
+ // Used by replaceSelections to allow moving the selection to the
+ // start or around the replaced test. Hint may be "start" or "around".
+ function computeReplacedSel(doc, changes, hint) {
+ var out = [];
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ var from = offsetPos(change.from, oldPrev, newPrev);
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
+ oldPrev = change.to;
+ newPrev = to;
+ if (hint == "around") {
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
+ out[i] = new Range(inv ? to : from, inv ? from : to);
+ } else {
+ out[i] = new Range(from, from);
}
}
- return {from: from, to: Math.max(to, from + 1)}
- }
-
- // Sync the scrollable area and scrollbars, ensure the viewport
- // covers the visible area.
- function setScrollTop(cm, val) {
- if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
- cm.doc.scrollTop = val;
- if (!gecko) { updateDisplaySimple(cm, {top: val}); }
- if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
- cm.display.scrollbars.setScrollTop(val);
- if (gecko) { updateDisplaySimple(cm); }
- startWorker(cm, 100);
- }
- // Sync scroller and scrollbar, ensure the gutter elements are
- // aligned.
- function setScrollLeft(cm, val, isScroller) {
- if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
- val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
- cm.doc.scrollLeft = val;
- alignHorizontally(cm);
- if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
- cm.display.scrollbars.setScrollLeft(val);
+ return new Selection(out, doc.sel.primIndex)
}
- // Since the delta values reported on mouse wheel events are
- // unstandardized between browsers and even browser versions, and
- // generally horribly unpredictable, this code starts by measuring
- // the scroll effect that the first few mouse wheel events have,
- // and, from that, detects the way it can convert deltas to pixel
- // offsets afterwards.
- //
- // The reason we want to know the amount a wheel event will scroll
- // is that it gives us a chance to update the display before the
- // actual scrolling happens, reducing flickering.
-
- var wheelSamples = 0;
- var wheelPixelsPerUnit = null;
- // Fill in a browser-detected starting value on browsers where we
- // know one. These don't have to be accurate -- the result of them
- // being wrong would just be a slight flicker on the first wheel
- // scroll (if it is large enough).
- if (ie) { wheelPixelsPerUnit = -.53; }
- else if (gecko) { wheelPixelsPerUnit = 15; }
- else if (chrome) { wheelPixelsPerUnit = -.7; }
- else if (safari) { wheelPixelsPerUnit = -1/3; }
+ // Used to get the editor into a consistent state again when options change.
- function wheelEventDelta(e) {
- var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
- if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
- if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
- else if (dy == null) { dy = e.wheelDelta; }
- return {x: dx, y: dy}
+ function loadMode(cm) {
+ cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
+ resetModeState(cm);
}
- function wheelEventPixels(e) {
- var delta = wheelEventDelta(e);
- delta.x *= wheelPixelsPerUnit;
- delta.y *= wheelPixelsPerUnit;
- return delta
+
+ function resetModeState(cm) {
+ cm.doc.iter(function (line) {
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ });
+ cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
+ startWorker(cm, 100);
+ cm.state.modeGen++;
+ if (cm.curOp) { regChange(cm); }
}
- function onScrollWheel(cm, e) {
- var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
+ // DOCUMENT DATA STRUCTURE
- var display = cm.display, scroll = display.scroller;
- // Quit if there's nothing to scroll here
- var canScrollX = scroll.scrollWidth > scroll.clientWidth;
- var canScrollY = scroll.scrollHeight > scroll.clientHeight;
- if (!(dx && canScrollX || dy && canScrollY)) { return }
+ // By default, updates that start and end at the beginning of a line
+ // are treated specially, in order to make the association of line
+ // widgets and marker elements with the text behave more intuitive.
+ function isWholeLineUpdate(doc, change) {
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
+ }
- // Webkit browsers on OS X abort momentum scrolls when the target
- // of the scroll event is removed from the scrollable element.
- // This hack (see related code in patchDisplay) makes sure the
- // element is kept around.
- if (dy && mac && webkit) {
- outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
- for (var i = 0; i < view.length; i++) {
- if (view[i].node == cur) {
- cm.display.currentWheelTarget = cur;
- break outer
- }
- }
- }
+ // Perform a change on the document data structure.
+ function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null}
+ function update(line, text, spans) {
+ updateLine(line, text, spans, estimateHeight$$1);
+ signalLater(line, "change", line, change);
}
-
- // On some browsers, horizontal scrolling will cause redraws to
- // happen before the gutter has been realigned, causing it to
- // wriggle around in a most unseemly way. When we have an
- // estimated pixels/delta value, we just handle horizontal
- // scrolling entirely here. It'll be slightly off from native, but
- // better than glitching out.
- if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
- if (dy && canScrollY)
- { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); }
- setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
- // Only prevent default scrolling if vertical scrolling is
- // actually possible. Otherwise, it causes vertical scroll
- // jitter on OSX trackpads when deltaX is small and deltaY
- // is large (issue #3579)
- if (!dy || (dy && canScrollY))
- { e_preventDefault(e); }
- display.wheelStartX = null; // Abort measurement, if in progress
- return
+ function linesFor(start, end) {
+ var result = [];
+ for (var i = start; i < end; ++i)
+ { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
+ return result
}
- // 'Project' the visible viewport to cover the area that is being
- // scrolled into view (if we know enough to estimate it).
- if (dy && wheelPixelsPerUnit != null) {
- var pixels = dy * wheelPixelsPerUnit;
- var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
- if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
- else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
- updateDisplaySimple(cm, {top: top, bottom: bot});
- }
+ var from = change.from, to = change.to, text = change.text;
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
- if (wheelSamples < 20) {
- if (display.wheelStartX == null) {
- display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
- display.wheelDX = dx; display.wheelDY = dy;
- setTimeout(function () {
- if (display.wheelStartX == null) { return }
- var movedX = scroll.scrollLeft - display.wheelStartX;
- var movedY = scroll.scrollTop - display.wheelStartY;
- var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
- (movedX && display.wheelDX && movedX / display.wheelDX);
- display.wheelStartX = display.wheelStartY = null;
- if (!sample) { return }
- wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
- ++wheelSamples;
- }, 200);
+ // Adjust the line structure
+ if (change.full) {
+ doc.insert(0, linesFor(0, text.length));
+ doc.remove(text.length, doc.size - text.length);
+ } else if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = linesFor(0, text.length - 1);
+ update(lastLine, lastLine.text, lastSpans);
+ if (nlines) { doc.remove(from.line, nlines); }
+ if (added.length) { doc.insert(from.line, added); }
+ } else if (firstLine == lastLine) {
+ if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
} else {
- display.wheelDX += dx; display.wheelDY += dy;
+ var added$1 = linesFor(1, text.length - 1);
+ added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ doc.insert(from.line + 1, added$1);
}
+ } else if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+ doc.remove(from.line + 1, nlines);
+ } else {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+ var added$2 = linesFor(1, text.length - 1);
+ if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
+ doc.insert(from.line + 1, added$2);
}
- }
- // SCROLLBARS
+ signalLater(doc, "change", doc, change);
+ }
- // Prepare DOM reads needed to update the scrollbars. Done in one
- // shot to minimize update/measure roundtrips.
- function measureForScrollbars(cm) {
- var d = cm.display, gutterW = d.gutters.offsetWidth;
- var docH = Math.round(cm.doc.height + paddingVert(cm.display));
- return {
- clientHeight: d.scroller.clientHeight,
- viewHeight: d.wrapper.clientHeight,
- scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
- viewWidth: d.wrapper.clientWidth,
- barLeft: cm.options.fixedGutter ? gutterW : 0,
- docHeight: docH,
- scrollHeight: docH + scrollGap(cm) + d.barHeight,
- nativeBarWidth: d.nativeBarWidth,
- gutterWidth: gutterW
+ // Call f for all linked documents.
+ function linkedDocs(doc, f, sharedHistOnly) {
+ function propagate(doc, skip, sharedHist) {
+ if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
+ var rel = doc.linked[i];
+ if (rel.doc == skip) { continue }
+ var shared = sharedHist && rel.sharedHist;
+ if (sharedHistOnly && !shared) { continue }
+ f(rel.doc, shared);
+ propagate(rel.doc, doc, shared);
+ } }
}
+ propagate(doc, null, true);
}
- var NativeScrollbars = function(place, scroll, cm) {
- this.cm = cm;
- var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
- var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
- place(vert); place(horiz);
+ // Attach a document to an editor.
+ function attachDoc(cm, doc) {
+ if (doc.cm) { throw new Error("This document is already in use.") }
+ cm.doc = doc;
+ doc.cm = cm;
+ estimateLineHeights(cm);
+ loadMode(cm);
+ setDirectionClass(cm);
+ if (!cm.options.lineWrapping) { findMaxLine(cm); }
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+ }
- on(vert, "scroll", function () {
- if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
- });
- on(horiz, "scroll", function () {
- if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
+ function setDirectionClass(cm) {
+ (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
+ }
+
+ function directionChanged(cm) {
+ runInOp(cm, function () {
+ setDirectionClass(cm);
+ regChange(cm);
});
+ }
- this.checkedZeroWidth = false;
- // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
- if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
- };
-
- NativeScrollbars.prototype.update = function (measure) {
- var needsH = measure.scrollWidth > measure.clientWidth + 1;
- var needsV = measure.scrollHeight > measure.clientHeight + 1;
- var sWidth = measure.nativeBarWidth;
+ function History(startGen) {
+ // Arrays of change events and selections. Doing something adds an
+ // event to done and clears undo. Undoing moves events from done
+ // to undone, redoing moves them in the other direction.
+ this.done = []; this.undone = [];
+ this.undoDepth = Infinity;
+ // Used to track when changes can be merged into a single undo
+ // event
+ this.lastModTime = this.lastSelTime = 0;
+ this.lastOp = this.lastSelOp = null;
+ this.lastOrigin = this.lastSelOrigin = null;
+ // Used by the isClean() method
+ this.generation = this.maxGeneration = startGen || 1;
+ }
- if (needsV) {
- this.vert.style.display = "block";
- this.vert.style.bottom = needsH ? sWidth + "px" : "0";
- var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
- // A bug in IE8 can cause this value to be negative, so guard it.
- this.vert.firstChild.style.height =
- Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
- } else {
- this.vert.style.display = "";
- this.vert.firstChild.style.height = "0";
- }
+ // Create a history change event from an updateDoc-style change
+ // object.
+ function historyChangeFromChange(doc, change) {
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+ linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
+ return histChange
+ }
- if (needsH) {
- this.horiz.style.display = "block";
- this.horiz.style.right = needsV ? sWidth + "px" : "0";
- this.horiz.style.left = measure.barLeft + "px";
- var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
- this.horiz.firstChild.style.width =
- Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
- } else {
- this.horiz.style.display = "";
- this.horiz.firstChild.style.width = "0";
+ // Pop all selection events off the end of a history array. Stop at
+ // a change event.
+ function clearSelectionEvents(array) {
+ while (array.length) {
+ var last = lst(array);
+ if (last.ranges) { array.pop(); }
+ else { break }
}
+ }
- if (!this.checkedZeroWidth && measure.clientHeight > 0) {
- if (sWidth == 0) { this.zeroWidthHack(); }
- this.checkedZeroWidth = true;
+ // Find the top change event in the history. Pop off selection
+ // events that are in the way.
+ function lastChangeEvent(hist, force) {
+ if (force) {
+ clearSelectionEvents(hist.done);
+ return lst(hist.done)
+ } else if (hist.done.length && !lst(hist.done).ranges) {
+ return lst(hist.done)
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
+ hist.done.pop();
+ return lst(hist.done)
}
+ }
- return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
- };
-
- NativeScrollbars.prototype.setScrollLeft = function (pos) {
- if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
- if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
- };
-
- NativeScrollbars.prototype.setScrollTop = function (pos) {
- if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
- if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
- };
-
- NativeScrollbars.prototype.zeroWidthHack = function () {
- var w = mac && !mac_geMountainLion ? "12px" : "18px";
- this.horiz.style.height = this.vert.style.width = w;
- this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
- this.disableHoriz = new Delayed;
- this.disableVert = new Delayed;
- };
+ // Register a change in the history. Merges changes that are within
+ // a single operation, or are close together with an origin that
+ // allows merging (starting with "+") into a single event.
+ function addChangeToHistory(doc, change, selAfter, opId) {
+ var hist = doc.history;
+ hist.undone.length = 0;
+ var time = +new Date, cur;
+ var last;
- NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
- bar.style.pointerEvents = "auto";
- function maybeDisable() {
- // To find out whether the scrollbar is still visible, we
- // check whether the element under the pixel in the bottom
- // right corner of the scrollbar box is the scrollbar box
- // itself (when the bar is still visible) or its filler child
- // (when the bar is hidden). If it is still visible, we keep
- // it enabled, if it's hidden, we disable pointer events.
- var box = bar.getBoundingClientRect();
- var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
- : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
- if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
- else { delay.set(1000, maybeDisable); }
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ last = lst(cur.changes);
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
+ // Optimized case for simple insertion -- don't want to add
+ // new changesets for every character typed
+ last.to = changeEnd(change);
+ } else {
+ // Add new sub-event
+ cur.changes.push(historyChangeFromChange(doc, change));
+ }
+ } else {
+ // Can not be merged, start a new event.
+ var before = lst(hist.done);
+ if (!before || !before.ranges)
+ { pushSelectionToHistory(doc.sel, hist.done); }
+ cur = {changes: [historyChangeFromChange(doc, change)],
+ generation: hist.generation};
+ hist.done.push(cur);
+ while (hist.done.length > hist.undoDepth) {
+ hist.done.shift();
+ if (!hist.done[0].ranges) { hist.done.shift(); }
+ }
}
- delay.set(1000, maybeDisable);
- };
-
- NativeScrollbars.prototype.clear = function () {
- var parent = this.horiz.parentNode;
- parent.removeChild(this.horiz);
- parent.removeChild(this.vert);
- };
-
- var NullScrollbars = function () {};
+ hist.done.push(selAfter);
+ hist.generation = ++hist.maxGeneration;
+ hist.lastModTime = hist.lastSelTime = time;
+ hist.lastOp = hist.lastSelOp = opId;
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
- NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
- NullScrollbars.prototype.setScrollLeft = function () {};
- NullScrollbars.prototype.setScrollTop = function () {};
- NullScrollbars.prototype.clear = function () {};
+ if (!last) { signal(doc, "historyAdded"); }
+ }
- function updateScrollbars(cm, measure) {
- if (!measure) { measure = measureForScrollbars(cm); }
- var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
- updateScrollbarsInner(cm, measure);
- for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
- if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
- { updateHeightsInViewport(cm); }
- updateScrollbarsInner(cm, measureForScrollbars(cm));
- startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
- }
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
+ var ch = origin.charAt(0);
+ return ch == "*" ||
+ ch == "+" &&
+ prev.ranges.length == sel.ranges.length &&
+ prev.somethingSelected() == sel.somethingSelected() &&
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
}
- // Re-synchronize the fake scrollbars with the actual size of the
- // content.
- function updateScrollbarsInner(cm, measure) {
- var d = cm.display;
- var sizes = d.scrollbars.update(measure);
+ // Called whenever the selection changes, sets the new selection as
+ // the pending selection in the history, and pushes the old pending
+ // selection into the 'done' array when it was significantly
+ // different (in number of selected ranges, emptiness, or time).
+ function addSelectionToHistory(doc, sel, opId, options) {
+ var hist = doc.history, origin = options && options.origin;
- d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
- d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
- d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
+ // A new event is started when the previous origin does not match
+ // the current, or the origins don't allow matching. Origins
+ // starting with * are always merged, those starting with + are
+ // merged when similar and close together in time.
+ if (opId == hist.lastSelOp ||
+ (origin && hist.lastSelOrigin == origin &&
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+ { hist.done[hist.done.length - 1] = sel; }
+ else
+ { pushSelectionToHistory(sel, hist.done); }
- if (sizes.right && sizes.bottom) {
- d.scrollbarFiller.style.display = "block";
- d.scrollbarFiller.style.height = sizes.bottom + "px";
- d.scrollbarFiller.style.width = sizes.right + "px";
- } else { d.scrollbarFiller.style.display = ""; }
- if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
- d.gutterFiller.style.display = "block";
- d.gutterFiller.style.height = sizes.bottom + "px";
- d.gutterFiller.style.width = measure.gutterWidth + "px";
- } else { d.gutterFiller.style.display = ""; }
+ hist.lastSelTime = +new Date;
+ hist.lastSelOrigin = origin;
+ hist.lastSelOp = opId;
+ if (options && options.clearRedo !== false)
+ { clearSelectionEvents(hist.undone); }
}
- var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
+ function pushSelectionToHistory(sel, dest) {
+ var top = lst(dest);
+ if (!(top && top.ranges && top.equals(sel)))
+ { dest.push(sel); }
+ }
- function initScrollbars(cm) {
- if (cm.display.scrollbars) {
- cm.display.scrollbars.clear();
- if (cm.display.scrollbars.addClass)
- { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
- }
+ // Used to store marked span information in the history.
+ function attachLocalSpans(doc, change, from, to) {
+ var existing = change["spans_" + doc.id], n = 0;
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
+ if (line.markedSpans)
+ { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
+ ++n;
+ });
+ }
- cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
- cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
- // Prevent clicks in the scrollbars from killing focus
- on(node, "mousedown", function () {
- if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
- });
- node.setAttribute("cm-not-content", "true");
- }, function (pos, axis) {
- if (axis == "horizontal") { setScrollLeft(cm, pos); }
- else { setScrollTop(cm, pos); }
- }, cm);
- if (cm.display.scrollbars.addClass)
- { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ // When un/re-doing restores text containing marked spans, those
+ // that have been explicitly cleared should not be restored.
+ function removeClearedSpans(spans) {
+ if (!spans) { return null }
+ var out;
+ for (var i = 0; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
+ else if (out) { out.push(spans[i]); }
+ }
+ return !out ? spans : out.length ? out : null
}
- // SCROLLING THINGS INTO VIEW
+ // Retrieve and filter the old marked spans stored in a change event.
+ function getOldSpans(doc, change) {
+ var found = change["spans_" + doc.id];
+ if (!found) { return null }
+ var nw = [];
+ for (var i = 0; i < change.text.length; ++i)
+ { nw.push(removeClearedSpans(found[i])); }
+ return nw
+ }
- // If an editor sits on the top or bottom of the window, partially
- // scrolled out of view, this ensures that the cursor is visible.
- function maybeScrollWindow(cm, rect) {
- if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+ // Used for un/re-doing changes from the history. Combines the
+ // result of computing the existing spans with the set of spans that
+ // existed in the history (so that deleting around a span and then
+ // undoing brings back the span).
+ function mergeOldSpans(doc, change) {
+ var old = getOldSpans(doc, change);
+ var stretched = stretchSpansOverChange(doc, change);
+ if (!old) { return stretched }
+ if (!stretched) { return old }
- var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
- if (rect.top + box.top < 0) { doScroll = true; }
- else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
- if (doScroll != null && !phantom) {
- var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
- cm.display.lineSpace.appendChild(scrollNode);
- scrollNode.scrollIntoView(doScroll);
- cm.display.lineSpace.removeChild(scrollNode);
+ for (var i = 0; i < old.length; ++i) {
+ var oldCur = old[i], stretchCur = stretched[i];
+ if (oldCur && stretchCur) {
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
+ var span = stretchCur[j];
+ for (var k = 0; k < oldCur.length; ++k)
+ { if (oldCur[k].marker == span.marker) { continue spans } }
+ oldCur.push(span);
+ }
+ } else if (stretchCur) {
+ old[i] = stretchCur;
+ }
}
+ return old
}
- // Scroll a given position into view (immediately), verifying that
- // it actually became visible (as line heights are accurately
- // measured, the position of something may 'drift' during drawing).
- function scrollPosIntoView(cm, pos, end, margin) {
- if (margin == null) { margin = 0; }
- var rect;
- for (var limit = 0; limit < 5; limit++) {
- var changed = false;
- var coords = cursorCoords(cm, pos);
- var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
- rect = {left: Math.min(coords.left, endCoords.left),
- top: Math.min(coords.top, endCoords.top) - margin,
- right: Math.max(coords.left, endCoords.left),
- bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
- var scrollPos = calculateScrollPos(cm, rect);
- var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
- if (scrollPos.scrollTop != null) {
- setScrollTop(cm, scrollPos.scrollTop);
- if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
+ // Used both to provide a JSON-safe object in .getHistory, and, when
+ // detaching a document, to split the history in two
+ function copyHistoryArray(events, newGroup, instantiateSel) {
+ var copy = [];
+ for (var i = 0; i < events.length; ++i) {
+ var event = events[i];
+ if (event.ranges) {
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
+ continue
}
- if (scrollPos.scrollLeft != null) {
- setScrollLeft(cm, scrollPos.scrollLeft);
- if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
+ var changes = event.changes, newChanges = [];
+ copy.push({changes: newChanges});
+ for (var j = 0; j < changes.length; ++j) {
+ var change = changes[j], m = (void 0);
+ newChanges.push({from: change.from, to: change.to, text: change.text});
+ if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
+ if (indexOf(newGroup, Number(m[1])) > -1) {
+ lst(newChanges)[prop] = change[prop];
+ delete change[prop];
+ }
+ } } }
}
- if (!changed) { break }
}
- return rect
+ return copy
}
- // Scroll a given set of coordinates into view (immediately).
- function scrollIntoView(cm, rect) {
- var scrollPos = calculateScrollPos(cm, rect);
- if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop); }
- if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
- }
+ // The 'scroll' parameter given to many of these indicated whether
+ // the new cursor position should be scrolled into view after
+ // modifying the selection.
- // Calculate a new scroll position needed to scroll the given
- // rectangle into view. Returns an object with scrollTop and
- // scrollLeft properties. When these are undefined, the
- // vertical/horizontal position does not need to be adjusted.
- function calculateScrollPos(cm, rect) {
- var display = cm.display, snapMargin = textHeight(cm.display);
- if (rect.top < 0) { rect.top = 0; }
- var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
- var screen = displayHeight(cm), result = {};
- if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
- var docBottom = cm.doc.height + paddingVert(display);
- var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
- if (rect.top < screentop) {
- result.scrollTop = atTop ? 0 : rect.top;
- } else if (rect.bottom > screentop + screen) {
- var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
- if (newTop != screentop) { result.scrollTop = newTop; }
+ // If shift is held or the extend flag is set, extends a range to
+ // include a given position (and optionally a second position).
+ // Otherwise, simply returns the range between the given positions.
+ // Used for cursor motion and such.
+ function extendRange(range, head, other, extend) {
+ if (extend) {
+ var anchor = range.anchor;
+ if (other) {
+ var posBefore = cmp(head, anchor) < 0;
+ if (posBefore != (cmp(other, anchor) < 0)) {
+ anchor = head;
+ head = other;
+ } else if (posBefore != (cmp(head, other) < 0)) {
+ head = other;
+ }
+ }
+ return new Range(anchor, head)
+ } else {
+ return new Range(other || head, head)
}
+ }
- var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
- var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
- var tooWide = rect.right - rect.left > screenw;
- if (tooWide) { rect.right = rect.left + screenw; }
- if (rect.left < 10)
- { result.scrollLeft = 0; }
- else if (rect.left < screenleft)
- { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
- else if (rect.right > screenw + screenleft - 3)
- { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
- return result
+ // Extend the primary selection range, discard the rest.
+ function extendSelection(doc, head, other, options, extend) {
+ if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
+ setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
}
- // Store a relative adjustment to the scroll position in the current
- // operation (to be applied when the operation finishes).
- function addToScrollPos(cm, left, top) {
- if (left != null || top != null) { resolveScrollToPos(cm); }
- if (left != null)
- { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; }
- if (top != null)
- { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; }
+ // Extend all selections (pos is an array of selections with length
+ // equal the number of selections)
+ function extendSelections(doc, heads, options) {
+ var out = [];
+ var extend = doc.cm && (doc.cm.display.shift || doc.extend);
+ for (var i = 0; i < doc.sel.ranges.length; i++)
+ { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
+ setSelection(doc, newSel, options);
}
- // Make sure that at the end of the operation the current cursor is
- // shown.
- function ensureCursorVisible(cm) {
- resolveScrollToPos(cm);
- var cur = cm.getCursor(), from = cur, to = cur;
- if (!cm.options.lineWrapping) {
- from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
- to = Pos(cur.line, cur.ch + 1);
- }
- cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin};
+ // Updates a single range in the selection.
+ function replaceOneSelection(doc, i, range, options) {
+ var ranges = doc.sel.ranges.slice(0);
+ ranges[i] = range;
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
}
- // When an operation has its scrollToPos property set, and another
- // scroll action is applied before the end of the operation, this
- // 'simulates' scrolling that position into view in a cheap way, so
- // that the effect of intermediate scroll commands is not ignored.
- function resolveScrollToPos(cm) {
- var range$$1 = cm.curOp.scrollToPos;
- if (range$$1) {
- cm.curOp.scrollToPos = null;
- var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
- var sPos = calculateScrollPos(cm, {
- left: Math.min(from.left, to.left),
- top: Math.min(from.top, to.top) - range$$1.margin,
- right: Math.max(from.right, to.right),
- bottom: Math.max(from.bottom, to.bottom) + range$$1.margin
- });
- cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
- }
+ // Reset the selection to a single range.
+ function setSimpleSelection(doc, anchor, head, options) {
+ setSelection(doc, simpleSelection(anchor, head), options);
}
- // Operations are used to wrap a series of changes to the editor
- // state in such a way that each change won't have to update the
- // cursor and display (which would be awkward, slow, and
- // error-prone). Instead, display updates are batched and then all
- // combined and executed at once.
+ // Give beforeSelectionChange handlers a change to influence a
+ // selection update.
+ function filterSelectionChange(doc, sel, options) {
+ var obj = {
+ ranges: sel.ranges,
+ update: function(ranges) {
+ var this$1 = this;
- var nextOpId = 0;
- // Start a new operation.
- function startOperation(cm) {
- cm.curOp = {
- cm: cm,
- viewChanged: false, // Flag that indicates that lines might need to be redrawn
- startHeight: cm.doc.height, // Used to detect need to update scrollbar
- forceUpdate: false, // Used to force a redraw
- updateInput: null, // Whether to reset the input textarea
- typing: false, // Whether this reset should be careful to leave existing text (for compositing)
- changeObjs: null, // Accumulated changes, for firing change events
- cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
- cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
- selectionChanged: false, // Whether the selection needs to be redrawn
- updateMaxLine: false, // Set when the widest line needs to be determined anew
- scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
- scrollToPos: null, // Used to scroll to a specific position
- focus: false,
- id: ++nextOpId // Unique ID
+ this.ranges = [];
+ for (var i = 0; i < ranges.length; i++)
+ { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
+ clipPos(doc, ranges[i].head)); }
+ },
+ origin: options && options.origin
};
- pushOperation(cm.curOp);
+ signal(doc, "beforeSelectionChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
+ if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
+ else { return sel }
}
- // Finish an operation, updating the display and signalling delayed events
- function endOperation(cm) {
- var op = cm.curOp;
- finishOperation(op, function (group) {
- for (var i = 0; i < group.ops.length; i++)
- { group.ops[i].cm.curOp = null; }
- endOperations(group);
- });
+ function setSelectionReplaceHistory(doc, sel, options) {
+ var done = doc.history.done, last = lst(done);
+ if (last && last.ranges) {
+ done[done.length - 1] = sel;
+ setSelectionNoUndo(doc, sel, options);
+ } else {
+ setSelection(doc, sel, options);
+ }
}
- // The DOM updates done when an operation finishes are batched so
- // that the minimum number of relayouts are required.
- function endOperations(group) {
- var ops = group.ops;
- for (var i = 0; i < ops.length; i++) // Read DOM
- { endOperation_R1(ops[i]); }
- for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
- { endOperation_W1(ops[i$1]); }
- for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
- { endOperation_R2(ops[i$2]); }
- for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
- { endOperation_W2(ops[i$3]); }
- for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
- { endOperation_finish(ops[i$4]); }
- }
+ // Set a new selection.
+ function setSelection(doc, sel, options) {
+ setSelectionNoUndo(doc, sel, options);
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
+ }
- function endOperation_R1(op) {
- var cm = op.cm, display = cm.display;
- maybeClipScrollbars(cm);
- if (op.updateMaxLine) { findMaxLine(cm); }
+ function setSelectionNoUndo(doc, sel, options) {
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
+ { sel = filterSelectionChange(doc, sel, options); }
- op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
- op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
- op.scrollToPos.to.line >= display.viewTo) ||
- display.maxLineChanged && cm.options.lineWrapping;
- op.update = op.mustUpdate &&
- new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
- }
+ var bias = options && options.bias ||
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
- function endOperation_W1(op) {
- op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
+ if (!(options && options.scroll === false) && doc.cm)
+ { ensureCursorVisible(doc.cm); }
}
- function endOperation_R2(op) {
- var cm = op.cm, display = cm.display;
- if (op.updatedDisplay) { updateHeightsInViewport(cm); }
+ function setSelectionInner(doc, sel) {
+ if (sel.equals(doc.sel)) { return }
- op.barMeasure = measureForScrollbars(cm);
+ doc.sel = sel;
- // If the max line changed since it was last measured, measure it,
- // and ensure the document's width matches it.
- // updateDisplay_W2 will use these properties to do the actual resizing
- if (display.maxLineChanged && !cm.options.lineWrapping) {
- op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
- cm.display.sizerWidth = op.adjustWidthTo;
- op.barMeasure.scrollWidth =
- Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
- op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
+ if (doc.cm) {
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
+ signalCursorActivity(doc.cm);
}
-
- if (op.updatedDisplay || op.selectionChanged)
- { op.preparedSelection = display.input.prepareSelection(op.focus); }
+ signalLater(doc, "cursorActivity", doc);
}
- function endOperation_W2(op) {
- var cm = op.cm;
-
- if (op.adjustWidthTo != null) {
- cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
- if (op.maxScrollLeft < cm.doc.scrollLeft)
- { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
- cm.display.maxLineChanged = false;
- }
-
- var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus());
- if (op.preparedSelection)
- { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
- if (op.updatedDisplay || op.startHeight != cm.doc.height)
- { updateScrollbars(cm, op.barMeasure); }
- if (op.updatedDisplay)
- { setDocumentHeight(cm, op.barMeasure); }
-
- if (op.selectionChanged) { restartBlink(cm); }
-
- if (cm.state.focused && op.updateInput)
- { cm.display.input.reset(op.typing); }
- if (takeFocus) { ensureFocus(op.cm); }
+ // Verify that the selection does not partially select any atomic
+ // marked ranges.
+ function reCheckSelection(doc) {
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
}
- function endOperation_finish(op) {
- var cm = op.cm, display = cm.display, doc = cm.doc;
-
- if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
-
- // Abort mouse wheel delta measurement, when scrolling explicitly
- if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
- { display.wheelStartX = display.wheelStartY = null; }
-
- // Propagate the scroll position to the actual DOM scroller
- if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
- doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
- display.scrollbars.setScrollTop(doc.scrollTop);
- display.scroller.scrollTop = doc.scrollTop;
- }
- if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
- doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
- display.scrollbars.setScrollLeft(doc.scrollLeft);
- display.scroller.scrollLeft = doc.scrollLeft;
- alignHorizontally(cm);
- }
- // If we need to scroll a specific position into view, do so.
- if (op.scrollToPos) {
- var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
- clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
- maybeScrollWindow(cm, rect);
+ // Return a selection that does not partially select any atomic
+ // ranges.
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
+ var out;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
+ var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
+ if (out || newAnchor != range.anchor || newHead != range.head) {
+ if (!out) { out = sel.ranges.slice(0, i); }
+ out[i] = new Range(newAnchor, newHead);
+ }
}
+ return out ? normalizeSelection(out, sel.primIndex) : sel
+ }
- // Fire events for markers that are hidden/unidden by editing or
- // undoing
- var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
- if (hidden) { for (var i = 0; i < hidden.length; ++i)
- { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
- if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
- { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+ var line = getLine(doc, pos.line);
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) { break }
+ else {--i; continue}
+ }
+ }
+ if (!m.atomic) { continue }
- if (display.wrapper.offsetHeight)
- { doc.scrollTop = cm.display.scroller.scrollTop; }
+ if (oldPos) {
+ var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
+ { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
+ { return skipAtomicInner(doc, near, pos, dir, mayClear) }
+ }
- // Fire change events, and delayed event handlers
- if (op.changeObjs)
- { signal(cm, "changes", cm, op.changeObjs); }
- if (op.update)
- { op.update.finish(); }
+ var far = m.find(dir < 0 ? -1 : 1);
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
+ { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
+ }
+ } }
+ return pos
}
- // Run the given function in an operation
- function runInOp(cm, f) {
- if (cm.curOp) { return f() }
- startOperation(cm);
- try { return f() }
- finally { endOperation(cm); }
- }
- // Wraps a function in an operation. Returns the wrapped function.
- function operation(cm, f) {
- return function() {
- if (cm.curOp) { return f.apply(cm, arguments) }
- startOperation(cm);
- try { return f.apply(cm, arguments) }
- finally { endOperation(cm); }
- }
- }
- // Used to add methods to editor and doc instances, wrapping them in
- // operations.
- function methodOp(f) {
- return function() {
- if (this.curOp) { return f.apply(this, arguments) }
- startOperation(this);
- try { return f.apply(this, arguments) }
- finally { endOperation(this); }
- }
- }
- function docMethodOp(f) {
- return function() {
- var cm = this.cm;
- if (!cm || cm.curOp) { return f.apply(this, arguments) }
- startOperation(cm);
- try { return f.apply(this, arguments) }
- finally { endOperation(cm); }
+ // Ensure a given position is not inside an atomic range.
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
+ var dir = bias || 1;
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
+ if (!found) {
+ doc.cantEdit = true;
+ return Pos(doc.first, 0)
}
+ return found
}
- // Updates the display.view data structure for a given change to the
- // document. From and to are in pre-change coordinates. Lendiff is
- // the amount of lines added or subtracted by the change. This is
- // used for changes that span multiple lines, or change the way
- // lines are divided into visual lines. regLineChange (below)
- // registers single-line changes.
- function regChange(cm, from, to, lendiff) {
- if (from == null) { from = cm.doc.first; }
- if (to == null) { to = cm.doc.first + cm.doc.size; }
- if (!lendiff) { lendiff = 0; }
-
- var display = cm.display;
- if (lendiff && to < display.viewTo &&
- (display.updateLineNumbers == null || display.updateLineNumbers > from))
- { display.updateLineNumbers = from; }
-
- cm.curOp.viewChanged = true;
-
- if (from >= display.viewTo) { // Change after
- if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
- { resetView(cm); }
- } else if (to <= display.viewFrom) { // Change before
- if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
- resetView(cm);
- } else {
- display.viewFrom += lendiff;
- display.viewTo += lendiff;
- }
- } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
- resetView(cm);
- } else if (from <= display.viewFrom) { // Top overlap
- var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
- if (cut) {
- display.view = display.view.slice(cut.index);
- display.viewFrom = cut.lineN;
- display.viewTo += lendiff;
- } else {
- resetView(cm);
- }
- } else if (to >= display.viewTo) { // Bottom overlap
- var cut$1 = viewCuttingPoint(cm, from, from, -1);
- if (cut$1) {
- display.view = display.view.slice(0, cut$1.index);
- display.viewTo = cut$1.lineN;
- } else {
- resetView(cm);
- }
- } else { // Gap in the middle
- var cutTop = viewCuttingPoint(cm, from, from, -1);
- var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
- if (cutTop && cutBot) {
- display.view = display.view.slice(0, cutTop.index)
- .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
- .concat(display.view.slice(cutBot.index));
- display.viewTo += lendiff;
- } else {
- resetView(cm);
- }
+ function movePos(doc, pos, dir, line) {
+ if (dir < 0 && pos.ch == 0) {
+ if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
+ else { return null }
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
+ if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
+ else { return null }
+ } else {
+ return new Pos(pos.line, pos.ch + dir)
}
+ }
- var ext = display.externalMeasured;
- if (ext) {
- if (to < ext.lineN)
- { ext.lineN += lendiff; }
- else if (from < ext.lineN + ext.size)
- { display.externalMeasured = null; }
- }
+ function selectAll(cm) {
+ cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
}
- // Register a change to a single line. Type must be one of "text",
- // "gutter", "class", "widget"
- function regLineChange(cm, line, type) {
- cm.curOp.viewChanged = true;
- var display = cm.display, ext = cm.display.externalMeasured;
- if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
- { display.externalMeasured = null; }
+ // UPDATING
- if (line < display.viewFrom || line >= display.viewTo) { return }
- var lineView = display.view[findViewIndex(cm, line)];
- if (lineView.node == null) { return }
- var arr = lineView.changes || (lineView.changes = []);
- if (indexOf(arr, type) == -1) { arr.push(type); }
- }
+ // Allow "beforeChange" event handlers to influence a change
+ function filterChange(doc, change, update) {
+ var obj = {
+ canceled: false,
+ from: change.from,
+ to: change.to,
+ text: change.text,
+ origin: change.origin,
+ cancel: function () { return obj.canceled = true; }
+ };
+ if (update) { obj.update = function (from, to, text, origin) {
+ if (from) { obj.from = clipPos(doc, from); }
+ if (to) { obj.to = clipPos(doc, to); }
+ if (text) { obj.text = text; }
+ if (origin !== undefined) { obj.origin = origin; }
+ }; }
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
- // Clear the view.
- function resetView(cm) {
- cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
- cm.display.view = [];
- cm.display.viewOffset = 0;
+ if (obj.canceled) { return null }
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
}
- function viewCuttingPoint(cm, oldN, newN, dir) {
- var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
- if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
- { return {index: index, lineN: newN} }
- var n = cm.display.viewFrom;
- for (var i = 0; i < index; i++)
- { n += view[i].size; }
- if (n != oldN) {
- if (dir > 0) {
- if (index == view.length - 1) { return null }
- diff = (n + view[index].size) - oldN;
- index++;
- } else {
- diff = n - oldN;
- }
- oldN += diff; newN += diff;
+ // Apply a change to a document, and add it to the document's
+ // history, and propagating it to all linked documents.
+ function makeChange(doc, change, ignoreReadOnly) {
+ if (doc.cm) {
+ if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
+ if (doc.cm.state.suppressEdits) { return }
}
- while (visualLineNo(cm.doc, newN) != newN) {
- if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
- newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
- index += dir;
+
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+ change = filterChange(doc, change, true);
+ if (!change) { return }
}
- return {index: index, lineN: newN}
- }
- // Force the view to cover a given range, adding empty view element
- // or clipping off existing ones as needed.
- function adjustView(cm, from, to) {
- var display = cm.display, view = display.view;
- if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
- display.view = buildViewArray(cm, from, to);
- display.viewFrom = from;
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+ if (split) {
+ for (var i = split.length - 1; i >= 0; --i)
+ { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
} else {
- if (display.viewFrom > from)
- { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
- else if (display.viewFrom < from)
- { display.view = display.view.slice(findViewIndex(cm, from)); }
- display.viewFrom = from;
- if (display.viewTo < to)
- { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
- else if (display.viewTo > to)
- { display.view = display.view.slice(0, findViewIndex(cm, to)); }
+ makeChangeInner(doc, change);
}
- display.viewTo = to;
}
- // Count the number of lines in the view whose DOM representation is
- // out of date (or nonexistent).
- function countDirtyView(cm) {
- var view = cm.display.view, dirty = 0;
- for (var i = 0; i < view.length; i++) {
- var lineView = view[i];
- if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
- }
- return dirty
- }
+ function makeChangeInner(doc, change) {
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
+ var selAfter = computeSelAfterChange(doc, change);
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
- // HIGHLIGHT WORKER
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+ var rebased = [];
- function startWorker(cm, time) {
- if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
- { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+ });
}
- function highlightWorker(cm) {
- var doc = cm.doc;
- if (doc.frontier < doc.first) { doc.frontier = doc.first; }
- if (doc.frontier >= cm.display.viewTo) { return }
- var end = +new Date + cm.options.workTime;
- var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
- var changedLines = [];
+ // Revert a change stored in a document's history.
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+ if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
- doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
- if (doc.frontier >= cm.display.viewFrom) { // Visible
- var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
- var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
- line.styles = highlighted.styles;
- var oldCls = line.styleClasses, newCls = highlighted.classes;
- if (newCls) { line.styleClasses = newCls; }
- else if (oldCls) { line.styleClasses = null; }
- var ischange = !oldStyles || oldStyles.length != line.styles.length ||
- oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
- for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
- if (ischange) { changedLines.push(doc.frontier); }
- line.stateAfter = tooLong ? state : copyState(doc.mode, state);
- } else {
- if (line.text.length <= cm.options.maxHighlightLength)
- { processLine(cm, line.text, state); }
- line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
- }
- ++doc.frontier;
- if (+new Date > end) {
- startWorker(cm, cm.options.workDelay);
- return true
+ var hist = doc.history, event, selAfter = doc.sel;
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
+
+ // Verify that there is a useable event (so that ctrl-z won't
+ // needlessly clear selection events)
+ var i = 0;
+ for (; i < source.length; i++) {
+ event = source[i];
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
+ { break }
+ }
+ if (i == source.length) { return }
+ hist.lastOrigin = hist.lastSelOrigin = null;
+
+ for (;;) {
+ event = source.pop();
+ if (event.ranges) {
+ pushSelectionToHistory(event, dest);
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
+ setSelection(doc, event, {clearRedo: false});
+ return
+ }
+ selAfter = event;
}
- });
- if (changedLines.length) { runInOp(cm, function () {
- for (var i = 0; i < changedLines.length; i++)
- { regLineChange(cm, changedLines[i], "text"); }
- }); }
- }
+ else { break }
+ }
- // DISPLAY DRAWING
+ // Build up a reverse change object to add to the opposite history
+ // stack (redo when undoing, and vice versa).
+ var antiChanges = [];
+ pushSelectionToHistory(selAfter, dest);
+ dest.push({changes: antiChanges, generation: hist.generation});
+ hist.generation = event.generation || ++hist.maxGeneration;
- var DisplayUpdate = function(cm, viewport, force) {
- var display = cm.display;
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
- this.viewport = viewport;
- // Store some values that we'll need later (but don't want to force a relayout for)
- this.visible = visibleLines(display, cm.doc, viewport);
- this.editorIsHidden = !display.wrapper.offsetWidth;
- this.wrapperHeight = display.wrapper.clientHeight;
- this.wrapperWidth = display.wrapper.clientWidth;
- this.oldDisplayWidth = displayWidth(cm);
- this.force = force;
- this.dims = getDimensions(cm);
- this.events = [];
- };
+ var loop = function ( i ) {
+ var change = event.changes[i];
+ change.origin = type;
+ if (filter && !filterChange(doc, change, false)) {
+ source.length = 0;
+ return {}
+ }
- DisplayUpdate.prototype.signal = function (emitter, type) {
- if (hasHandler(emitter, type))
- { this.events.push(arguments); }
- };
- DisplayUpdate.prototype.finish = function () {
- var this$1 = this;
+ antiChanges.push(historyChangeFromChange(doc, change));
- for (var i = 0; i < this.events.length; i++)
- { signal.apply(null, this$1.events[i]); }
- };
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
+ var rebased = [];
- function maybeClipScrollbars(cm) {
- var display = cm.display;
- if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
- display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
- display.heightForcer.style.height = scrollGap(cm) + "px";
- display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
- display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
- display.scrollbarsClipped = true;
- }
- }
+ // Propagate to the linked documents
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ });
+ };
- // Does the actual updating of the line display. Bails out
- // (returning false) when there is nothing to be done and forced is
- // false.
- function updateDisplayIfNeeded(cm, update) {
- var display = cm.display, doc = cm.doc;
+ for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
+ var returned = loop( i$1 );
- if (update.editorIsHidden) {
- resetView(cm);
- return false
+ if ( returned ) return returned.v;
}
+ }
- // Bail out if the visible area is already rendered and nothing changed.
- if (!update.force &&
- update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
- display.renderedView == display.view && countDirtyView(cm) == 0)
- { return false }
-
- if (maybeUpdateLineNumberWidth(cm)) {
- resetView(cm);
- update.dims = getDimensions(cm);
+ // Sub-views need their line numbers shifted when text is added
+ // above or below them in the parent document.
+ function shiftDoc(doc, distance) {
+ if (distance == 0) { return }
+ doc.first += distance;
+ doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
+ Pos(range.anchor.line + distance, range.anchor.ch),
+ Pos(range.head.line + distance, range.head.ch)
+ ); }), doc.sel.primIndex);
+ if (doc.cm) {
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
+ { regLineChange(doc.cm, l, "gutter"); }
}
+ }
- // Compute a suitable new viewport (from & to)
- var end = doc.first + doc.size;
- var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
- var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
- if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
- if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
- if (sawCollapsedSpans) {
- from = visualLineNo(cm.doc, from);
- to = visualLineEndNo(cm.doc, to);
- }
+ // More lower-level change function, handling only a single document
+ // (not linked ones).
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
+ if (doc.cm && !doc.cm.curOp)
+ { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
- var different = from != display.viewFrom || to != display.viewTo ||
- display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
- adjustView(cm, from, to);
+ if (change.to.line < doc.first) {
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+ return
+ }
+ if (change.from.line > doc.lastLine()) { return }
- display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
- // Position the mover div to align with the current scroll position
- cm.display.mover.style.top = display.viewOffset + "px";
+ // Clip the change to the size of this doc
+ if (change.from.line < doc.first) {
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
+ shiftDoc(doc, shift);
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+ text: [lst(change.text)], origin: change.origin};
+ }
+ var last = doc.lastLine();
+ if (change.to.line > last) {
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+ text: [change.text[0]], origin: change.origin};
+ }
- var toUpdate = countDirtyView(cm);
- if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
- { return false }
+ change.removed = getBetween(doc, change.from, change.to);
- // For big changes, we hide the enclosing element during the
- // update, since that speeds up the operations on most browsers.
- var focused = activeElt();
- if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
- patchDisplay(cm, display.updateLineNumbers, update.dims);
- if (toUpdate > 4) { display.lineDiv.style.display = ""; }
- display.renderedView = display.view;
- // There might have been a widget with a focused element that got
- // hidden or updated, if so re-focus it.
- if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus(); }
+ if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
+ if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
+ else { updateDoc(doc, change, spans); }
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+ }
- // Prevent selection and cursors from interfering with the scroll
- // width and height.
- removeChildren(display.cursorDiv);
- removeChildren(display.selectionDiv);
- display.gutters.style.height = display.sizer.style.minHeight = 0;
+ // Handle the interaction of a change to a document with the editor
+ // that this document is part of.
+ function makeChangeSingleDocInEditor(cm, change, spans) {
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
- if (different) {
- display.lastWrapHeight = update.wrapperHeight;
- display.lastWrapWidth = update.wrapperWidth;
- startWorker(cm, 400);
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
+ doc.iter(checkWidthStart, to.line + 1, function (line) {
+ if (line == display.maxLine) {
+ recomputeMaxLength = true;
+ return true
+ }
+ });
}
- display.updateLineNumbers = null;
-
- return true
- }
+ if (doc.sel.contains(change.from, change.to) > -1)
+ { signalCursorActivity(cm); }
- function postUpdateDisplay(cm, update) {
- var viewport = update.viewport;
+ updateDoc(doc, change, spans, estimateHeight(cm));
- for (var first = true;; first = false) {
- if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
- // Clip forced viewport to actual scrollable area.
- if (viewport && viewport.top != null)
- { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
- // Updated line heights might result in the drawn area not
- // actually covering the viewport. Keep looping until it does.
- update.visible = visibleLines(cm.display, cm.doc, viewport);
- if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
- { break }
- }
- if (!updateDisplayIfNeeded(cm, update)) { break }
- updateHeightsInViewport(cm);
- var barMeasure = measureForScrollbars(cm);
- updateSelection(cm);
- updateScrollbars(cm, barMeasure);
- setDocumentHeight(cm, barMeasure);
+ if (!cm.options.lineWrapping) {
+ doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
+ var len = lineLength(line);
+ if (len > display.maxLineLength) {
+ display.maxLine = line;
+ display.maxLineLength = len;
+ display.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
}
- update.signal(cm, "update", cm);
- if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
- update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
- cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
+ retreatFrontier(doc, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = change.text.length - (to.line - from.line) - 1;
+ // Remember that these lines changed, for updating the display
+ if (change.full)
+ { regChange(cm); }
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
+ { regLineChange(cm, from.line, "text"); }
+ else
+ { regChange(cm, from.line, to.line + 1, lendiff); }
+
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
+ if (changeHandler || changesHandler) {
+ var obj = {
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ };
+ if (changeHandler) { signalLater(cm, "change", cm, obj); }
+ if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
}
+ cm.display.selForContextMenu = null;
}
- function updateDisplaySimple(cm, viewport) {
- var update = new DisplayUpdate(cm, viewport);
- if (updateDisplayIfNeeded(cm, update)) {
- updateHeightsInViewport(cm);
- postUpdateDisplay(cm, update);
- var barMeasure = measureForScrollbars(cm);
- updateSelection(cm);
- updateScrollbars(cm, barMeasure);
- setDocumentHeight(cm, barMeasure);
- update.finish();
- }
+ function replaceRange(doc, code, from, to, origin) {
+ if (!to) { to = from; }
+ if (cmp(to, from) < 0) { var assign;
+ (assign = [to, from], from = assign[0], to = assign[1], assign); }
+ if (typeof code == "string") { code = doc.splitLines(code); }
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
}
- // Sync the actual display DOM structure with display.view, removing
- // nodes for lines that are no longer in view, and creating the ones
- // that are not there yet, and updating the ones that are out of
- // date.
- function patchDisplay(cm, updateNumbersFrom, dims) {
- var display = cm.display, lineNumbers = cm.options.lineNumbers;
- var container = display.lineDiv, cur = container.firstChild;
+ // Rebasing/resetting history to deal with externally-sourced changes
- function rm(node) {
- var next = node.nextSibling;
- // Works around a throw-scroll bug in OS X Webkit
- if (webkit && mac && cm.display.currentWheelTarget == node)
- { node.style.display = "none"; }
- else
- { node.parentNode.removeChild(node); }
- return next
+ function rebaseHistSelSingle(pos, from, to, diff) {
+ if (to < pos.line) {
+ pos.line += diff;
+ } else if (from < pos.line) {
+ pos.line = from;
+ pos.ch = 0;
}
+ }
- var view = display.view, lineN = display.viewFrom;
- // Loop over the elements in the view, syncing cur (the DOM nodes
- // in display.lineDiv) with the view as we go.
- for (var i = 0; i < view.length; i++) {
- var lineView = view[i];
- if (lineView.hidden) {
- } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
- var node = buildLineElement(cm, lineView, lineN, dims);
- container.insertBefore(node, cur);
- } else { // Already drawn
- while (cur != lineView.node) { cur = rm(cur); }
- var updateNumber = lineNumbers && updateNumbersFrom != null &&
- updateNumbersFrom <= lineN && lineView.lineNumber;
- if (lineView.changes) {
- if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
- updateLineForChanges(cm, lineView, lineN, dims);
+ // Tries to rebase an array of history events given a change in the
+ // document. If the change touches the same lines as the event, the
+ // event, and everything 'behind' it, is discarded. If the change is
+ // before the event, the event's positions are updated. Uses a
+ // copy-on-write scheme for the positions, to avoid having to
+ // reallocate them all on every rebase, but also avoid problems with
+ // shared position objects being unsafely updated.
+ function rebaseHistArray(array, from, to, diff) {
+ for (var i = 0; i < array.length; ++i) {
+ var sub = array[i], ok = true;
+ if (sub.ranges) {
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
+ for (var j = 0; j < sub.ranges.length; j++) {
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
}
- if (updateNumber) {
- removeChildren(lineView.lineNumber);
- lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
+ continue
+ }
+ for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
+ var cur = sub.changes[j$1];
+ if (to < cur.from.line) {
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
+ } else if (from <= cur.to.line) {
+ ok = false;
+ break
}
- cur = lineView.node.nextSibling;
}
- lineN += lineView.size;
+ if (!ok) {
+ array.splice(0, i + 1);
+ i = 0;
+ }
}
- while (cur) { cur = rm(cur); }
}
- function updateGutterSpace(cm) {
- var width = cm.display.gutters.offsetWidth;
- cm.display.sizer.style.marginLeft = width + "px";
+ function rebaseHist(hist, change) {
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+ rebaseHistArray(hist.done, from, to, diff);
+ rebaseHistArray(hist.undone, from, to, diff);
}
- function setDocumentHeight(cm, measure) {
- cm.display.sizer.style.minHeight = measure.docHeight + "px";
- cm.display.heightForcer.style.top = measure.docHeight + "px";
- cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
+ // Utility for applying a change to a line by handle or number,
+ // returning the number and optionally registering the line as
+ // changed.
+ function changeLine(doc, handle, changeType, op) {
+ var no = handle, line = handle;
+ if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
+ else { no = lineNo(handle); }
+ if (no == null) { return null }
+ if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
+ return line
}
- // Rebuild the gutter elements, ensure the margin to the left of the
- // code matches their width.
- function updateGutters(cm) {
- var gutters = cm.display.gutters, specs = cm.options.gutters;
- removeChildren(gutters);
- var i = 0;
- for (; i < specs.length; ++i) {
- var gutterClass = specs[i];
- var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
- if (gutterClass == "CodeMirror-linenumbers") {
- cm.display.lineGutter = gElt;
- gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
- }
- }
- gutters.style.display = i ? "" : "none";
- updateGutterSpace(cm);
- }
+ // The document is represented as a BTree consisting of leaves, with
+ // chunk of lines in them, and branches, with up to ten leaves or
+ // other branch nodes below them. The top node is always a branch
+ // node, and is the document object itself (meaning it has
+ // additional methods and properties).
+ //
+ // All nodes have parent links. The tree is used both to go from
+ // line numbers to line objects, and to go from objects to numbers.
+ // It also indexes by height, and is used to convert between height
+ // and line object, and to find the total height of the document.
+ //
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
- // Make sure the gutters options contains the element
- // "CodeMirror-linenumbers" when the lineNumbers option is true.
- function setGuttersForLineNumbers(options) {
- var found = indexOf(options.gutters, "CodeMirror-linenumbers");
- if (found == -1 && options.lineNumbers) {
- options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
- } else if (found > -1 && !options.lineNumbers) {
- options.gutters = options.gutters.slice(0);
- options.gutters.splice(found, 1);
+ function LeafChunk(lines) {
+ var this$1 = this;
+
+ this.lines = lines;
+ this.parent = null;
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) {
+ lines[i].parent = this$1;
+ height += lines[i].height;
}
+ this.height = height;
}
- // Selection objects are immutable. A new one is created every time
- // the selection changes. A selection is one or more non-overlapping
- // (and non-touching) ranges, sorted, and an integer that indicates
- // which one is the primary selection (the one that's scrolled into
- // view, that getCursor returns, etc).
- var Selection = function(ranges, primIndex) {
- this.ranges = ranges;
- this.primIndex = primIndex;
- };
-
- Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
+ LeafChunk.prototype = {
+ chunkSize: function chunkSize() { return this.lines.length },
- Selection.prototype.equals = function (other) {
+ // Remove the n lines at offset 'at'.
+ removeInner: function removeInner(at, n) {
var this$1 = this;
- if (other == this) { return true }
- if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
- for (var i = 0; i < this.ranges.length; i++) {
- var here = this$1.ranges[i], there = other.ranges[i];
- if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
- }
- return true
- };
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this$1.lines[i];
+ this$1.height -= line.height;
+ cleanUpLine(line);
+ signalLater(line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
- Selection.prototype.deepCopy = function () {
+ // Helper used to collapse a small branch into a single leaf.
+ collapse: function collapse(lines) {
+ lines.push.apply(lines, this.lines);
+ },
+
+ // Insert the given array of lines at offset 'at', count them as
+ // having the given height.
+ insertInner: function insertInner(at, lines, height) {
var this$1 = this;
- var out = [];
- for (var i = 0; i < this.ranges.length; i++)
- { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
- return new Selection(out, this.primIndex)
- };
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
+ },
- Selection.prototype.somethingSelected = function () {
+ // Used to iterate over a part of the tree.
+ iterN: function iterN(at, n, op) {
var this$1 = this;
- for (var i = 0; i < this.ranges.length; i++)
- { if (!this$1.ranges[i].empty()) { return true } }
- return false
+ for (var e = at + n; at < e; ++at)
+ { if (op(this$1.lines[at])) { return true } }
+ }
};
- Selection.prototype.contains = function (pos, end) {
- var this$1 = this;
+ function BranchChunk(children) {
+ var this$1 = this;
- if (!end) { end = pos; }
- for (var i = 0; i < this.ranges.length; i++) {
- var range = this$1.ranges[i];
- if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
- { return i }
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0; i < children.length; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this$1;
}
- return -1
- };
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+ }
- var Range = function(anchor, head) {
- this.anchor = anchor; this.head = head;
- };
+ BranchChunk.prototype = {
+ chunkSize: function chunkSize() { return this.size },
- Range.prototype.from = function () { return minPos(this.anchor, this.head) };
- Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
- Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
+ removeInner: function removeInner(at, n) {
+ var this$1 = this;
- // Take an unsorted, potentially overlapping set of ranges, and
- // build a selection out of it. 'Consumes' ranges array (modifying
- // it).
- function normalizeSelection(ranges, primIndex) {
- var prim = ranges[primIndex];
- ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
- primIndex = indexOf(ranges, prim);
- for (var i = 1; i < ranges.length; i++) {
- var cur = ranges[i], prev = ranges[i - 1];
- if (cmp(prev.to(), cur.from()) >= 0) {
- var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
- var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
- if (i <= primIndex) { --primIndex; }
- ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.removeInner(at, rm);
+ this$1.height -= oldHeight - child.height;
+ if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
+ }
+ // If the result is smaller than 25 lines, ensure that it is a
+ // single leaf node.
+ if (this.size - n < 25 &&
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
}
- }
- return new Selection(ranges, primIndex)
- }
+ },
- function simpleSelection(anchor, head) {
- return new Selection([new Range(anchor, head || anchor)], 0)
- }
+ collapse: function collapse(lines) {
+ var this$1 = this;
- // Compute the position of the end of a change (its 'to' property
- // refers to the pre-change end).
- function changeEnd(change) {
- if (!change.text) { return change.to }
- return Pos(change.from.line + change.text.length - 1,
- lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
- }
+ for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
+ },
- // Adjust a position to refer to the post-change position of the
- // same text, or the end of the change if the change covers it.
- function adjustForChange(pos, change) {
- if (cmp(pos, change.from) < 0) { return pos }
- if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
+ insertInner: function insertInner(at, lines, height) {
+ var this$1 = this;
- var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
- if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
- return Pos(line, ch)
- }
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertInner(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
+ // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
+ var remaining = child.lines.length % 25 + 25;
+ for (var pos = remaining; pos < child.lines.length;) {
+ var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
+ child.height -= leaf.height;
+ this$1.children.splice(++i, 0, leaf);
+ leaf.parent = this$1;
+ }
+ child.lines = child.lines.slice(0, remaining);
+ this$1.maybeSpill();
+ }
+ break
+ }
+ at -= sz;
+ }
+ },
- function computeSelAfterChange(doc, change) {
- var out = [];
- for (var i = 0; i < doc.sel.ranges.length; i++) {
- var range = doc.sel.ranges[i];
- out.push(new Range(adjustForChange(range.anchor, change),
- adjustForChange(range.head, change)));
- }
- return normalizeSelection(out, doc.sel.primIndex)
- }
+ // When a node has grown, check whether it should be split.
+ maybeSpill: function maybeSpill() {
+ if (this.children.length <= 10) { return }
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10)
+ me.parent.maybeSpill();
+ },
- function offsetPos(pos, old, nw) {
- if (pos.line == old.line)
- { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
- else
- { return Pos(nw.line + (pos.line - old.line), pos.ch) }
- }
+ iterN: function iterN(at, n, op) {
+ var this$1 = this;
- // Used by replaceSelections to allow moving the selection to the
- // start or around the replaced test. Hint may be "start" or "around".
- function computeReplacedSel(doc, changes, hint) {
- var out = [];
- var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
- var from = offsetPos(change.from, oldPrev, newPrev);
- var to = offsetPos(changeEnd(change), oldPrev, newPrev);
- oldPrev = change.to;
- newPrev = to;
- if (hint == "around") {
- var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
- out[i] = new Range(inv ? to : from, inv ? from : to);
- } else {
- out[i] = new Range(from, from);
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) { return true }
+ if ((n -= used) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
}
}
- return new Selection(out, doc.sel.primIndex)
- }
-
- // Used to get the editor into a consistent state again when options change.
+ };
- function loadMode(cm) {
- cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
- resetModeState(cm);
- }
+ // Line widgets are block elements displayed above or below a line.
- function resetModeState(cm) {
- cm.doc.iter(function (line) {
- if (line.stateAfter) { line.stateAfter = null; }
- if (line.styles) { line.styles = null; }
- });
- cm.doc.frontier = cm.doc.first;
- startWorker(cm, 100);
- cm.state.modeGen++;
- if (cm.curOp) { regChange(cm); }
- }
+ var LineWidget = function(doc, node, options) {
+ var this$1 = this;
- // DOCUMENT DATA STRUCTURE
+ if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
+ { this$1[opt] = options[opt]; } } }
+ this.doc = doc;
+ this.node = node;
+ };
- // By default, updates that start and end at the beginning of a line
- // are treated specially, in order to make the association of line
- // widgets and marker elements with the text behave more intuitive.
- function isWholeLineUpdate(doc, change) {
- return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
- (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
- }
+ LineWidget.prototype.clear = function () {
+ var this$1 = this;
- // Perform a change on the document data structure.
- function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
- function spansFor(n) {return markedSpans ? markedSpans[n] : null}
- function update(line, text, spans) {
- updateLine(line, text, spans, estimateHeight$$1);
- signalLater(line, "change", line, change);
- }
- function linesFor(start, end) {
- var result = [];
- for (var i = start; i < end; ++i)
- { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
- return result
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
+ if (no == null || !ws) { return }
+ for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
+ if (!ws.length) { line.widgets = null; }
+ var height = widgetHeight(this);
+ updateLineHeight(line, Math.max(0, line.height - height));
+ if (cm) {
+ runInOp(cm, function () {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ });
+ signalLater(cm, "lineWidgetCleared", cm, this, no);
}
+ };
- var from = change.from, to = change.to, text = change.text;
- var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
- var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+ LineWidget.prototype.changed = function () {
+ var this$1 = this;
- // Adjust the line structure
- if (change.full) {
- doc.insert(0, linesFor(0, text.length));
- doc.remove(text.length, doc.size - text.length);
- } else if (isWholeLineUpdate(doc, change)) {
- // This is a whole-line replace. Treated specially to make
- // sure line objects move the way they are supposed to.
- var added = linesFor(0, text.length - 1);
- update(lastLine, lastLine.text, lastSpans);
- if (nlines) { doc.remove(from.line, nlines); }
- if (added.length) { doc.insert(from.line, added); }
- } else if (firstLine == lastLine) {
- if (text.length == 1) {
- update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
- } else {
- var added$1 = linesFor(1, text.length - 1);
- added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
- doc.insert(from.line + 1, added$1);
- }
- } else if (text.length == 1) {
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
- doc.remove(from.line + 1, nlines);
- } else {
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
- update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
- var added$2 = linesFor(1, text.length - 1);
- if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
- doc.insert(from.line + 1, added$2);
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) { return }
+ updateLineHeight(line, line.height + diff);
+ if (cm) {
+ runInOp(cm, function () {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
+ });
}
+ };
+ eventMixin(LineWidget);
- signalLater(doc, "change", doc, change);
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ { addToScrollTop(cm, diff); }
}
- // Call f for all linked documents.
- function linkedDocs(doc, f, sharedHistOnly) {
- function propagate(doc, skip, sharedHist) {
- if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
- var rel = doc.linked[i];
- if (rel.doc == skip) { continue }
- var shared = sharedHist && rel.sharedHist;
- if (sharedHistOnly && !shared) { continue }
- f(rel.doc, shared);
- propagate(rel.doc, doc, shared);
- } }
- }
- propagate(doc, null, true);
+ function addLineWidget(doc, handle, node, options) {
+ var widget = new LineWidget(doc, node, options);
+ var cm = doc.cm;
+ if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
+ changeLine(doc, handle, "widget", function (line) {
+ var widgets = line.widgets || (line.widgets = []);
+ if (widget.insertAt == null) { widgets.push(widget); }
+ else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
+ widget.line = line;
+ if (cm && !lineIsHidden(doc, line)) {
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) { addToScrollTop(cm, widget.height); }
+ cm.curOp.forceUpdate = true;
+ }
+ return true
+ });
+ signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
+ return widget
}
- // Attach a document to an editor.
- function attachDoc(cm, doc) {
- if (doc.cm) { throw new Error("This document is already in use.") }
- cm.doc = doc;
- doc.cm = cm;
- estimateLineHeights(cm);
- loadMode(cm);
- setDirectionClass(cm);
- if (!cm.options.lineWrapping) { findMaxLine(cm); }
- cm.options.mode = doc.modeOption;
- regChange(cm);
- }
+ // TEXTMARKERS
- function setDirectionClass(cm) {
- (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
- }
+ // Created with markText and setBookmark methods. A TextMarker is a
+ // handle that can be used to clear or find a marked position in the
+ // document. Line objects hold arrays (markedSpans) containing
+ // {from, to, marker} object pointing to such marker objects, and
+ // indicating that such a marker is present on that line. Multiple
+ // lines may point to the same marker when it spans across lines.
+ // The spans will have null for their from/to properties when the
+ // marker continues beyond the start/end of the line. Markers have
+ // links back to the lines they currently touch.
- function directionChanged(cm) {
- runInOp(cm, function () {
- setDirectionClass(cm);
- regChange(cm);
- });
- }
+ // Collapsed markers have unique ids, in order to be able to order
+ // them, which is needed for uniquely determining an outer marker
+ // when they overlap (they may nest, but not partially overlap).
+ var nextMarkerId = 0;
- function History(startGen) {
- // Arrays of change events and selections. Doing something adds an
- // event to done and clears undo. Undoing moves events from done
- // to undone, redoing moves them in the other direction.
- this.done = []; this.undone = [];
- this.undoDepth = Infinity;
- // Used to track when changes can be merged into a single undo
- // event
- this.lastModTime = this.lastSelTime = 0;
- this.lastOp = this.lastSelOp = null;
- this.lastOrigin = this.lastSelOrigin = null;
- // Used by the isClean() method
- this.generation = this.maxGeneration = startGen || 1;
- }
+ var TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ this.id = ++nextMarkerId;
+ };
- // Create a history change event from an updateDoc-style change
- // object.
- function historyChangeFromChange(doc, change) {
- var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
- attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
- linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
- return histChange
- }
+ // Clear the marker.
+ TextMarker.prototype.clear = function () {
+ var this$1 = this;
- // Pop all selection events off the end of a history array. Stop at
- // a change event.
- function clearSelectionEvents(array) {
- while (array.length) {
- var last = lst(array);
- if (last.ranges) { array.pop(); }
- else { break }
+ if (this.explicitlyCleared) { return }
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
+ if (withOp) { startOperation(cm); }
+ if (hasHandler(this, "clear")) {
+ var found = this.find();
+ if (found) { signalLater(this, "clear", found.from, found.to); }
}
- }
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this$1.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this$1);
+ if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
+ else if (cm) {
+ if (span.to != null) { max = lineNo(line); }
+ if (span.from != null) { min = lineNo(line); }
+ }
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
+ { updateLineHeight(line, textHeight(cm.display)); }
+ }
+ if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
+ var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
+ if (len > cm.display.maxLineLength) {
+ cm.display.maxLine = visual;
+ cm.display.maxLineLength = len;
+ cm.display.maxLineChanged = true;
+ }
+ } }
- // Find the top change event in the history. Pop off selection
- // events that are in the way.
- function lastChangeEvent(hist, force) {
- if (force) {
- clearSelectionEvents(hist.done);
- return lst(hist.done)
- } else if (hist.done.length && !lst(hist.done).ranges) {
- return lst(hist.done)
- } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
- hist.done.pop();
- return lst(hist.done)
+ if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.atomic && this.doc.cantEdit) {
+ this.doc.cantEdit = false;
+ if (cm) { reCheckSelection(cm.doc); }
}
- }
+ if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
+ if (withOp) { endOperation(cm); }
+ if (this.parent) { this.parent.clear(); }
+ };
- // Register a change in the history. Merges changes that are within
- // a single operation, or are close together with an origin that
- // allows merging (starting with "+") into a single event.
- function addChangeToHistory(doc, change, selAfter, opId) {
- var hist = doc.history;
- hist.undone.length = 0;
- var time = +new Date, cur;
- var last;
+ // Find the position of the marker in the document. Returns a {from,
+ // to} object by default. Side can be passed to get a specific side
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+ // Pos objects returned contain a line object, rather than a line
+ // number (used to prevent looking up the same line twice).
+ TextMarker.prototype.find = function (side, lineObj) {
+ var this$1 = this;
- if ((hist.lastOp == opId ||
- hist.lastOrigin == change.origin && change.origin &&
- ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
- change.origin.charAt(0) == "*")) &&
- (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
- // Merge this change into the last event
- last = lst(cur.changes);
- if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
- // Optimized case for simple insertion -- don't want to add
- // new changesets for every character typed
- last.to = changeEnd(change);
- } else {
- // Add new sub-event
- cur.changes.push(historyChangeFromChange(doc, change));
+ if (side == null && this.type == "bookmark") { side = 1; }
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this$1.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this$1);
+ if (span.from != null) {
+ from = Pos(lineObj ? line : lineNo(line), span.from);
+ if (side == -1) { return from }
}
- } else {
- // Can not be merged, start a new event.
- var before = lst(hist.done);
- if (!before || !before.ranges)
- { pushSelectionToHistory(doc.sel, hist.done); }
- cur = {changes: [historyChangeFromChange(doc, change)],
- generation: hist.generation};
- hist.done.push(cur);
- while (hist.done.length > hist.undoDepth) {
- hist.done.shift();
- if (!hist.done[0].ranges) { hist.done.shift(); }
+ if (span.to != null) {
+ to = Pos(lineObj ? line : lineNo(line), span.to);
+ if (side == 1) { return to }
}
}
- hist.done.push(selAfter);
- hist.generation = ++hist.maxGeneration;
- hist.lastModTime = hist.lastSelTime = time;
- hist.lastOp = hist.lastSelOp = opId;
- hist.lastOrigin = hist.lastSelOrigin = change.origin;
+ return from && {from: from, to: to}
+ };
- if (!last) { signal(doc, "historyAdded"); }
- }
+ // Signals that the marker's widget changed, and surrounding layout
+ // should be recomputed.
+ TextMarker.prototype.changed = function () {
+ var this$1 = this;
- function selectionEventCanBeMerged(doc, origin, prev, sel) {
- var ch = origin.charAt(0);
- return ch == "*" ||
- ch == "+" &&
- prev.ranges.length == sel.ranges.length &&
- prev.somethingSelected() == sel.somethingSelected() &&
- new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
- }
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
+ if (!pos || !cm) { return }
+ runInOp(cm, function () {
+ var line = pos.line, lineN = lineNo(pos.line);
+ var view = findViewForLine(cm, lineN);
+ if (view) {
+ clearLineMeasurementCacheFor(view);
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
+ }
+ cm.curOp.updateMaxLine = true;
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
+ var oldHeight = widget.height;
+ widget.height = null;
+ var dHeight = widgetHeight(widget) - oldHeight;
+ if (dHeight)
+ { updateLineHeight(line, line.height + dHeight); }
+ }
+ signalLater(cm, "markerChanged", cm, this$1);
+ });
+ };
- // Called whenever the selection changes, sets the new selection as
- // the pending selection in the history, and pushes the old pending
- // selection into the 'done' array when it was significantly
- // different (in number of selected ranges, emptiness, or time).
- function addSelectionToHistory(doc, sel, opId, options) {
- var hist = doc.history, origin = options && options.origin;
+ TextMarker.prototype.attachLine = function (line) {
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+ { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
+ }
+ this.lines.push(line);
+ };
- // A new event is started when the previous origin does not match
- // the current, or the origins don't allow matching. Origins
- // starting with * are always merged, those starting with + are
- // merged when similar and close together in time.
- if (opId == hist.lastSelOp ||
- (origin && hist.lastSelOrigin == origin &&
- (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
- selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
- { hist.done[hist.done.length - 1] = sel; }
- else
- { pushSelectionToHistory(sel, hist.done); }
+ TextMarker.prototype.detachLine = function (line) {
+ this.lines.splice(indexOf(this.lines, line), 1);
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+ }
+ };
+ eventMixin(TextMarker);
- hist.lastSelTime = +new Date;
- hist.lastSelOrigin = origin;
- hist.lastSelOp = opId;
- if (options && options.clearRedo !== false)
- { clearSelectionEvents(hist.undone); }
- }
+ // Create a marker, wire it up to the right lines, and
+ function markText(doc, from, to, options, type) {
+ // Shared markers (across linked documents) are handled separately
+ // (markTextShared will call out to this again, once per
+ // document).
+ if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
+ // Ensure we are in an operation.
+ if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
- function pushSelectionToHistory(sel, dest) {
- var top = lst(dest);
- if (!(top && top.ranges && top.equals(sel)))
- { dest.push(sel); }
- }
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
+ if (options) { copyObj(options, marker, false); }
+ // Don't connect empty markers unless clearWhenEmpty is false
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
+ { return marker }
+ if (marker.replacedWith) {
+ // Showing up as a widget implies collapsed (widget replaces text)
+ marker.collapsed = true;
+ marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
+ if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
+ }
+ if (marker.collapsed) {
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
+ { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
+ seeCollapsedSpans();
+ }
- // Used to store marked span information in the history.
- function attachLocalSpans(doc, change, from, to) {
- var existing = change["spans_" + doc.id], n = 0;
- doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
- if (line.markedSpans)
- { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
- ++n;
+ if (marker.addToHistory)
+ { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
+
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
+ doc.iter(curLine, to.line + 1, function (line) {
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
+ { updateMaxLine = true; }
+ if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
+ addMarkedSpan(line, new MarkedSpan(marker,
+ curLine == from.line ? from.ch : null,
+ curLine == to.line ? to.ch : null));
+ ++curLine;
});
- }
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
+ if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
+ if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
+ }); }
- // When un/re-doing restores text containing marked spans, those
- // that have been explicitly cleared should not be restored.
- function removeClearedSpans(spans) {
- if (!spans) { return null }
- var out;
- for (var i = 0; i < spans.length; ++i) {
- if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
- else if (out) { out.push(spans[i]); }
- }
- return !out ? spans : out.length ? out : null
- }
+ if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
- // Retrieve and filter the old marked spans stored in a change event.
- function getOldSpans(doc, change) {
- var found = change["spans_" + doc.id];
- if (!found) { return null }
- var nw = [];
- for (var i = 0; i < change.text.length; ++i)
- { nw.push(removeClearedSpans(found[i])); }
- return nw
+ if (marker.readOnly) {
+ seeReadOnlySpans();
+ if (doc.history.done.length || doc.history.undone.length)
+ { doc.clearHistory(); }
+ }
+ if (marker.collapsed) {
+ marker.id = ++nextMarkerId;
+ marker.atomic = true;
+ }
+ if (cm) {
+ // Sync editor state
+ if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
+ if (marker.collapsed)
+ { regChange(cm, from.line, to.line + 1); }
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
+ { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
+ if (marker.atomic) { reCheckSelection(cm.doc); }
+ signalLater(cm, "markerAdded", cm, marker);
+ }
+ return marker
}
- // Used for un/re-doing changes from the history. Combines the
- // result of computing the existing spans with the set of spans that
- // existed in the history (so that deleting around a span and then
- // undoing brings back the span).
- function mergeOldSpans(doc, change) {
- var old = getOldSpans(doc, change);
- var stretched = stretchSpansOverChange(doc, change);
- if (!old) { return stretched }
- if (!stretched) { return old }
+ // SHARED TEXTMARKERS
- for (var i = 0; i < old.length; ++i) {
- var oldCur = old[i], stretchCur = stretched[i];
- if (oldCur && stretchCur) {
- spans: for (var j = 0; j < stretchCur.length; ++j) {
- var span = stretchCur[j];
- for (var k = 0; k < oldCur.length; ++k)
- { if (oldCur[k].marker == span.marker) { continue spans } }
- oldCur.push(span);
- }
- } else if (stretchCur) {
- old[i] = stretchCur;
- }
- }
- return old
- }
+ // A shared marker spans multiple linked documents. It is
+ // implemented as a meta-marker-object controlling multiple normal
+ // markers.
+ var SharedTextMarker = function(markers, primary) {
+ var this$1 = this;
- // Used both to provide a JSON-safe object in .getHistory, and, when
- // detaching a document, to split the history in two
- function copyHistoryArray(events, newGroup, instantiateSel) {
- var copy = [];
- for (var i = 0; i < events.length; ++i) {
- var event = events[i];
- if (event.ranges) {
- copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
- continue
- }
- var changes = event.changes, newChanges = [];
- copy.push({changes: newChanges});
- for (var j = 0; j < changes.length; ++j) {
- var change = changes[j], m = (void 0);
- newChanges.push({from: change.from, to: change.to, text: change.text});
- if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
- if (indexOf(newGroup, Number(m[1])) > -1) {
- lst(newChanges)[prop] = change[prop];
- delete change[prop];
- }
- } } }
- }
- }
- return copy
- }
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0; i < markers.length; ++i)
+ { markers[i].parent = this$1; }
+ };
- // The 'scroll' parameter given to many of these indicated whether
- // the new cursor position should be scrolled into view after
- // modifying the selection.
+ SharedTextMarker.prototype.clear = function () {
+ var this$1 = this;
- // If shift is held or the extend flag is set, extends a range to
- // include a given position (and optionally a second position).
- // Otherwise, simply returns the range between the given positions.
- // Used for cursor motion and such.
- function extendRange(doc, range, head, other) {
- if (doc.cm && doc.cm.display.shift || doc.extend) {
- var anchor = range.anchor;
- if (other) {
- var posBefore = cmp(head, anchor) < 0;
- if (posBefore != (cmp(other, anchor) < 0)) {
- anchor = head;
- head = other;
- } else if (posBefore != (cmp(head, other) < 0)) {
- head = other;
- }
- }
- return new Range(anchor, head)
- } else {
- return new Range(other || head, head)
- }
- }
+ if (this.explicitlyCleared) { return }
+ this.explicitlyCleared = true;
+ for (var i = 0; i < this.markers.length; ++i)
+ { this$1.markers[i].clear(); }
+ signalLater(this, "clear");
+ };
- // Extend the primary selection range, discard the rest.
- function extendSelection(doc, head, other, options) {
- setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
- }
+ SharedTextMarker.prototype.find = function (side, lineObj) {
+ return this.primary.find(side, lineObj)
+ };
+ eventMixin(SharedTextMarker);
- // Extend all selections (pos is an array of selections with length
- // equal the number of selections)
- function extendSelections(doc, heads, options) {
- var out = [];
- for (var i = 0; i < doc.sel.ranges.length; i++)
- { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); }
- var newSel = normalizeSelection(out, doc.sel.primIndex);
- setSelection(doc, newSel, options);
+ function markTextShared(doc, from, to, options, type) {
+ options = copyObj(options);
+ options.shared = false;
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+ var widget = options.widgetNode;
+ linkedDocs(doc, function (doc) {
+ if (widget) { options.widgetNode = widget.cloneNode(true); }
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+ for (var i = 0; i < doc.linked.length; ++i)
+ { if (doc.linked[i].isParent) { return } }
+ primary = lst(markers);
+ });
+ return new SharedTextMarker(markers, primary)
}
- // Updates a single range in the selection.
- function replaceOneSelection(doc, i, range, options) {
- var ranges = doc.sel.ranges.slice(0);
- ranges[i] = range;
- setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
+ function findSharedMarkers(doc) {
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
}
- // Reset the selection to a single range.
- function setSimpleSelection(doc, anchor, head, options) {
- setSelection(doc, simpleSelection(anchor, head), options);
+ function copySharedMarkers(doc, markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], pos = marker.find();
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
+ if (cmp(mFrom, mTo)) {
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
+ marker.markers.push(subMark);
+ subMark.parent = marker;
+ }
+ }
}
- // Give beforeSelectionChange handlers a change to influence a
- // selection update.
- function filterSelectionChange(doc, sel, options) {
- var obj = {
- ranges: sel.ranges,
- update: function(ranges) {
- var this$1 = this;
-
- this.ranges = [];
- for (var i = 0; i < ranges.length; i++)
- { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
- clipPos(doc, ranges[i].head)); }
- },
- origin: options && options.origin
+ function detachSharedMarkers(markers) {
+ var loop = function ( i ) {
+ var marker = markers[i], linked = [marker.primary.doc];
+ linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
+ for (var j = 0; j < marker.markers.length; j++) {
+ var subMarker = marker.markers[j];
+ if (indexOf(linked, subMarker.doc) == -1) {
+ subMarker.parent = null;
+ marker.markers.splice(j--, 1);
+ }
+ }
};
- signal(doc, "beforeSelectionChange", doc, obj);
- if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
- if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
- else { return sel }
- }
-
- function setSelectionReplaceHistory(doc, sel, options) {
- var done = doc.history.done, last = lst(done);
- if (last && last.ranges) {
- done[done.length - 1] = sel;
- setSelectionNoUndo(doc, sel, options);
- } else {
- setSelection(doc, sel, options);
- }
- }
- // Set a new selection.
- function setSelection(doc, sel, options) {
- setSelectionNoUndo(doc, sel, options);
- addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
+ for (var i = 0; i < markers.length; i++) loop( i );
}
- function setSelectionNoUndo(doc, sel, options) {
- if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
- { sel = filterSelectionChange(doc, sel, options); }
-
- var bias = options && options.bias ||
- (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
- setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
+ var nextDocId = 0;
+ var Doc = function(text, mode, firstLine, lineSep, direction) {
+ if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
+ if (firstLine == null) { firstLine = 0; }
- if (!(options && options.scroll === false) && doc.cm)
- { ensureCursorVisible(doc.cm); }
- }
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+ this.first = firstLine;
+ this.scrollTop = this.scrollLeft = 0;
+ this.cantEdit = false;
+ this.cleanGeneration = 1;
+ this.modeFrontier = this.highlightFrontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+ this.lineSep = lineSep;
+ this.direction = (direction == "rtl") ? "rtl" : "ltr";
+ this.extend = false;
- function setSelectionInner(doc, sel) {
- if (sel.equals(doc.sel)) { return }
+ if (typeof text == "string") { text = this.splitLines(text); }
+ updateDoc(this, {from: start, to: start, text: text});
+ setSelection(this, simpleSelection(start), sel_dontScroll);
+ };
- doc.sel = sel;
+ Doc.prototype = createObj(BranchChunk.prototype, {
+ constructor: Doc,
+ // Iterate over the document. Supports two forms -- with only one
+ // argument, it calls that for each line in the document. With
+ // three, it iterates over the range given by the first two (with
+ // the second being non-inclusive).
+ iter: function(from, to, op) {
+ if (op) { this.iterN(from - this.first, to - from, op); }
+ else { this.iterN(this.first, this.first + this.size, from); }
+ },
- if (doc.cm) {
- doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
- signalCursorActivity(doc.cm);
- }
- signalLater(doc, "cursorActivity", doc);
- }
+ // Non-public interface for adding and removing lines.
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
+ this.insertInner(at - this.first, lines, height);
+ },
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
- // Verify that the selection does not partially select any atomic
- // marked ranges.
- function reCheckSelection(doc) {
- setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
- }
+ // From here, the methods are part of the public interface. Most
+ // are also available from CodeMirror (editor) instances.
- // Return a selection that does not partially select any atomic
- // ranges.
- function skipAtomicInSelection(doc, sel, bias, mayClear) {
- var out;
- for (var i = 0; i < sel.ranges.length; i++) {
- var range = sel.ranges[i];
- var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
- var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
- var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
- if (out || newAnchor != range.anchor || newHead != range.head) {
- if (!out) { out = sel.ranges.slice(0, i); }
- out[i] = new Range(newAnchor, newHead);
- }
- }
- return out ? normalizeSelection(out, sel.primIndex) : sel
- }
+ getValue: function(lineSep) {
+ var lines = getLines(this, this.first, this.first + this.size);
+ if (lineSep === false) { return lines }
+ return lines.join(lineSep || this.lineSeparator())
+ },
+ setValue: docMethodOp(function(code) {
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
+ if (this.cm) { scrollToCoords(this.cm, 0, 0); }
+ setSelection(this, simpleSelection(top), sel_dontScroll);
+ }),
+ replaceRange: function(code, from, to, origin) {
+ from = clipPos(this, from);
+ to = to ? clipPos(this, to) : from;
+ replaceRange(this, code, from, to, origin);
+ },
+ getRange: function(from, to, lineSep) {
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+ if (lineSep === false) { return lines }
+ return lines.join(lineSep || this.lineSeparator())
+ },
- function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
- var line = getLine(doc, pos.line);
- if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
- var sp = line.markedSpans[i], m = sp.marker;
- if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
- (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
- if (mayClear) {
- signal(m, "beforeCursorEnter");
- if (m.explicitlyCleared) {
- if (!line.markedSpans) { break }
- else {--i; continue}
- }
- }
- if (!m.atomic) { continue }
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
- if (oldPos) {
- var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
- if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
- { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
- if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
- { return skipAtomicInner(doc, near, pos, dir, mayClear) }
- }
+ getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
+ getLineNumber: function(line) {return lineNo(line)},
- var far = m.find(dir < 0 ? -1 : 1);
- if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
- { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
- return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
- }
- } }
- return pos
- }
+ getLineHandleVisualStart: function(line) {
+ if (typeof line == "number") { line = getLine(this, line); }
+ return visualLine(line)
+ },
- // Ensure a given position is not inside an atomic range.
- function skipAtomic(doc, pos, oldPos, bias, mayClear) {
- var dir = bias || 1;
- var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
- (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
- skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
- (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
- if (!found) {
- doc.cantEdit = true;
- return Pos(doc.first, 0)
- }
- return found
- }
+ lineCount: function() {return this.size},
+ firstLine: function() {return this.first},
+ lastLine: function() {return this.first + this.size - 1},
- function movePos(doc, pos, dir, line) {
- if (dir < 0 && pos.ch == 0) {
- if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
- else { return null }
- } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
- if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
- else { return null }
- } else {
- return new Pos(pos.line, pos.ch + dir)
- }
- }
+ clipPos: function(pos) {return clipPos(this, pos)},
- function selectAll(cm) {
- cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
- }
+ getCursor: function(start) {
+ var range$$1 = this.sel.primary(), pos;
+ if (start == null || start == "head") { pos = range$$1.head; }
+ else if (start == "anchor") { pos = range$$1.anchor; }
+ else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
+ else { pos = range$$1.from(); }
+ return pos
+ },
+ listSelections: function() { return this.sel.ranges },
+ somethingSelected: function() {return this.sel.somethingSelected()},
- // UPDATING
+ setCursor: docMethodOp(function(line, ch, options) {
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
+ }),
+ setSelection: docMethodOp(function(anchor, head, options) {
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
+ }),
+ extendSelection: docMethodOp(function(head, other, options) {
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
+ }),
+ extendSelections: docMethodOp(function(heads, options) {
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ extendSelectionsBy: docMethodOp(function(f, options) {
+ var heads = map(this.sel.ranges, f);
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ var this$1 = this;
- // Allow "beforeChange" event handlers to influence a change
- function filterChange(doc, change, update) {
- var obj = {
- canceled: false,
- from: change.from,
- to: change.to,
- text: change.text,
- origin: change.origin,
- cancel: function () { return obj.canceled = true; }
- };
- if (update) { obj.update = function (from, to, text, origin) {
- if (from) { obj.from = clipPos(doc, from); }
- if (to) { obj.to = clipPos(doc, to); }
- if (text) { obj.text = text; }
- if (origin !== undefined) { obj.origin = origin; }
- }; }
- signal(doc, "beforeChange", doc, obj);
- if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
+ if (!ranges.length) { return }
+ var out = [];
+ for (var i = 0; i < ranges.length; i++)
+ { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
+ clipPos(this$1, ranges[i].head)); }
+ if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
+ setSelection(this, normalizeSelection(out, primary), options);
+ }),
+ addSelection: docMethodOp(function(anchor, head, options) {
+ var ranges = this.sel.ranges.slice(0);
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
+ }),
- if (obj.canceled) { return null }
- return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
- }
+ getSelection: function(lineSep) {
+ var this$1 = this;
- // Apply a change to a document, and add it to the document's
- // history, and propagating it to all linked documents.
- function makeChange(doc, change, ignoreReadOnly) {
- if (doc.cm) {
- if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
- if (doc.cm.state.suppressEdits) { return }
- }
+ var ranges = this.sel.ranges, lines;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
+ lines = lines ? lines.concat(sel) : sel;
+ }
+ if (lineSep === false) { return lines }
+ else { return lines.join(lineSep || this.lineSeparator()) }
+ },
+ getSelections: function(lineSep) {
+ var this$1 = this;
- if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
- change = filterChange(doc, change, true);
- if (!change) { return }
- }
+ var parts = [], ranges = this.sel.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
+ if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
+ parts[i] = sel;
+ }
+ return parts
+ },
+ replaceSelection: function(code, collapse, origin) {
+ var dup = [];
+ for (var i = 0; i < this.sel.ranges.length; i++)
+ { dup[i] = code; }
+ this.replaceSelections(dup, collapse, origin || "+input");
+ },
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
+ var this$1 = this;
- // Possibly split or suppress the update based on the presence
- // of read-only spans in its range.
- var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
- if (split) {
- for (var i = split.length - 1; i >= 0; --i)
- { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); }
- } else {
- makeChangeInner(doc, change);
- }
- }
+ var changes = [], sel = this.sel;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range$$1 = sel.ranges[i];
+ changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
+ { makeChange(this$1, changes[i$1]); }
+ if (newSel) { setSelectionReplaceHistory(this, newSel); }
+ else if (this.cm) { ensureCursorVisible(this.cm); }
+ }),
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
- function makeChangeInner(doc, change) {
- if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
- var selAfter = computeSelAfterChange(doc, change);
- addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
+ setExtending: function(val) {this.extend = val;},
+ getExtending: function() {return this.extend},
- makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
- var rebased = [];
+ historySize: function() {
+ var hist = this.history, done = 0, undone = 0;
+ for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
+ for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
+ return {undo: done, redo: undone}
+ },
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
- linkedDocs(doc, function (doc, sharedHist) {
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
- rebaseHist(doc.history, change);
- rebased.push(doc.history);
- }
- makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
- });
- }
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
+ return this.history.generation
+ },
+ isClean: function (gen) {
+ return this.history.generation == (gen || this.cleanGeneration)
+ },
- // Revert a change stored in a document's history.
- function makeChangeFromHistory(doc, type, allowSelectionOnly) {
- if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
+ getHistory: function() {
+ return {done: copyHistoryArray(this.history.done),
+ undone: copyHistoryArray(this.history.undone)}
+ },
+ setHistory: function(histData) {
+ var hist = this.history = new History(this.history.maxGeneration);
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
+ },
- var hist = doc.history, event, selAfter = doc.sel;
- var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
+ setGutterMarker: docMethodOp(function(line, gutterID, value) {
+ return changeLine(this, line, "gutter", function (line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
+ return true
+ })
+ }),
- // Verify that there is a useable event (so that ctrl-z won't
- // needlessly clear selection events)
- var i = 0;
- for (; i < source.length; i++) {
- event = source[i];
- if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
- { break }
- }
- if (i == source.length) { return }
- hist.lastOrigin = hist.lastSelOrigin = null;
+ clearGutter: docMethodOp(function(gutterID) {
+ var this$1 = this;
- for (;;) {
- event = source.pop();
- if (event.ranges) {
- pushSelectionToHistory(event, dest);
- if (allowSelectionOnly && !event.equals(doc.sel)) {
- setSelection(doc, event, {clearRedo: false});
- return
+ this.iter(function (line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ changeLine(this$1, line, "gutter", function () {
+ line.gutterMarkers[gutterID] = null;
+ if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
+ return true
+ });
}
- selAfter = event;
+ });
+ }),
+
+ lineInfo: function(line) {
+ var n;
+ if (typeof line == "number") {
+ if (!isLine(this, line)) { return null }
+ n = line;
+ line = getLine(this, line);
+ if (!line) { return null }
+ } else {
+ n = lineNo(line);
+ if (n == null) { return null }
}
- else { break }
- }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets}
+ },
- // Build up a reverse change object to add to the opposite history
- // stack (redo when undoing, and vice versa).
- var antiChanges = [];
- pushSelectionToHistory(selAfter, dest);
- dest.push({changes: antiChanges, generation: hist.generation});
- hist.generation = event.generation || ++hist.maxGeneration;
-
- var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
-
- var loop = function ( i ) {
- var change = event.changes[i];
- change.origin = type;
- if (filter && !filterChange(doc, change, false)) {
- source.length = 0;
- return {}
- }
+ addLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ if (!line[prop]) { line[prop] = cls; }
+ else if (classTest(cls).test(line[prop])) { return false }
+ else { line[prop] += " " + cls; }
+ return true
+ })
+ }),
+ removeLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) { return false }
+ else if (cls == null) { line[prop] = null; }
+ else {
+ var found = cur.match(classTest(cls));
+ if (!found) { return false }
+ var end = found.index + found[0].length;
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ }
+ return true
+ })
+ }),
- antiChanges.push(historyChangeFromChange(doc, change));
+ addLineWidget: docMethodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options)
+ }),
+ removeLineWidget: function(widget) { widget.clear(); },
- var after = i ? computeSelAfterChange(doc, change) : lst(source);
- makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
- if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
- var rebased = [];
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
+ },
+ setBookmark: function(pos, options) {
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+ insertLeft: options && options.insertLeft,
+ clearWhenEmpty: false, shared: options && options.shared,
+ handleMouseEvents: options && options.handleMouseEvents};
+ pos = clipPos(this, pos);
+ return markText(this, pos, pos, realOpts, "bookmark")
+ },
+ findMarksAt: function(pos) {
+ pos = clipPos(this, pos);
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ { markers.push(span.marker.parent || span.marker); }
+ } }
+ return markers
+ },
+ findMarks: function(from, to, filter) {
+ from = clipPos(this, from); to = clipPos(this, to);
+ var found = [], lineNo$$1 = from.line;
+ this.iter(from.line, to.line + 1, function (line) {
+ var spans = line.markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; i++) {
+ var span = spans[i];
+ if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
+ span.from == null && lineNo$$1 != from.line ||
+ span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
+ (!filter || filter(span.marker)))
+ { found.push(span.marker.parent || span.marker); }
+ } }
+ ++lineNo$$1;
+ });
+ return found
+ },
+ getAllMarks: function() {
+ var markers = [];
+ this.iter(function (line) {
+ var sps = line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i)
+ { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
+ });
+ return markers
+ },
- // Propagate to the linked documents
- linkedDocs(doc, function (doc, sharedHist) {
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
- rebaseHist(doc.history, change);
- rebased.push(doc.history);
- }
- makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ posFromIndex: function(off) {
+ var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
+ this.iter(function (line) {
+ var sz = line.text.length + sepSize;
+ if (sz > off) { ch = off; return true }
+ off -= sz;
+ ++lineNo$$1;
});
- };
+ return clipPos(this, Pos(lineNo$$1, ch))
+ },
+ indexFromPos: function (coords) {
+ coords = clipPos(this, coords);
+ var index = coords.ch;
+ if (coords.line < this.first || coords.ch < 0) { return 0 }
+ var sepSize = this.lineSeparator().length;
+ this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
+ index += line.text.length + sepSize;
+ });
+ return index
+ },
- for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
- var returned = loop( i$1 );
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
+ this.modeOption, this.first, this.lineSep, this.direction);
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+ doc.sel = this.sel;
+ doc.extend = false;
+ if (copyHistory) {
+ doc.history.undoDepth = this.history.undoDepth;
+ doc.setHistory(this.getHistory());
+ }
+ return doc
+ },
- if ( returned ) return returned.v;
- }
- }
+ linkedDoc: function(options) {
+ if (!options) { options = {}; }
+ var from = this.first, to = this.first + this.size;
+ if (options.from != null && options.from > from) { from = options.from; }
+ if (options.to != null && options.to < to) { to = options.to; }
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
+ if (options.sharedHist) { copy.history = this.history
+ ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+ copySharedMarkers(copy, findSharedMarkers(this));
+ return copy
+ },
+ unlinkDoc: function(other) {
+ var this$1 = this;
- // Sub-views need their line numbers shifted when text is added
- // above or below them in the parent document.
- function shiftDoc(doc, distance) {
- if (distance == 0) { return }
- doc.first += distance;
- doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
- Pos(range.anchor.line + distance, range.anchor.ch),
- Pos(range.head.line + distance, range.head.ch)
- ); }), doc.sel.primIndex);
- if (doc.cm) {
- regChange(doc.cm, doc.first, doc.first - distance, distance);
- for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
- { regLineChange(doc.cm, l, "gutter"); }
- }
- }
+ if (other instanceof CodeMirror$1) { other = other.doc; }
+ if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
+ var link = this$1.linked[i];
+ if (link.doc != other) { continue }
+ this$1.linked.splice(i, 1);
+ other.unlinkDoc(this$1);
+ detachSharedMarkers(findSharedMarkers(this$1));
+ break
+ } }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
+ other.history = new History(null);
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ }
+ },
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
- // More lower-level change function, handling only a single document
- // (not linked ones).
- function makeChangeSingleDoc(doc, change, selAfter, spans) {
- if (doc.cm && !doc.cm.curOp)
- { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
+ getMode: function() {return this.mode},
+ getEditor: function() {return this.cm},
- if (change.to.line < doc.first) {
- shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
- return
- }
- if (change.from.line > doc.lastLine()) { return }
+ splitLines: function(str) {
+ if (this.lineSep) { return str.split(this.lineSep) }
+ return splitLinesAuto(str)
+ },
+ lineSeparator: function() { return this.lineSep || "\n" },
- // Clip the change to the size of this doc
- if (change.from.line < doc.first) {
- var shift = change.text.length - 1 - (doc.first - change.from.line);
- shiftDoc(doc, shift);
- change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
- text: [lst(change.text)], origin: change.origin};
- }
- var last = doc.lastLine();
- if (change.to.line > last) {
- change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
- text: [change.text[0]], origin: change.origin};
- }
+ setDirection: docMethodOp(function (dir) {
+ if (dir != "rtl") { dir = "ltr"; }
+ if (dir == this.direction) { return }
+ this.direction = dir;
+ this.iter(function (line) { return line.order = null; });
+ if (this.cm) { directionChanged(this.cm); }
+ })
+ });
- change.removed = getBetween(doc, change.from, change.to);
+ // Public alias.
+ Doc.prototype.eachLine = Doc.prototype.iter;
- if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
- if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
- else { updateDoc(doc, change, spans); }
- setSelectionNoUndo(doc, selAfter, sel_dontScroll);
- }
+ // Kludge to work around strange IE behavior where it'll sometimes
+ // re-fire a series of drag-related events right after the drop (#1551)
+ var lastDrop = 0;
- // Handle the interaction of a change to a document with the editor
- // that this document is part of.
- function makeChangeSingleDocInEditor(cm, change, spans) {
- var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+ function onDrop(e) {
+ var cm = this;
+ clearDragCursor(cm);
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+ { return }
+ e_preventDefault(e);
+ if (ie) { lastDrop = +new Date; }
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || cm.isReadOnly()) { return }
+ // Might be a file drop, in which case we simply extract the text
+ // and insert it.
+ if (files && files.length && window.FileReader && window.File) {
+ var n = files.length, text = Array(n), read = 0;
+ var loadFile = function (file, i) {
+ if (cm.options.allowDropFileTypes &&
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
+ { return }
- var recomputeMaxLength = false, checkWidthStart = from.line;
- if (!cm.options.lineWrapping) {
- checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
- doc.iter(checkWidthStart, to.line + 1, function (line) {
- if (line == display.maxLine) {
- recomputeMaxLength = true;
- return true
+ var reader = new FileReader;
+ reader.onload = operation(cm, function () {
+ var content = reader.result;
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
+ text[i] = content;
+ if (++read == n) {
+ pos = clipPos(cm.doc, pos);
+ var change = {from: pos, to: pos,
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
+ origin: "paste"};
+ makeChange(cm.doc, change);
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
+ }
+ });
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
+ } else { // Normal drop
+ // Don't do a replace if the drop happened inside of the selected text.
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
+ cm.state.draggingText(e);
+ // Ensure the editor is re-focused
+ setTimeout(function () { return cm.display.input.focus(); }, 20);
+ return
+ }
+ try {
+ var text$1 = e.dataTransfer.getData("Text");
+ if (text$1) {
+ var selected;
+ if (cm.state.draggingText && !cm.state.draggingText.copy)
+ { selected = cm.listSelections(); }
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
+ if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
+ { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
+ cm.replaceSelection(text$1, "around", "paste");
+ cm.display.input.focus();
}
- });
+ }
+ catch(e){}
}
+ }
- if (doc.sel.contains(change.from, change.to) > -1)
- { signalCursorActivity(cm); }
+ function onDragStart(cm, e) {
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
- updateDoc(doc, change, spans, estimateHeight(cm));
+ e.dataTransfer.setData("Text", cm.getSelection());
+ e.dataTransfer.effectAllowed = "copyMove";
- if (!cm.options.lineWrapping) {
- doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
- var len = lineLength(line);
- if (len > display.maxLineLength) {
- display.maxLine = line;
- display.maxLineLength = len;
- display.maxLineChanged = true;
- recomputeMaxLength = false;
- }
- });
- if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
+ // Use dummy image instead of default browsers image.
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+ if (e.dataTransfer.setDragImage && !safari) {
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
+ if (presto) {
+ img.width = img.height = 1;
+ cm.display.wrapper.appendChild(img);
+ // Force a relayout, or Opera won't use our image for some obscure reason
+ img._top = img.offsetTop;
+ }
+ e.dataTransfer.setDragImage(img, 0, 0);
+ if (presto) { img.parentNode.removeChild(img); }
}
+ }
- // Adjust frontier, schedule worker
- doc.frontier = Math.min(doc.frontier, from.line);
- startWorker(cm, 400);
-
- var lendiff = change.text.length - (to.line - from.line) - 1;
- // Remember that these lines changed, for updating the display
- if (change.full)
- { regChange(cm); }
- else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
- { regLineChange(cm, from.line, "text"); }
- else
- { regChange(cm, from.line, to.line + 1, lendiff); }
-
- var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
- if (changeHandler || changesHandler) {
- var obj = {
- from: from, to: to,
- text: change.text,
- removed: change.removed,
- origin: change.origin
- };
- if (changeHandler) { signalLater(cm, "change", cm, obj); }
- if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
+ function onDragOver(cm, e) {
+ var pos = posFromMouse(cm, e);
+ if (!pos) { return }
+ var frag = document.createDocumentFragment();
+ drawSelectionCursor(cm, pos, frag);
+ if (!cm.display.dragCursor) {
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
}
- cm.display.selForContextMenu = null;
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
}
- function replaceRange(doc, code, from, to, origin) {
- if (!to) { to = from; }
- if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
- if (typeof code == "string") { code = doc.splitLines(code); }
- makeChange(doc, {from: from, to: to, text: code, origin: origin});
+ function clearDragCursor(cm) {
+ if (cm.display.dragCursor) {
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
+ cm.display.dragCursor = null;
+ }
}
- // Rebasing/resetting history to deal with externally-sourced changes
+ // These must be handled carefully, because naively registering a
+ // handler for each editor will cause the editors to never be
+ // garbage collected.
- function rebaseHistSelSingle(pos, from, to, diff) {
- if (to < pos.line) {
- pos.line += diff;
- } else if (from < pos.line) {
- pos.line = from;
- pos.ch = 0;
+ function forEachCodeMirror(f) {
+ if (!document.getElementsByClassName) { return }
+ var byClass = document.getElementsByClassName("CodeMirror");
+ for (var i = 0; i < byClass.length; i++) {
+ var cm = byClass[i].CodeMirror;
+ if (cm) { f(cm); }
}
}
- // Tries to rebase an array of history events given a change in the
- // document. If the change touches the same lines as the event, the
- // event, and everything 'behind' it, is discarded. If the change is
- // before the event, the event's positions are updated. Uses a
- // copy-on-write scheme for the positions, to avoid having to
- // reallocate them all on every rebase, but also avoid problems with
- // shared position objects being unsafely updated.
- function rebaseHistArray(array, from, to, diff) {
- for (var i = 0; i < array.length; ++i) {
- var sub = array[i], ok = true;
- if (sub.ranges) {
- if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
- for (var j = 0; j < sub.ranges.length; j++) {
- rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
- rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
- }
- continue
- }
- for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
- var cur = sub.changes[j$1];
- if (to < cur.from.line) {
- cur.from = Pos(cur.from.line + diff, cur.from.ch);
- cur.to = Pos(cur.to.line + diff, cur.to.ch);
- } else if (from <= cur.to.line) {
- ok = false;
- break
- }
- }
- if (!ok) {
- array.splice(0, i + 1);
- i = 0;
- }
- }
+ var globalsRegistered = false;
+ function ensureGlobalHandlers() {
+ if (globalsRegistered) { return }
+ registerGlobalHandlers();
+ globalsRegistered = true;
}
-
- function rebaseHist(hist, change) {
- var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
- rebaseHistArray(hist.done, from, to, diff);
- rebaseHistArray(hist.undone, from, to, diff);
+ function registerGlobalHandlers() {
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ on(window, "resize", function () {
+ if (resizeTimer == null) { resizeTimer = setTimeout(function () {
+ resizeTimer = null;
+ forEachCodeMirror(onResize);
+ }, 100); }
+ });
+ // When the window loses focus, we want to show the editor as blurred
+ on(window, "blur", function () { return forEachCodeMirror(onBlur); });
}
-
- // Utility for applying a change to a line by handle or number,
- // returning the number and optionally registering the line as
- // changed.
- function changeLine(doc, handle, changeType, op) {
- var no = handle, line = handle;
- if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
- else { no = lineNo(handle); }
- if (no == null) { return null }
- if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
- return line
+ // Called when the window resizes
+ function onResize(cm) {
+ var d = cm.display;
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
+ { return }
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+ d.scrollbarsClipped = false;
+ cm.setSize();
}
- // The document is represented as a BTree consisting of leaves, with
- // chunk of lines in them, and branches, with up to ten leaves or
- // other branch nodes below them. The top node is always a branch
- // node, and is the document object itself (meaning it has
- // additional methods and properties).
- //
- // All nodes have parent links. The tree is used both to go from
- // line numbers to line objects, and to go from objects to numbers.
- // It also indexes by height, and is used to convert between height
- // and line object, and to find the total height of the document.
- //
- // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
-
- var LeafChunk = function(lines) {
- var this$1 = this;
-
- this.lines = lines;
- this.parent = null;
- var height = 0;
- for (var i = 0; i < lines.length; ++i) {
- lines[i].parent = this$1;
- height += lines[i].height;
- }
- this.height = height;
+ var keyNames = {
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
};
- LeafChunk.prototype.chunkSize = function () { return this.lines.length };
-
- // Remove the n lines at offset 'at'.
- LeafChunk.prototype.removeInner = function (at, n) {
- var this$1 = this;
-
- for (var i = at, e = at + n; i < e; ++i) {
- var line = this$1.lines[i];
- this$1.height -= line.height;
- cleanUpLine(line);
- signalLater(line, "delete");
- }
- this.lines.splice(at, n);
- };
+ // Number keys
+ for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
+ // Alphabetic keys
+ for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
+ // Function keys
+ for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
- // Helper used to collapse a small branch into a single leaf.
- LeafChunk.prototype.collapse = function (lines) {
- lines.push.apply(lines, this.lines);
- };
+ var keyMap = {};
- // Insert the given array of lines at offset 'at', count them as
- // having the given height.
- LeafChunk.prototype.insertInner = function (at, lines, height) {
- var this$1 = this;
-
- this.height += height;
- this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
- for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
+ keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
+ "Esc": "singleSelection"
};
-
- // Used to iterate over a part of the tree.
- LeafChunk.prototype.iterN = function (at, n, op) {
- var this$1 = this;
-
- for (var e = at + n; at < e; ++at)
- { if (op(this$1.lines[at])) { return true } }
+ // Note that the save and find-related commands aren't defined by
+ // default. User code or addons can define them. Unknown commands
+ // are simply ignored.
+ keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
+ fallthrough: "basic"
};
-
- var BranchChunk = function(children) {
- var this$1 = this;
-
- this.children = children;
- var size = 0, height = 0;
- for (var i = 0; i < children.length; ++i) {
- var ch = children[i];
- size += ch.chunkSize(); height += ch.height;
- ch.parent = this$1;
- }
- this.size = size;
- this.height = height;
- this.parent = null;
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
+ keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
+ "Ctrl-O": "openLine"
};
-
- BranchChunk.prototype.chunkSize = function () { return this.size };
-
- BranchChunk.prototype.removeInner = function (at, n) {
- var this$1 = this;
-
- this.size -= n;
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at < sz) {
- var rm = Math.min(n, sz - at), oldHeight = child.height;
- child.removeInner(at, rm);
- this$1.height -= oldHeight - child.height;
- if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
- if ((n -= rm) == 0) { break }
- at = 0;
- } else { at -= sz; }
- }
- // If the result is smaller than 25 lines, ensure that it is a
- // single leaf node.
- if (this.size - n < 25 &&
- (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
- var lines = [];
- this.collapse(lines);
- this.children = [new LeafChunk(lines)];
- this.children[0].parent = this;
- }
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
+ fallthrough: ["basic", "emacsy"]
};
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
- BranchChunk.prototype.collapse = function (lines) {
- var this$1 = this;
+ // KEYMAP DISPATCH
- for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
- };
+ function normalizeKeyName(name) {
+ var parts = name.split(/-(?!$)/);
+ name = parts[parts.length - 1];
+ var alt, ctrl, shift, cmd;
+ for (var i = 0; i < parts.length - 1; i++) {
+ var mod = parts[i];
+ if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
+ else if (/^a(lt)?$/i.test(mod)) { alt = true; }
+ else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
+ else if (/^s(hift)?$/i.test(mod)) { shift = true; }
+ else { throw new Error("Unrecognized modifier name: " + mod) }
+ }
+ if (alt) { name = "Alt-" + name; }
+ if (ctrl) { name = "Ctrl-" + name; }
+ if (cmd) { name = "Cmd-" + name; }
+ if (shift) { name = "Shift-" + name; }
+ return name
+ }
- BranchChunk.prototype.insertInner = function (at, lines, height) {
- var this$1 = this;
+ // This is a kludge to keep keymaps mostly working as raw objects
+ // (backwards compatibility) while at the same time support features
+ // like normalization and multi-stroke key bindings. It compiles a
+ // new normalized keymap, and then updates the old object to reflect
+ // this.
+ function normalizeKeyMap(keymap) {
+ var copy = {};
+ for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
+ var value = keymap[keyname];
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
+ if (value == "...") { delete keymap[keyname]; continue }
- this.size += lines.length;
- this.height += height;
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at <= sz) {
- child.insertInner(at, lines, height);
- if (child.lines && child.lines.length > 50) {
- // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
- // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
- var remaining = child.lines.length % 25 + 25;
- for (var pos = remaining; pos < child.lines.length;) {
- var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
- child.height -= leaf.height;
- this$1.children.splice(++i, 0, leaf);
- leaf.parent = this$1;
- }
- child.lines = child.lines.slice(0, remaining);
- this$1.maybeSpill();
+ var keys = map(keyname.split(" "), normalizeKeyName);
+ for (var i = 0; i < keys.length; i++) {
+ var val = (void 0), name = (void 0);
+ if (i == keys.length - 1) {
+ name = keys.join(" ");
+ val = value;
+ } else {
+ name = keys.slice(0, i + 1).join(" ");
+ val = "...";
}
- break
- }
- at -= sz;
- }
- };
-
- // When a node has grown, check whether it should be split.
- BranchChunk.prototype.maybeSpill = function () {
- if (this.children.length <= 10) { return }
- var me = this;
- do {
- var spilled = me.children.splice(me.children.length - 5, 5);
- var sibling = new BranchChunk(spilled);
- if (!me.parent) { // Become the parent node
- var copy = new BranchChunk(me.children);
- copy.parent = me;
- me.children = [copy, sibling];
- me = copy;
- } else {
- me.size -= sibling.size;
- me.height -= sibling.height;
- var myIndex = indexOf(me.parent.children, me);
- me.parent.children.splice(myIndex + 1, 0, sibling);
+ var prev = copy[name];
+ if (!prev) { copy[name] = val; }
+ else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
}
- sibling.parent = me.parent;
- } while (me.children.length > 10)
- me.parent.maybeSpill();
- };
+ delete keymap[keyname];
+ } }
+ for (var prop in copy) { keymap[prop] = copy[prop]; }
+ return keymap
+ }
- BranchChunk.prototype.iterN = function (at, n, op) {
- var this$1 = this;
+ function lookupKey(key, map$$1, handle, context) {
+ map$$1 = getKeyMap(map$$1);
+ var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
+ if (found === false) { return "nothing" }
+ if (found === "...") { return "multi" }
+ if (found != null && handle(found)) { return "handled" }
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at < sz) {
- var used = Math.min(n, sz - at);
- if (child.iterN(at, used, op)) { return true }
- if ((n -= used) == 0) { break }
- at = 0;
- } else { at -= sz; }
+ if (map$$1.fallthrough) {
+ if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
+ { return lookupKey(key, map$$1.fallthrough, handle, context) }
+ for (var i = 0; i < map$$1.fallthrough.length; i++) {
+ var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
+ if (result) { return result }
+ }
}
- };
-
- // Line widgets are block elements displayed above or below a line.
-
- var LineWidget = function(doc, node, options) {
- var this$1 = this;
-
- if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
- { this$1[opt] = options[opt]; } } }
- this.doc = doc;
- this.node = node;
- };
-
- LineWidget.prototype.clear = function () {
- var this$1 = this;
+ }
- var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
- if (no == null || !ws) { return }
- for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
- if (!ws.length) { line.widgets = null; }
- var height = widgetHeight(this);
- updateLineHeight(line, Math.max(0, line.height - height));
- if (cm) {
- runInOp(cm, function () {
- adjustScrollWhenAboveVisible(cm, line, -height);
- regLineChange(cm, no, "widget");
- });
- signalLater(cm, "lineWidgetCleared", cm, this, no);
- }
- };
+ // Modifier key presses don't count as 'real' key presses for the
+ // purpose of keymap fallthrough.
+ function isModifierKey(value) {
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
+ }
- LineWidget.prototype.changed = function () {
- var this$1 = this;
+ function addModifierNames(name, event, noShift) {
+ var base = name;
+ if (event.altKey && base != "Alt") { name = "Alt-" + name; }
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
+ if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
+ return name
+ }
- var oldH = this.height, cm = this.doc.cm, line = this.line;
- this.height = null;
- var diff = widgetHeight(this) - oldH;
- if (!diff) { return }
- updateLineHeight(line, line.height + diff);
- if (cm) {
- runInOp(cm, function () {
- cm.curOp.forceUpdate = true;
- adjustScrollWhenAboveVisible(cm, line, diff);
- signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
- });
- }
- };
- eventMixin(LineWidget);
+ // Look up the name of a key as indicated by an event object.
+ function keyName(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) { return false }
+ var name = keyNames[event.keyCode];
+ if (name == null || event.altGraphKey) { return false }
+ return addModifierNames(name, event, noShift)
+ }
- function adjustScrollWhenAboveVisible(cm, line, diff) {
- if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
- { addToScrollPos(cm, null, diff); }
+ function getKeyMap(val) {
+ return typeof val == "string" ? keyMap[val] : val
}
- function addLineWidget(doc, handle, node, options) {
- var widget = new LineWidget(doc, node, options);
- var cm = doc.cm;
- if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
- changeLine(doc, handle, "widget", function (line) {
- var widgets = line.widgets || (line.widgets = []);
- if (widget.insertAt == null) { widgets.push(widget); }
- else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
- widget.line = line;
- if (cm && !lineIsHidden(doc, line)) {
- var aboveVisible = heightAtLine(line) < doc.scrollTop;
- updateLineHeight(line, line.height + widgetHeight(widget));
- if (aboveVisible) { addToScrollPos(cm, null, widget.height); }
- cm.curOp.forceUpdate = true;
+ // Helper for deleting text near the selection(s), used to implement
+ // backspace, delete, and similar functionality.
+ function deleteNearSelection(cm, compute) {
+ var ranges = cm.doc.sel.ranges, kill = [];
+ // Build up a set of ranges to kill first, merging overlapping
+ // ranges.
+ for (var i = 0; i < ranges.length; i++) {
+ var toKill = compute(ranges[i]);
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
+ var replaced = kill.pop();
+ if (cmp(replaced.from, toKill.from) < 0) {
+ toKill.from = replaced.from;
+ break
+ }
}
- return true
+ kill.push(toKill);
+ }
+ // Next, remove those actual ranges.
+ runInOp(cm, function () {
+ for (var i = kill.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
+ ensureCursorVisible(cm);
});
- signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
- return widget
}
- // TEXTMARKERS
-
- // Created with markText and setBookmark methods. A TextMarker is a
- // handle that can be used to clear or find a marked position in the
- // document. Line objects hold arrays (markedSpans) containing
- // {from, to, marker} object pointing to such marker objects, and
- // indicating that such a marker is present on that line. Multiple
- // lines may point to the same marker when it spans across lines.
- // The spans will have null for their from/to properties when the
- // marker continues beyond the start/end of the line. Markers have
- // links back to the lines they currently touch.
-
- // Collapsed markers have unique ids, in order to be able to order
- // them, which is needed for uniquely determining an outer marker
- // when they overlap (they may nest, but not partially overlap).
- var nextMarkerId = 0;
-
- var TextMarker = function(doc, type) {
- this.lines = [];
- this.type = type;
- this.doc = doc;
- this.id = ++nextMarkerId;
- };
+ function moveCharLogically(line, ch, dir) {
+ var target = skipExtendingChars(line.text, ch + dir, dir);
+ return target < 0 || target > line.text.length ? null : target
+ }
- // Clear the marker.
- TextMarker.prototype.clear = function () {
- var this$1 = this;
+ function moveLogically(line, start, dir) {
+ var ch = moveCharLogically(line, start.ch, dir);
+ return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+ }
- if (this.explicitlyCleared) { return }
- var cm = this.doc.cm, withOp = cm && !cm.curOp;
- if (withOp) { startOperation(cm); }
- if (hasHandler(this, "clear")) {
- var found = this.find();
- if (found) { signalLater(this, "clear", found.from, found.to); }
- }
- var min = null, max = null;
- for (var i = 0; i < this.lines.length; ++i) {
- var line = this$1.lines[i];
- var span = getMarkedSpanFor(line.markedSpans, this$1);
- if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
- else if (cm) {
- if (span.to != null) { max = lineNo(line); }
- if (span.from != null) { min = lineNo(line); }
+ function endOfLine(visually, cm, lineObj, lineNo, dir) {
+ if (visually) {
+ var order = getOrder(lineObj, cm.doc.direction);
+ if (order) {
+ var part = dir < 0 ? lst(order) : order[0];
+ var moveInStorageOrder = (dir < 0) == (part.level == 1);
+ var sticky = moveInStorageOrder ? "after" : "before";
+ var ch;
+ // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
+ // it could be that the last bidi part is not on the last visual line,
+ // since visual lines contain content order-consecutive chunks.
+ // Thus, in rtl, we are looking for the first (content-order) character
+ // in the rtl chunk that is on the last line (that is, the same line
+ // as the last (content-order) character).
+ if (part.level > 0) {
+ var prep = prepareMeasureForLine(cm, lineObj);
+ ch = dir < 0 ? lineObj.text.length - 1 : 0;
+ var targetTop = measureCharPrepared(cm, prep, ch).top;
+ ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
+ if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
+ } else { ch = dir < 0 ? part.to : part.from; }
+ return new Pos(lineNo, ch, sticky)
}
- line.markedSpans = removeMarkedSpan(line.markedSpans, span);
- if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
- { updateLineHeight(line, textHeight(cm.display)); }
}
- if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
- var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
- if (len > cm.display.maxLineLength) {
- cm.display.maxLine = visual;
- cm.display.maxLineLength = len;
- cm.display.maxLineChanged = true;
- }
- } }
+ return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+ }
- if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
- this.lines.length = 0;
- this.explicitlyCleared = true;
- if (this.atomic && this.doc.cantEdit) {
- this.doc.cantEdit = false;
- if (cm) { reCheckSelection(cm.doc); }
+ function moveVisually(cm, line, start, dir) {
+ var bidi = getOrder(line, cm.doc.direction);
+ if (!bidi) { return moveLogically(line, start, dir) }
+ if (start.ch >= line.text.length) {
+ start.ch = line.text.length;
+ start.sticky = "before";
+ } else if (start.ch <= 0) {
+ start.ch = 0;
+ start.sticky = "after";
}
- if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
- if (withOp) { endOperation(cm); }
- if (this.parent) { this.parent.clear(); }
- };
-
- // Find the position of the marker in the document. Returns a {from,
- // to} object by default. Side can be passed to get a specific side
- // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
- // Pos objects returned contain a line object, rather than a line
- // number (used to prevent looking up the same line twice).
- TextMarker.prototype.find = function (side, lineObj) {
- var this$1 = this;
-
- if (side == null && this.type == "bookmark") { side = 1; }
- var from, to;
- for (var i = 0; i < this.lines.length; ++i) {
- var line = this$1.lines[i];
- var span = getMarkedSpanFor(line.markedSpans, this$1);
- if (span.from != null) {
- from = Pos(lineObj ? line : lineNo(line), span.from);
- if (side == -1) { return from }
- }
- if (span.to != null) {
- to = Pos(lineObj ? line : lineNo(line), span.to);
- if (side == 1) { return to }
- }
+ var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
+ if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
+ // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
+ // nothing interesting happens.
+ return moveLogically(line, start, dir)
}
- return from && {from: from, to: to}
- };
- // Signals that the marker's widget changed, and surrounding layout
- // should be recomputed.
- TextMarker.prototype.changed = function () {
- var this$1 = this;
+ var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
+ var prep;
+ var getWrappedLineExtent = function (ch) {
+ if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
+ prep = prep || prepareMeasureForLine(cm, line);
+ return wrappedLineExtentChar(cm, line, prep, ch)
+ };
+ var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
- var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
- if (!pos || !cm) { return }
- runInOp(cm, function () {
- var line = pos.line, lineN = lineNo(pos.line);
- var view = findViewForLine(cm, lineN);
- if (view) {
- clearLineMeasurementCacheFor(view);
- cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
- }
- cm.curOp.updateMaxLine = true;
- if (!lineIsHidden(widget.doc, line) && widget.height != null) {
- var oldHeight = widget.height;
- widget.height = null;
- var dHeight = widgetHeight(widget) - oldHeight;
- if (dHeight)
- { updateLineHeight(line, line.height + dHeight); }
+ if (cm.doc.direction == "rtl" || part.level == 1) {
+ var moveInStorageOrder = (part.level == 1) == (dir < 0);
+ var ch = mv(start, moveInStorageOrder ? 1 : -1);
+ if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
+ // Case 2: We move within an rtl part or in an rtl editor on the same visual line
+ var sticky = moveInStorageOrder ? "before" : "after";
+ return new Pos(start.line, ch, sticky)
}
- signalLater(cm, "markerChanged", cm, this$1);
- });
- };
-
- TextMarker.prototype.attachLine = function (line) {
- if (!this.lines.length && this.doc.cm) {
- var op = this.doc.cm.curOp;
- if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
- { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
- }
- this.lines.push(line);
- };
-
- TextMarker.prototype.detachLine = function (line) {
- this.lines.splice(indexOf(this.lines, line), 1);
- if (!this.lines.length && this.doc.cm) {
- var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
}
- };
- eventMixin(TextMarker);
-
- // Create a marker, wire it up to the right lines, and
- function markText(doc, from, to, options, type) {
- // Shared markers (across linked documents) are handled separately
- // (markTextShared will call out to this again, once per
- // document).
- if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
- // Ensure we are in an operation.
- if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
- var marker = new TextMarker(doc, type), diff = cmp(from, to);
- if (options) { copyObj(options, marker, false); }
- // Don't connect empty markers unless clearWhenEmpty is false
- if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
- { return marker }
- if (marker.replacedWith) {
- // Showing up as a widget implies collapsed (widget replaces text)
- marker.collapsed = true;
- marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
- if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
- if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
- }
- if (marker.collapsed) {
- if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
- from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
- { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
- seeCollapsedSpans();
- }
+ // Case 3: Could not move within this bidi part in this visual line, so leave
+ // the current bidi part
- if (marker.addToHistory)
- { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
+ var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
+ var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
+ ? new Pos(start.line, mv(ch, 1), "before")
+ : new Pos(start.line, ch, "after"); };
- var curLine = from.line, cm = doc.cm, updateMaxLine;
- doc.iter(curLine, to.line + 1, function (line) {
- if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
- { updateMaxLine = true; }
- if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
- addMarkedSpan(line, new MarkedSpan(marker,
- curLine == from.line ? from.ch : null,
- curLine == to.line ? to.ch : null));
- ++curLine;
- });
- // lineIsHidden depends on the presence of the spans, so needs a second pass
- if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
- if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
- }); }
+ for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
+ var part = bidi[partPos];
+ var moveInStorageOrder = (dir > 0) == (part.level != 1);
+ var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
+ if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
+ ch = moveInStorageOrder ? part.from : mv(part.to, -1);
+ if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
+ }
+ };
- if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
+ // Case 3a: Look for other bidi parts on the same visual line
+ var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
+ if (res) { return res }
- if (marker.readOnly) {
- seeReadOnlySpans();
- if (doc.history.done.length || doc.history.undone.length)
- { doc.clearHistory(); }
- }
- if (marker.collapsed) {
- marker.id = ++nextMarkerId;
- marker.atomic = true;
- }
- if (cm) {
- // Sync editor state
- if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
- if (marker.collapsed)
- { regChange(cm, from.line, to.line + 1); }
- else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
- { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
- if (marker.atomic) { reCheckSelection(cm.doc); }
- signalLater(cm, "markerAdded", cm, marker);
+ // Case 3b: Look for other bidi parts on the next visual line
+ var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
+ if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
+ res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
+ if (res) { return res }
}
- return marker
- }
- // SHARED TEXTMARKERS
+ // Case 4: Nowhere to move
+ return null
+ }
- // A shared marker spans multiple linked documents. It is
- // implemented as a meta-marker-object controlling multiple normal
- // markers.
- var SharedTextMarker = function(markers, primary) {
- var this$1 = this;
-
- this.markers = markers;
- this.primary = primary;
- for (var i = 0; i < markers.length; ++i)
- { markers[i].parent = this$1; }
+ // Commands are parameter-less actions that can be performed on an
+ // editor, mostly used for keybindings.
+ var commands = {
+ selectAll: selectAll,
+ singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
+ killLine: function (cm) { return deleteNearSelection(cm, function (range) {
+ if (range.empty()) {
+ var len = getLine(cm.doc, range.head.line).text.length;
+ if (range.head.ch == len && range.head.line < cm.lastLine())
+ { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
+ else
+ { return {from: range.head, to: Pos(range.head.line, len)} }
+ } else {
+ return {from: range.from(), to: range.to()}
+ }
+ }); },
+ deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
+ }); }); },
+ delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0), to: range.from()
+ }); }); },
+ delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
+ return {from: leftPos, to: range.from()}
+ }); },
+ delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ return {from: range.from(), to: rightPos }
+ }); },
+ undo: function (cm) { return cm.undo(); },
+ redo: function (cm) { return cm.redo(); },
+ undoSelection: function (cm) { return cm.undoSelection(); },
+ redoSelection: function (cm) { return cm.redoSelection(); },
+ goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
+ goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
+ goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
+ {origin: "+move", bias: -1}
+ ); },
+ goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
+ }, sel_move); },
+ goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div")
+ }, sel_move); },
+ goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
+ return pos
+ }, sel_move); },
+ goLineUp: function (cm) { return cm.moveV(-1, "line"); },
+ goLineDown: function (cm) { return cm.moveV(1, "line"); },
+ goPageUp: function (cm) { return cm.moveV(-1, "page"); },
+ goPageDown: function (cm) { return cm.moveV(1, "page"); },
+ goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
+ goCharRight: function (cm) { return cm.moveH(1, "char"); },
+ goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
+ goColumnRight: function (cm) { return cm.moveH(1, "column"); },
+ goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
+ goGroupRight: function (cm) { return cm.moveH(1, "group"); },
+ goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
+ goWordRight: function (cm) { return cm.moveH(1, "word"); },
+ delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
+ delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
+ delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
+ delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
+ delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
+ delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
+ indentAuto: function (cm) { return cm.indentSelection("smart"); },
+ indentMore: function (cm) { return cm.indentSelection("add"); },
+ indentLess: function (cm) { return cm.indentSelection("subtract"); },
+ insertTab: function (cm) { return cm.replaceSelection("\t"); },
+ insertSoftTab: function (cm) {
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].from();
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
+ spaces.push(spaceStr(tabSize - col % tabSize));
+ }
+ cm.replaceSelections(spaces);
+ },
+ defaultTab: function (cm) {
+ if (cm.somethingSelected()) { cm.indentSelection("add"); }
+ else { cm.execCommand("insertTab"); }
+ },
+ // Swap the two chars left and right of each selection's head.
+ // Move cursor behind the two swapped characters afterwards.
+ //
+ // Doesn't consider line feeds a character.
+ // Doesn't scan more than one line above to find a character.
+ // Doesn't do anything on an empty line.
+ // Doesn't do anything with non-empty selections.
+ transposeChars: function (cm) { return runInOp(cm, function () {
+ var ranges = cm.listSelections(), newSel = [];
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) { continue }
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (line) {
+ if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
+ if (cur.ch > 0) {
+ cur = new Pos(cur.line, cur.ch + 1);
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
+ } else if (cur.line > cm.doc.first) {
+ var prev = getLine(cm.doc, cur.line - 1).text;
+ if (prev) {
+ cur = new Pos(cur.line, 1);
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
+ prev.charAt(prev.length - 1),
+ Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
+ }
+ }
+ }
+ newSel.push(new Range(cur, cur));
+ }
+ cm.setSelections(newSel);
+ }); },
+ newlineAndIndent: function (cm) { return runInOp(cm, function () {
+ var sels = cm.listSelections();
+ for (var i = sels.length - 1; i >= 0; i--)
+ { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
+ sels = cm.listSelections();
+ for (var i$1 = 0; i$1 < sels.length; i$1++)
+ { cm.indentLine(sels[i$1].from().line, null, true); }
+ ensureCursorVisible(cm);
+ }); },
+ openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
+ toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
};
- SharedTextMarker.prototype.clear = function () {
- var this$1 = this;
- if (this.explicitlyCleared) { return }
- this.explicitlyCleared = true;
- for (var i = 0; i < this.markers.length; ++i)
- { this$1.markers[i].clear(); }
- signalLater(this, "clear");
- };
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, visual, lineN, 1)
+ }
+ function lineEnd(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLineEnd(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, line, lineN, -1)
+ }
+ function lineStartSmart(cm, pos) {
+ var start = lineStart(cm, pos.line);
+ var line = getLine(cm.doc, start.line);
+ var order = getOrder(line, cm.doc.direction);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
+ }
+ return start
+ }
- SharedTextMarker.prototype.find = function (side, lineObj) {
- return this.primary.find(side, lineObj)
- };
- eventMixin(SharedTextMarker);
+ // Run a handler that was bound to a key.
+ function doHandleBinding(cm, bound, dropShift) {
+ if (typeof bound == "string") {
+ bound = commands[bound];
+ if (!bound) { return false }
+ }
+ // Ensure previous input has been read, so that the handler sees a
+ // consistent view of the document
+ cm.display.input.ensurePolled();
+ var prevShift = cm.display.shift, done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ if (dropShift) { cm.display.shift = false; }
+ done = bound(cm) != Pass;
+ } finally {
+ cm.display.shift = prevShift;
+ cm.state.suppressEdits = false;
+ }
+ return done
+ }
- function markTextShared(doc, from, to, options, type) {
- options = copyObj(options);
- options.shared = false;
- var markers = [markText(doc, from, to, options, type)], primary = markers[0];
- var widget = options.widgetNode;
- linkedDocs(doc, function (doc) {
- if (widget) { options.widgetNode = widget.cloneNode(true); }
- markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
- for (var i = 0; i < doc.linked.length; ++i)
- { if (doc.linked[i].isParent) { return } }
- primary = lst(markers);
- });
- return new SharedTextMarker(markers, primary)
+ function lookupKeyForEditor(cm, name, handle) {
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
+ if (result) { return result }
+ }
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
+ || lookupKey(name, cm.options.keyMap, handle, cm)
}
- function findSharedMarkers(doc) {
- return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
+ // Note that, despite the name, this function is also used to check
+ // for bound mouse clicks.
+
+ var stopSeq = new Delayed;
+ function dispatchKey(cm, name, e, handle) {
+ var seq = cm.state.keySeq;
+ if (seq) {
+ if (isModifierKey(name)) { return "handled" }
+ stopSeq.set(50, function () {
+ if (cm.state.keySeq == seq) {
+ cm.state.keySeq = null;
+ cm.display.input.reset();
+ }
+ });
+ name = seq + " " + name;
+ }
+ var result = lookupKeyForEditor(cm, name, handle);
+
+ if (result == "multi")
+ { cm.state.keySeq = name; }
+ if (result == "handled")
+ { signalLater(cm, "keyHandled", cm, name, e); }
+
+ if (result == "handled" || result == "multi") {
+ e_preventDefault(e);
+ restartBlink(cm);
+ }
+
+ if (seq && !result && /\'$/.test(name)) {
+ e_preventDefault(e);
+ return true
+ }
+ return !!result
}
- function copySharedMarkers(doc, markers) {
- for (var i = 0; i < markers.length; i++) {
- var marker = markers[i], pos = marker.find();
- var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
- if (cmp(mFrom, mTo)) {
- var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
- marker.markers.push(subMark);
- subMark.parent = marker;
- }
+ // Handle a key from the keydown event.
+ function handleKeyBinding(cm, e) {
+ var name = keyName(e, true);
+ if (!name) { return false }
+
+ if (e.shiftKey && !cm.state.keySeq) {
+ // First try to resolve full name (including 'Shift-'). Failing
+ // that, see if there is a cursor-motion command (starting with
+ // 'go') bound to the keyname without 'Shift-'.
+ return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
+ || dispatchKey(cm, name, e, function (b) {
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+ { return doHandleBinding(cm, b) }
+ })
+ } else {
+ return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
}
}
- function detachSharedMarkers(markers) {
- var loop = function ( i ) {
- var marker = markers[i], linked = [marker.primary.doc];
- linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
- for (var j = 0; j < marker.markers.length; j++) {
- var subMarker = marker.markers[j];
- if (indexOf(linked, subMarker.doc) == -1) {
- subMarker.parent = null;
- marker.markers.splice(j--, 1);
- }
+ // Handle a key from the keypress event
+ function handleCharBinding(cm, e, ch) {
+ return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
+ }
+
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ cm.curOp.focus = activeElt();
+ if (signalDOMEvent(cm, e)) { return }
+ // IE does strange things with escape.
+ if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
+ var code = e.keyCode;
+ cm.display.shift = code == 16 || e.shiftKey;
+ var handled = handleKeyBinding(cm, e);
+ if (presto) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+ { cm.replaceSelection("", null, "cut"); }
+ }
+
+ // Turn mouse into crosshair when Alt is held on Mac.
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+ { showCrossHair(cm); }
+ }
+
+ function showCrossHair(cm) {
+ var lineDiv = cm.display.lineDiv;
+ addClass(lineDiv, "CodeMirror-crosshair");
+
+ function up(e) {
+ if (e.keyCode == 18 || !e.altKey) {
+ rmClass(lineDiv, "CodeMirror-crosshair");
+ off(document, "keyup", up);
+ off(document, "mouseover", up);
}
- };
+ }
+ on(document, "keyup", up);
+ on(document, "mouseover", up);
+ }
- for (var i = 0; i < markers.length; i++) loop( i );
+ function onKeyUp(e) {
+ if (e.keyCode == 16) { this.doc.sel.shift = false; }
+ signalDOMEvent(this, e);
}
- var nextDocId = 0;
- var Doc = function(text, mode, firstLine, lineSep, direction) {
- if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
- if (firstLine == null) { firstLine = 0; }
+ function onKeyPress(e) {
+ var cm = this;
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
+ var keyCode = e.keyCode, charCode = e.charCode;
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ // Some browsers fire keypress events for backspace
+ if (ch == "\x08") { return }
+ if (handleCharBinding(cm, e, ch)) { return }
+ cm.display.input.onKeyPress(e);
+ }
- BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
- this.first = firstLine;
- this.scrollTop = this.scrollLeft = 0;
- this.cantEdit = false;
- this.cleanGeneration = 1;
- this.frontier = firstLine;
- var start = Pos(firstLine, 0);
- this.sel = simpleSelection(start);
- this.history = new History(null);
- this.id = ++nextDocId;
- this.modeOption = mode;
- this.lineSep = lineSep;
- this.direction = (direction == "rtl") ? "rtl" : "ltr";
- this.extend = false;
+ var DOUBLECLICK_DELAY = 400;
- if (typeof text == "string") { text = this.splitLines(text); }
- updateDoc(this, {from: start, to: start, text: text});
- setSelection(this, simpleSelection(start), sel_dontScroll);
+ var PastClick = function(time, pos, button) {
+ this.time = time;
+ this.pos = pos;
+ this.button = button;
};
- Doc.prototype = createObj(BranchChunk.prototype, {
- constructor: Doc,
- // Iterate over the document. Supports two forms -- with only one
- // argument, it calls that for each line in the document. With
- // three, it iterates over the range given by the first two (with
- // the second being non-inclusive).
- iter: function(from, to, op) {
- if (op) { this.iterN(from - this.first, to - from, op); }
- else { this.iterN(this.first, this.first + this.size, from); }
- },
+ PastClick.prototype.compare = function (time, pos, button) {
+ return this.time + DOUBLECLICK_DELAY > time &&
+ cmp(pos, this.pos) == 0 && button == this.button
+ };
- // Non-public interface for adding and removing lines.
- insert: function(at, lines) {
- var height = 0;
- for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
- this.insertInner(at - this.first, lines, height);
- },
- remove: function(at, n) { this.removeInner(at - this.first, n); },
+ var lastClick;
+ var lastDoubleClick;
+ function clickRepeat(pos, button) {
+ var now = +new Date;
+ if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
+ lastClick = lastDoubleClick = null;
+ return "triple"
+ } else if (lastClick && lastClick.compare(now, pos, button)) {
+ lastDoubleClick = new PastClick(now, pos, button);
+ lastClick = null;
+ return "double"
+ } else {
+ lastClick = new PastClick(now, pos, button);
+ lastDoubleClick = null;
+ return "single"
+ }
+ }
- // From here, the methods are part of the public interface. Most
- // are also available from CodeMirror (editor) instances.
+ // A mouse down can be a single click, double click, triple click,
+ // start of selection drag, start of text drag, new cursor
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
+ // middle-click-paste. Or it might be a click on something we should
+ // not interfere with, such as a scrollbar or widget.
+ function onMouseDown(e) {
+ var cm = this, display = cm.display;
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
+ display.input.ensurePolled();
+ display.shift = e.shiftKey;
- getValue: function(lineSep) {
- var lines = getLines(this, this.first, this.first + this.size);
- if (lineSep === false) { return lines }
- return lines.join(lineSep || this.lineSeparator())
- },
- setValue: docMethodOp(function(code) {
- var top = Pos(this.first, 0), last = this.first + this.size - 1;
- makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
- text: this.splitLines(code), origin: "setValue", full: true}, true);
- if (this.cm) { this.cm.scrollTo(0, 0); }
- setSelection(this, simpleSelection(top), sel_dontScroll);
- }),
- replaceRange: function(code, from, to, origin) {
- from = clipPos(this, from);
- to = to ? clipPos(this, to) : from;
- replaceRange(this, code, from, to, origin);
- },
- getRange: function(from, to, lineSep) {
- var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
- if (lineSep === false) { return lines }
- return lines.join(lineSep || this.lineSeparator())
- },
+ if (eventInWidget(display, e)) {
+ if (!webkit) {
+ // Briefly turn off draggability, to allow widgets to do
+ // normal dragging things.
+ display.scroller.draggable = false;
+ setTimeout(function () { return display.scroller.draggable = true; }, 100);
+ }
+ return
+ }
+ if (clickInGutter(cm, e)) { return }
+ var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
+ window.focus();
- getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
+ // #3261: make sure, that we're not starting a second selection
+ if (button == 1 && cm.state.selectingText)
+ { cm.state.selectingText(e); }
- getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
- getLineNumber: function(line) {return lineNo(line)},
+ if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
- getLineHandleVisualStart: function(line) {
- if (typeof line == "number") { line = getLine(this, line); }
- return visualLine(line)
- },
+ if (button == 1) {
+ if (pos) { leftButtonDown(cm, pos, repeat, e); }
+ else if (e_target(e) == display.scroller) { e_preventDefault(e); }
+ } else if (button == 2) {
+ if (pos) { extendSelection(cm.doc, pos); }
+ setTimeout(function () { return display.input.focus(); }, 20);
+ } else if (button == 3) {
+ if (captureRightClick) { onContextMenu(cm, e); }
+ else { delayBlurEvent(cm); }
+ }
+ }
- lineCount: function() {return this.size},
- firstLine: function() {return this.first},
- lastLine: function() {return this.first + this.size - 1},
+ function handleMappedButton(cm, button, pos, repeat, event) {
+ var name = "Click";
+ if (repeat == "double") { name = "Double" + name; }
+ else if (repeat == "triple") { name = "Triple" + name; }
+ name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
- clipPos: function(pos) {return clipPos(this, pos)},
+ return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
+ if (typeof bound == "string") { bound = commands[bound]; }
+ if (!bound) { return false }
+ var done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ done = bound(cm, pos) != Pass;
+ } finally {
+ cm.state.suppressEdits = false;
+ }
+ return done
+ })
+ }
- getCursor: function(start) {
- var range$$1 = this.sel.primary(), pos;
- if (start == null || start == "head") { pos = range$$1.head; }
- else if (start == "anchor") { pos = range$$1.anchor; }
- else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
- else { pos = range$$1.from(); }
- return pos
- },
- listSelections: function() { return this.sel.ranges },
- somethingSelected: function() {return this.sel.somethingSelected()},
+ function configureMouse(cm, repeat, event) {
+ var option = cm.getOption("configureMouse");
+ var value = option ? option(cm, repeat, event) : {};
+ if (value.unit == null) {
+ var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
+ value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
+ }
+ if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
+ if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
+ if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
+ return value
+ }
- setCursor: docMethodOp(function(line, ch, options) {
- setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
- }),
- setSelection: docMethodOp(function(anchor, head, options) {
- setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
- }),
- extendSelection: docMethodOp(function(head, other, options) {
- extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
- }),
- extendSelections: docMethodOp(function(heads, options) {
- extendSelections(this, clipPosArray(this, heads), options);
- }),
- extendSelectionsBy: docMethodOp(function(f, options) {
- var heads = map(this.sel.ranges, f);
- extendSelections(this, clipPosArray(this, heads), options);
- }),
- setSelections: docMethodOp(function(ranges, primary, options) {
- var this$1 = this;
+ function leftButtonDown(cm, pos, repeat, event) {
+ if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
+ else { cm.curOp.focus = activeElt(); }
- if (!ranges.length) { return }
- var out = [];
- for (var i = 0; i < ranges.length; i++)
- { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
- clipPos(this$1, ranges[i].head)); }
- if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
- setSelection(this, normalizeSelection(out, primary), options);
- }),
- addSelection: docMethodOp(function(anchor, head, options) {
- var ranges = this.sel.ranges.slice(0);
- ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
- setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
- }),
+ var behavior = configureMouse(cm, repeat, event);
- getSelection: function(lineSep) {
- var this$1 = this;
+ var sel = cm.doc.sel, contained;
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
+ repeat == "single" && (contained = sel.contains(pos)) > -1 &&
+ (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
+ (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
+ { leftButtonStartDrag(cm, event, pos, behavior); }
+ else
+ { leftButtonSelect(cm, event, pos, behavior); }
+ }
- var ranges = this.sel.ranges, lines;
- for (var i = 0; i < ranges.length; i++) {
- var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
- lines = lines ? lines.concat(sel) : sel;
- }
- if (lineSep === false) { return lines }
- else { return lines.join(lineSep || this.lineSeparator()) }
- },
- getSelections: function(lineSep) {
- var this$1 = this;
-
- var parts = [], ranges = this.sel.ranges;
- for (var i = 0; i < ranges.length; i++) {
- var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
- if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
- parts[i] = sel;
+ // Start a text drag. When it ends, see if any dragging actually
+ // happen, and treat as a click if it didn't.
+ function leftButtonStartDrag(cm, event, pos, behavior) {
+ var display = cm.display, moved = false;
+ var dragEnd = operation(cm, function (e) {
+ if (webkit) { display.scroller.draggable = false; }
+ cm.state.draggingText = false;
+ off(document, "mouseup", dragEnd);
+ off(document, "mousemove", mouseMove);
+ off(display.scroller, "dragstart", dragStart);
+ off(display.scroller, "drop", dragEnd);
+ if (!moved) {
+ e_preventDefault(e);
+ if (!behavior.addNew)
+ { extendSelection(cm.doc, pos, null, null, behavior.extend); }
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
+ if (webkit || ie && ie_version == 9)
+ { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
+ else
+ { display.input.focus(); }
}
- return parts
- },
- replaceSelection: function(code, collapse, origin) {
- var dup = [];
- for (var i = 0; i < this.sel.ranges.length; i++)
- { dup[i] = code; }
- this.replaceSelections(dup, collapse, origin || "+input");
- },
- replaceSelections: docMethodOp(function(code, collapse, origin) {
- var this$1 = this;
+ });
+ var mouseMove = function(e2) {
+ moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
+ };
+ var dragStart = function () { return moved = true; };
+ // Let the drag handler handle this.
+ if (webkit) { display.scroller.draggable = true; }
+ cm.state.draggingText = dragEnd;
+ dragEnd.copy = !behavior.moveOnDrag;
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
+ on(document, "mouseup", dragEnd);
+ on(document, "mousemove", mouseMove);
+ on(display.scroller, "dragstart", dragStart);
+ on(display.scroller, "drop", dragEnd);
- var changes = [], sel = this.sel;
- for (var i = 0; i < sel.ranges.length; i++) {
- var range$$1 = sel.ranges[i];
- changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
- }
- var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
- for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
- { makeChange(this$1, changes[i$1]); }
- if (newSel) { setSelectionReplaceHistory(this, newSel); }
- else if (this.cm) { ensureCursorVisible(this.cm); }
- }),
- undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
- redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
- undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
- redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
+ delayBlurEvent(cm);
+ setTimeout(function () { return display.input.focus(); }, 20);
+ }
- setExtending: function(val) {this.extend = val;},
- getExtending: function() {return this.extend},
+ function rangeForUnit(cm, pos, unit) {
+ if (unit == "char") { return new Range(pos, pos) }
+ if (unit == "word") { return cm.findWordAt(pos) }
+ if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
+ var result = unit(cm, pos);
+ return new Range(result.from, result.to)
+ }
- historySize: function() {
- var hist = this.history, done = 0, undone = 0;
- for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
- for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
- return {undo: done, redo: undone}
- },
- clearHistory: function() {this.history = new History(this.history.maxGeneration);},
+ // Normal selection, as opposed to text dragging.
+ function leftButtonSelect(cm, event, start, behavior) {
+ var display = cm.display, doc = cm.doc;
+ e_preventDefault(event);
- markClean: function() {
- this.cleanGeneration = this.changeGeneration(true);
- },
- changeGeneration: function(forceSplit) {
- if (forceSplit)
- { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
- return this.history.generation
- },
- isClean: function (gen) {
- return this.history.generation == (gen || this.cleanGeneration)
- },
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
+ if (behavior.addNew && !behavior.extend) {
+ ourIndex = doc.sel.contains(start);
+ if (ourIndex > -1)
+ { ourRange = ranges[ourIndex]; }
+ else
+ { ourRange = new Range(start, start); }
+ } else {
+ ourRange = doc.sel.primary();
+ ourIndex = doc.sel.primIndex;
+ }
- getHistory: function() {
- return {done: copyHistoryArray(this.history.done),
- undone: copyHistoryArray(this.history.undone)}
- },
- setHistory: function(histData) {
- var hist = this.history = new History(this.history.maxGeneration);
- hist.done = copyHistoryArray(histData.done.slice(0), null, true);
- hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
- },
+ if (behavior.unit == "rectangle") {
+ if (!behavior.addNew) { ourRange = new Range(start, start); }
+ start = posFromMouse(cm, event, true, true);
+ ourIndex = -1;
+ } else {
+ var range$$1 = rangeForUnit(cm, start, behavior.unit);
+ if (behavior.extend)
+ { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
+ else
+ { ourRange = range$$1; }
+ }
- setGutterMarker: docMethodOp(function(line, gutterID, value) {
- return changeLine(this, line, "gutter", function (line) {
- var markers = line.gutterMarkers || (line.gutterMarkers = {});
- markers[gutterID] = value;
- if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
- return true
- })
- }),
+ if (!behavior.addNew) {
+ ourIndex = 0;
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
+ startSel = doc.sel;
+ } else if (ourIndex == -1) {
+ ourIndex = ranges.length;
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
+ {scroll: false, origin: "*mouse"});
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
+ {scroll: false, origin: "*mouse"});
+ startSel = doc.sel;
+ } else {
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
+ }
- clearGutter: docMethodOp(function(gutterID) {
- var this$1 = this;
+ var lastPos = start;
+ function extendTo(pos) {
+ if (cmp(lastPos, pos) == 0) { return }
+ lastPos = pos;
- this.iter(function (line) {
- if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
- changeLine(this$1, line, "gutter", function () {
- line.gutterMarkers[gutterID] = null;
- if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
- return true
- });
+ if (behavior.unit == "rectangle") {
+ var ranges = [], tabSize = cm.options.tabSize;
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
+ line <= end; line++) {
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
+ if (left == right)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
+ else if (text.length > leftPos)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
}
- });
- }),
-
- lineInfo: function(line) {
- var n;
- if (typeof line == "number") {
- if (!isLine(this, line)) { return null }
- n = line;
- line = getLine(this, line);
- if (!line) { return null }
+ if (!ranges.length) { ranges.push(new Range(start, start)); }
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
+ {origin: "*mouse", scroll: false});
+ cm.scrollIntoView(pos);
} else {
- n = lineNo(line);
- if (n == null) { return null }
- }
- return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
- textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
- widgets: line.widgets}
- },
-
- addLineClass: docMethodOp(function(handle, where, cls) {
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
- var prop = where == "text" ? "textClass"
- : where == "background" ? "bgClass"
- : where == "gutter" ? "gutterClass" : "wrapClass";
- if (!line[prop]) { line[prop] = cls; }
- else if (classTest(cls).test(line[prop])) { return false }
- else { line[prop] += " " + cls; }
- return true
- })
- }),
- removeLineClass: docMethodOp(function(handle, where, cls) {
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
- var prop = where == "text" ? "textClass"
- : where == "background" ? "bgClass"
- : where == "gutter" ? "gutterClass" : "wrapClass";
- var cur = line[prop];
- if (!cur) { return false }
- else if (cls == null) { line[prop] = null; }
- else {
- var found = cur.match(classTest(cls));
- if (!found) { return false }
- var end = found.index + found[0].length;
- line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ var oldRange = ourRange;
+ var range$$1 = rangeForUnit(cm, pos, behavior.unit);
+ var anchor = oldRange.anchor, head;
+ if (cmp(range$$1.anchor, anchor) > 0) {
+ head = range$$1.head;
+ anchor = minPos(oldRange.from(), range$$1.anchor);
+ } else {
+ head = range$$1.anchor;
+ anchor = maxPos(oldRange.to(), range$$1.head);
}
- return true
- })
- }),
-
- addLineWidget: docMethodOp(function(handle, node, options) {
- return addLineWidget(this, handle, node, options)
- }),
- removeLineWidget: function(widget) { widget.clear(); },
-
- markText: function(from, to, options) {
- return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
- },
- setBookmark: function(pos, options) {
- var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
- insertLeft: options && options.insertLeft,
- clearWhenEmpty: false, shared: options && options.shared,
- handleMouseEvents: options && options.handleMouseEvents};
- pos = clipPos(this, pos);
- return markText(this, pos, pos, realOpts, "bookmark")
- },
- findMarksAt: function(pos) {
- pos = clipPos(this, pos);
- var markers = [], spans = getLine(this, pos.line).markedSpans;
- if (spans) { for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if ((span.from == null || span.from <= pos.ch) &&
- (span.to == null || span.to >= pos.ch))
- { markers.push(span.marker.parent || span.marker); }
- } }
- return markers
- },
- findMarks: function(from, to, filter) {
- from = clipPos(this, from); to = clipPos(this, to);
- var found = [], lineNo$$1 = from.line;
- this.iter(from.line, to.line + 1, function (line) {
- var spans = line.markedSpans;
- if (spans) { for (var i = 0; i < spans.length; i++) {
- var span = spans[i];
- if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
- span.from == null && lineNo$$1 != from.line ||
- span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
- (!filter || filter(span.marker)))
- { found.push(span.marker.parent || span.marker); }
- } }
- ++lineNo$$1;
- });
- return found
- },
- getAllMarks: function() {
- var markers = [];
- this.iter(function (line) {
- var sps = line.markedSpans;
- if (sps) { for (var i = 0; i < sps.length; ++i)
- { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
- });
- return markers
- },
-
- posFromIndex: function(off) {
- var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
- this.iter(function (line) {
- var sz = line.text.length + sepSize;
- if (sz > off) { ch = off; return true }
- off -= sz;
- ++lineNo$$1;
- });
- return clipPos(this, Pos(lineNo$$1, ch))
- },
- indexFromPos: function (coords) {
- coords = clipPos(this, coords);
- var index = coords.ch;
- if (coords.line < this.first || coords.ch < 0) { return 0 }
- var sepSize = this.lineSeparator().length;
- this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
- index += line.text.length + sepSize;
- });
- return index
- },
-
- copy: function(copyHistory) {
- var doc = new Doc(getLines(this, this.first, this.first + this.size),
- this.modeOption, this.first, this.lineSep, this.direction);
- doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
- doc.sel = this.sel;
- doc.extend = false;
- if (copyHistory) {
- doc.history.undoDepth = this.history.undoDepth;
- doc.setHistory(this.getHistory());
+ var ranges$1 = startSel.ranges.slice(0);
+ ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
+ setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
}
- return doc
- },
+ }
- linkedDoc: function(options) {
- if (!options) { options = {}; }
- var from = this.first, to = this.first + this.size;
- if (options.from != null && options.from > from) { from = options.from; }
- if (options.to != null && options.to < to) { to = options.to; }
- var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
- if (options.sharedHist) { copy.history = this.history
- ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
- copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
- copySharedMarkers(copy, findSharedMarkers(this));
- return copy
- },
- unlinkDoc: function(other) {
- var this$1 = this;
+ var editorSize = display.wrapper.getBoundingClientRect();
+ // Used to ensure timeout re-tries don't fire when another extend
+ // happened in the meantime (clearTimeout isn't reliable -- at
+ // least on Chrome, the timeouts still happen even when cleared,
+ // if the clear happens after their scheduled firing time).
+ var counter = 0;
- if (other instanceof CodeMirror$1) { other = other.doc; }
- if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
- var link = this$1.linked[i];
- if (link.doc != other) { continue }
- this$1.linked.splice(i, 1);
- other.unlinkDoc(this$1);
- detachSharedMarkers(findSharedMarkers(this$1));
- break
- } }
- // If the histories were shared, split them again
- if (other.history == this.history) {
- var splitIds = [other.id];
- linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
- other.history = new History(null);
- other.history.done = copyHistoryArray(this.history.done, splitIds);
- other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ function extend(e) {
+ var curCount = ++counter;
+ var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
+ if (!cur) { return }
+ if (cmp(cur, lastPos) != 0) {
+ cm.curOp.focus = activeElt();
+ extendTo(cur);
+ var visible = visibleLines(display, doc);
+ if (cur.line >= visible.to || cur.line < visible.from)
+ { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
+ } else {
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+ if (outside) { setTimeout(operation(cm, function () {
+ if (counter != curCount) { return }
+ display.scroller.scrollTop += outside;
+ extend(e);
+ }), 50); }
}
- },
- iterLinkedDocs: function(f) {linkedDocs(this, f);},
-
- getMode: function() {return this.mode},
- getEditor: function() {return this.cm},
+ }
- splitLines: function(str) {
- if (this.lineSep) { return str.split(this.lineSep) }
- return splitLinesAuto(str)
- },
- lineSeparator: function() { return this.lineSep || "\n" },
+ function done(e) {
+ cm.state.selectingText = false;
+ counter = Infinity;
+ e_preventDefault(e);
+ display.input.focus();
+ off(document, "mousemove", move);
+ off(document, "mouseup", up);
+ doc.history.lastSelOrigin = null;
+ }
- setDirection: docMethodOp(function (dir) {
- if (dir != "rtl") { dir = "ltr"; }
- if (dir == this.direction) { return }
- this.direction = dir;
- this.iter(function (line) { return line.order = null; });
- if (this.cm) { directionChanged(this.cm); }
- })
- });
+ var move = operation(cm, function (e) {
+ if (!e_button(e)) { done(e); }
+ else { extend(e); }
+ });
+ var up = operation(cm, done);
+ cm.state.selectingText = up;
+ on(document, "mousemove", move);
+ on(document, "mouseup", up);
+ }
- // Public alias.
- Doc.prototype.eachLine = Doc.prototype.iter;
+ // Used when mouse-selecting to adjust the anchor to the proper side
+ // of a bidi jump depending on the visual position of the head.
+ function bidiSimplify(cm, range$$1) {
+ var anchor = range$$1.anchor;
+ var head = range$$1.head;
+ var anchorLine = getLine(cm.doc, anchor.line);
+ if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
+ var order = getOrder(anchorLine);
+ if (!order) { return range$$1 }
+ var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
+ if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
+ var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
+ if (boundary == 0 || boundary == order.length) { return range$$1 }
+
+ // Compute the relative visual position of the head compared to the
+ // anchor (<0 is to the left, >0 to the right)
+ var leftSide;
+ if (head.line != anchor.line) {
+ leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
+ } else {
+ var headIndex = getBidiPartAt(order, head.ch, head.sticky);
+ var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
+ if (headIndex == boundary - 1 || headIndex == boundary)
+ { leftSide = dir < 0; }
+ else
+ { leftSide = dir > 0; }
+ }
- // Kludge to work around strange IE behavior where it'll sometimes
- // re-fire a series of drag-related events right after the drop (#1551)
- var lastDrop = 0;
+ var usePart = order[boundary + (leftSide ? -1 : 0)];
+ var from = leftSide == (usePart.level == 1);
+ var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
+ return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
+ }
- function onDrop(e) {
- var cm = this;
- clearDragCursor(cm);
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
- { return }
- e_preventDefault(e);
- if (ie) { lastDrop = +new Date; }
- var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
- if (!pos || cm.isReadOnly()) { return }
- // Might be a file drop, in which case we simply extract the text
- // and insert it.
- if (files && files.length && window.FileReader && window.File) {
- var n = files.length, text = Array(n), read = 0;
- var loadFile = function (file, i) {
- if (cm.options.allowDropFileTypes &&
- indexOf(cm.options.allowDropFileTypes, file.type) == -1)
- { return }
- var reader = new FileReader;
- reader.onload = operation(cm, function () {
- var content = reader.result;
- if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
- text[i] = content;
- if (++read == n) {
- pos = clipPos(cm.doc, pos);
- var change = {from: pos, to: pos,
- text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
- origin: "paste"};
- makeChange(cm.doc, change);
- setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
- }
- });
- reader.readAsText(file);
- };
- for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
- } else { // Normal drop
- // Don't do a replace if the drop happened inside of the selected text.
- if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
- cm.state.draggingText(e);
- // Ensure the editor is re-focused
- setTimeout(function () { return cm.display.input.focus(); }, 20);
- return
- }
- try {
- var text$1 = e.dataTransfer.getData("Text");
- if (text$1) {
- var selected;
- if (cm.state.draggingText && !cm.state.draggingText.copy)
- { selected = cm.listSelections(); }
- setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
- if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
- { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
- cm.replaceSelection(text$1, "around", "paste");
- cm.display.input.focus();
- }
- }
- catch(e){}
+ // Determines whether an event happened in the gutter, and fires the
+ // handlers for the corresponding event.
+ function gutterEvent(cm, e, type, prevent) {
+ var mX, mY;
+ if (e.touches) {
+ mX = e.touches[0].clientX;
+ mY = e.touches[0].clientY;
+ } else {
+ try { mX = e.clientX; mY = e.clientY; }
+ catch(e) { return false }
}
- }
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
+ if (prevent) { e_preventDefault(e); }
- function onDragStart(cm, e) {
- if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
+ var display = cm.display;
+ var lineBox = display.lineDiv.getBoundingClientRect();
- e.dataTransfer.setData("Text", cm.getSelection());
- e.dataTransfer.effectAllowed = "copyMove";
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
+ mY -= lineBox.top - display.viewOffset;
- // Use dummy image instead of default browsers image.
- // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
- if (e.dataTransfer.setDragImage && !safari) {
- var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
- img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
- if (presto) {
- img.width = img.height = 1;
- cm.display.wrapper.appendChild(img);
- // Force a relayout, or Opera won't use our image for some obscure reason
- img._top = img.offsetTop;
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.doc, mY);
+ var gutter = cm.options.gutters[i];
+ signal(cm, type, cm, line, gutter, e);
+ return e_defaultPrevented(e)
}
- e.dataTransfer.setDragImage(img, 0, 0);
- if (presto) { img.parentNode.removeChild(img); }
- }
- }
-
- function onDragOver(cm, e) {
- var pos = posFromMouse(cm, e);
- if (!pos) { return }
- var frag = document.createDocumentFragment();
- drawSelectionCursor(cm, pos, frag);
- if (!cm.display.dragCursor) {
- cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
- cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
}
- removeChildrenAndAdd(cm.display.dragCursor, frag);
}
- function clearDragCursor(cm) {
- if (cm.display.dragCursor) {
- cm.display.lineSpace.removeChild(cm.display.dragCursor);
- cm.display.dragCursor = null;
- }
+ function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true)
}
- // These must be handled carefully, because naively registering a
- // handler for each editor will cause the editors to never be
- // garbage collected.
+ // CONTEXT MENU HANDLING
- function forEachCodeMirror(f) {
- if (!document.body.getElementsByClassName) { return }
- var byClass = document.body.getElementsByClassName("CodeMirror");
- for (var i = 0; i < byClass.length; i++) {
- var cm = byClass[i].CodeMirror;
- if (cm) { f(cm); }
- }
+ // To make the context menu work, we need to briefly unhide the
+ // textarea (making it as unobtrusive as possible) to let the
+ // right-click take effect on it.
+ function onContextMenu(cm, e) {
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
+ if (signalDOMEvent(cm, e, "contextmenu")) { return }
+ cm.display.input.onContextMenu(e);
}
- var globalsRegistered = false;
- function ensureGlobalHandlers() {
- if (globalsRegistered) { return }
- registerGlobalHandlers();
- globalsRegistered = true;
- }
- function registerGlobalHandlers() {
- // When the window resizes, we need to refresh active editors.
- var resizeTimer;
- on(window, "resize", function () {
- if (resizeTimer == null) { resizeTimer = setTimeout(function () {
- resizeTimer = null;
- forEachCodeMirror(onResize);
- }, 100); }
- });
- // When the window loses focus, we want to show the editor as blurred
- on(window, "blur", function () { return forEachCodeMirror(onBlur); });
+ function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) { return false }
+ return gutterEvent(cm, e, "gutterContextMenu", false)
}
- // Called when the window resizes
- function onResize(cm) {
- var d = cm.display;
- if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
- { return }
- // Might be a text scaling operation, clear size caches.
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
- d.scrollbarsClipped = false;
- cm.setSize();
+
+ function themeChanged(cm) {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+ clearCaches(cm);
}
- var keyNames = {
- 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
- 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
- 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
- 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
- 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
- 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
- 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
- 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
- };
+ var Init = {toString: function(){return "CodeMirror.Init"}};
- // Number keys
- for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
- // Alphabetic keys
- for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
- // Function keys
- for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
+ var defaults = {};
+ var optionHandlers = {};
- var keyMap = {};
+ function defineOptions(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
- keyMap.basic = {
- "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
- "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
- "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
- "Tab": "defaultTab", "Shift-Tab": "indentAuto",
- "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
- "Esc": "singleSelection"
- };
- // Note that the save and find-related commands aren't defined by
- // default. User code or addons can define them. Unknown commands
- // are simply ignored.
- keyMap.pcDefault = {
- "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
- "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
- "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
- "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
- "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
- "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
- "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
- fallthrough: "basic"
- };
- // Very basic readline/emacs-style bindings, which are standard on Mac.
- keyMap.emacsy = {
- "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
- "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
- "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
- "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
- "Ctrl-O": "openLine"
- };
- keyMap.macDefault = {
- "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
- "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
- "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
- "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
- "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
- "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
- "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
- fallthrough: ["basic", "emacsy"]
- };
- keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) { optionHandlers[name] =
+ notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
+ }
- // KEYMAP DISPATCH
+ CodeMirror.defineOption = option;
- function normalizeKeyName(name) {
- var parts = name.split(/-(?!$)/);
- name = parts[parts.length - 1];
- var alt, ctrl, shift, cmd;
- for (var i = 0; i < parts.length - 1; i++) {
- var mod = parts[i];
- if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
- else if (/^a(lt)?$/i.test(mod)) { alt = true; }
- else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
- else if (/^s(hift)?$/i.test(mod)) { shift = true; }
- else { throw new Error("Unrecognized modifier name: " + mod) }
- }
- if (alt) { name = "Alt-" + name; }
- if (ctrl) { name = "Ctrl-" + name; }
- if (cmd) { name = "Cmd-" + name; }
- if (shift) { name = "Shift-" + name; }
- return name
- }
+ // Passed to option handlers when there is no old value.
+ CodeMirror.Init = Init;
- // This is a kludge to keep keymaps mostly working as raw objects
- // (backwards compatibility) while at the same time support features
- // like normalization and multi-stroke key bindings. It compiles a
- // new normalized keymap, and then updates the old object to reflect
- // this.
- function normalizeKeyMap(keymap) {
- var copy = {};
- for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
- var value = keymap[keyname];
- if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
- if (value == "...") { delete keymap[keyname]; continue }
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function (cm, val) { return cm.setValue(val); }, true);
+ option("mode", null, function (cm, val) {
+ cm.doc.modeOption = val;
+ loadMode(cm);
+ }, true);
- var keys = map(keyname.split(" "), normalizeKeyName);
- for (var i = 0; i < keys.length; i++) {
- var val = (void 0), name = (void 0);
- if (i == keys.length - 1) {
- name = keys.join(" ");
- val = value;
- } else {
- name = keys.slice(0, i + 1).join(" ");
- val = "...";
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function (cm) {
+ resetModeState(cm);
+ clearCaches(cm);
+ regChange(cm);
+ }, true);
+ option("lineSeparator", null, function (cm, val) {
+ cm.doc.lineSep = val;
+ if (!val) { return }
+ var newBreaks = [], lineNo = cm.doc.first;
+ cm.doc.iter(function (line) {
+ for (var pos = 0;;) {
+ var found = line.text.indexOf(val, pos);
+ if (found == -1) { break }
+ pos = found + val.length;
+ newBreaks.push(Pos(lineNo, found));
}
- var prev = copy[name];
- if (!prev) { copy[name] = val; }
- else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
+ lineNo++;
+ });
+ for (var i = newBreaks.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
+ });
+ option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ if (old != Init) { cm.refresh(); }
+ });
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
+ option("electricChars", true);
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
+ throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
+ }, true);
+ option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function (cm) {
+ themeChanged(cm);
+ guttersChanged(cm);
+ }, true);
+ option("keyMap", "default", function (cm, val, old) {
+ var next = getKeyMap(val);
+ var prev = old != Init && getKeyMap(old);
+ if (prev && prev.detach) { prev.detach(cm, next); }
+ if (next.attach) { next.attach(cm, prev || null); }
+ });
+ option("extraKeys", null);
+ option("configureMouse", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function (cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("fixedGutter", true, function (cm, val) {
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+ cm.refresh();
+ }, true);
+ option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
+ option("scrollbarStyle", "native", function (cm) {
+ initScrollbars(cm);
+ updateScrollbars(cm);
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
+ }, true);
+ option("lineNumbers", false, function (cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("firstLineNumber", 1, guttersChanged, true);
+ option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+ option("lineWiseCopyCut", true);
+ option("pasteLinesPerSelection", true);
+
+ option("readOnly", false, function (cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
}
- delete keymap[keyname];
- } }
- for (var prop in copy) { keymap[prop] = copy[prop]; }
- return keymap
+ cm.display.input.readOnlyChanged(val);
+ });
+ option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
+ option("dragDrop", true, dragDropChanged);
+ option("allowDropFileTypes", null);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1, updateSelection, true);
+ option("singleCursorHeightPerLine", true, updateSelection, true);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true, resetModeState, true);
+ option("addModeClass", false, resetModeState, true);
+ option("pollInterval", 100);
+ option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function (cm, val) {
+ if (!val) { cm.display.input.resetPosition(); }
+ });
+
+ option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
+ option("autofocus", null);
+ option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
}
- function lookupKey(key, map$$1, handle, context) {
- map$$1 = getKeyMap(map$$1);
- var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
- if (found === false) { return "nothing" }
- if (found === "...") { return "multi" }
- if (found != null && handle(found)) { return "handled" }
+ function guttersChanged(cm) {
+ updateGutters(cm);
+ regChange(cm);
+ alignHorizontally(cm);
+ }
- if (map$$1.fallthrough) {
- if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
- { return lookupKey(key, map$$1.fallthrough, handle, context) }
- for (var i = 0; i < map$$1.fallthrough.length; i++) {
- var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
- if (result) { return result }
- }
+ function dragDropChanged(cm, value, old) {
+ var wasOn = old && old != Init;
+ if (!value != !wasOn) {
+ var funcs = cm.display.dragFunctions;
+ var toggle = value ? on : off;
+ toggle(cm.display.scroller, "dragstart", funcs.start);
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
+ toggle(cm.display.scroller, "dragover", funcs.over);
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
+ toggle(cm.display.scroller, "drop", funcs.drop);
}
}
- // Modifier key presses don't count as 'real' key presses for the
- // purpose of keymap fallthrough.
- function isModifierKey(value) {
- var name = typeof value == "string" ? value : keyNames[value.keyCode];
- return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
+ function wrappingChanged(cm) {
+ if (cm.options.lineWrapping) {
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
+ cm.display.sizer.style.minWidth = "";
+ cm.display.sizerWidth = null;
+ } else {
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
+ findMaxLine(cm);
+ }
+ estimateLineHeights(cm);
+ regChange(cm);
+ clearCaches(cm);
+ setTimeout(function () { return updateScrollbars(cm); }, 100);
}
- // Look up the name of a key as indicated by an event object.
- function keyName(event, noShift) {
- if (presto && event.keyCode == 34 && event["char"]) { return false }
- var base = keyNames[event.keyCode], name = base;
- if (name == null || event.altGraphKey) { return false }
- if (event.altKey && base != "Alt") { name = "Alt-" + name; }
- if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
- if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
- if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
- return name
- }
+ // A CodeMirror instance represents an editor. This is the object
+ // that user code is usually dealing with.
- function getKeyMap(val) {
- return typeof val == "string" ? keyMap[val] : val
+ function CodeMirror$1(place, options) {
+ var this$1 = this;
+
+ if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
+
+ this.options = options = options ? copyObj(options) : {};
+ // Determine effective options based on given values and defaults.
+ copyObj(defaults, options, false);
+ setGuttersForLineNumbers(options);
+
+ var doc = options.value;
+ if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
+ this.doc = doc;
+
+ var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
+ var display = this.display = new Display(place, doc, input);
+ display.wrapper.CodeMirror = this;
+ updateGutters(this);
+ themeChanged(this);
+ if (options.lineWrapping)
+ { this.display.wrapper.className += " CodeMirror-wrap"; }
+ initScrollbars(this);
+
+ this.state = {
+ keyMaps: [], // stores maps added by addKeyMap
+ overlays: [], // highlighting overlays, as added by addOverlay
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
+ overwrite: false,
+ delayingBlurEvent: false,
+ focused: false,
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
+ selectingText: false,
+ draggingText: false,
+ highlight: new Delayed(), // stores highlight worker timeout
+ keySeq: null, // Unfinished key sequence
+ specialChars: null
+ };
+
+ if (options.autofocus && !mobile) { display.input.focus(); }
+
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
+
+ registerEventHandlers(this);
+ ensureGlobalHandlers();
+
+ startOperation(this);
+ this.curOp.forceUpdate = true;
+ attachDoc(this, doc);
+
+ if ((options.autofocus && !mobile) || this.hasFocus())
+ { setTimeout(bind(onFocus, this), 20); }
+ else
+ { onBlur(this); }
+
+ for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
+ { optionHandlers[opt](this$1, options[opt], Init); } }
+ maybeUpdateLineNumberWidth(this);
+ if (options.finishInit) { options.finishInit(this); }
+ for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
+ endOperation(this);
+ // Suppress optimizelegibility in Webkit, since it breaks text
+ // measuring on line wrapping boundaries.
+ if (webkit && options.lineWrapping &&
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
+ { display.lineDiv.style.textRendering = "auto"; }
}
- // Helper for deleting text near the selection(s), used to implement
- // backspace, delete, and similar functionality.
- function deleteNearSelection(cm, compute) {
- var ranges = cm.doc.sel.ranges, kill = [];
- // Build up a set of ranges to kill first, merging overlapping
- // ranges.
- for (var i = 0; i < ranges.length; i++) {
- var toKill = compute(ranges[i]);
- while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
- var replaced = kill.pop();
- if (cmp(replaced.from, toKill.from) < 0) {
- toKill.from = replaced.from;
- break
- }
+ // The default configuration options.
+ CodeMirror$1.defaults = defaults;
+ // Functions to run when options are changed.
+ CodeMirror$1.optionHandlers = optionHandlers;
+
+ // Attach the necessary event handlers when initializing the editor
+ function registerEventHandlers(cm) {
+ var d = cm.display;
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
+ // Older IE's will not fire a second mousedown for a double click
+ if (ie && ie_version < 11)
+ { on(d.scroller, "dblclick", operation(cm, function (e) {
+ if (signalDOMEvent(cm, e)) { return }
+ var pos = posFromMouse(cm, e);
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
+ e_preventDefault(e);
+ var word = cm.findWordAt(pos);
+ extendSelection(cm.doc, word.anchor, word.head);
+ })); }
+ else
+ { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
+ // Some browsers fire contextmenu *after* opening the menu, at
+ // which point we can't mess with it anymore. Context menu is
+ // handled in onMouseDown for these browsers.
+ if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
+
+ // Used to suppress mouse event handling when a touch happens
+ var touchFinished, prevTouch = {end: 0};
+ function finishTouch() {
+ if (d.activeTouch) {
+ touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
+ prevTouch = d.activeTouch;
+ prevTouch.end = +new Date;
}
- kill.push(toKill);
}
- // Next, remove those actual ranges.
- runInOp(cm, function () {
- for (var i = kill.length - 1; i >= 0; i--)
- { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
- ensureCursorVisible(cm);
+ function isMouseLikeTouchEvent(e) {
+ if (e.touches.length != 1) { return false }
+ var touch = e.touches[0];
+ return touch.radiusX <= 1 && touch.radiusY <= 1
+ }
+ function farAway(touch, other) {
+ if (other.left == null) { return true }
+ var dx = other.left - touch.left, dy = other.top - touch.top;
+ return dx * dx + dy * dy > 20 * 20
+ }
+ on(d.scroller, "touchstart", function (e) {
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
+ d.input.ensurePolled();
+ clearTimeout(touchFinished);
+ var now = +new Date;
+ d.activeTouch = {start: now, moved: false,
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
+ if (e.touches.length == 1) {
+ d.activeTouch.left = e.touches[0].pageX;
+ d.activeTouch.top = e.touches[0].pageY;
+ }
+ }
});
- }
-
- // Commands are parameter-less actions that can be performed on an
- // editor, mostly used for keybindings.
- var commands = {
- selectAll: selectAll,
- singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
- killLine: function (cm) { return deleteNearSelection(cm, function (range) {
- if (range.empty()) {
- var len = getLine(cm.doc, range.head.line).text.length;
- if (range.head.ch == len && range.head.line < cm.lastLine())
- { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
- else
- { return {from: range.head, to: Pos(range.head.line, len)} }
- } else {
- return {from: range.from(), to: range.to()}
+ on(d.scroller, "touchmove", function () {
+ if (d.activeTouch) { d.activeTouch.moved = true; }
+ });
+ on(d.scroller, "touchend", function (e) {
+ var touch = d.activeTouch;
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
+ !touch.moved && new Date - touch.start < 300) {
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
+ { range = new Range(pos, pos); }
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
+ { range = cm.findWordAt(pos); }
+ else // Triple tap
+ { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
+ cm.setSelection(range.anchor, range.head);
+ cm.focus();
+ e_preventDefault(e);
}
- }); },
- deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
- from: Pos(range.from().line, 0),
- to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
- }); }); },
- delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
- from: Pos(range.from().line, 0), to: range.from()
- }); }); },
- delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- var leftPos = cm.coordsChar({left: 0, top: top}, "div");
- return {from: leftPos, to: range.from()}
- }); },
- delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
- return {from: range.from(), to: rightPos }
- }); },
- undo: function (cm) { return cm.undo(); },
- redo: function (cm) { return cm.redo(); },
- undoSelection: function (cm) { return cm.undoSelection(); },
- redoSelection: function (cm) { return cm.redoSelection(); },
- goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
- goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
- goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
- {origin: "+move", bias: 1}
- ); },
- goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
- {origin: "+move", bias: 1}
- ); },
- goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
- {origin: "+move", bias: -1}
- ); },
- goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
- }, sel_move); },
- goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- return cm.coordsChar({left: 0, top: top}, "div")
- }, sel_move); },
- goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- var pos = cm.coordsChar({left: 0, top: top}, "div");
- if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
- return pos
- }, sel_move); },
- goLineUp: function (cm) { return cm.moveV(-1, "line"); },
- goLineDown: function (cm) { return cm.moveV(1, "line"); },
- goPageUp: function (cm) { return cm.moveV(-1, "page"); },
- goPageDown: function (cm) { return cm.moveV(1, "page"); },
- goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
- goCharRight: function (cm) { return cm.moveH(1, "char"); },
- goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
- goColumnRight: function (cm) { return cm.moveH(1, "column"); },
- goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
- goGroupRight: function (cm) { return cm.moveH(1, "group"); },
- goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
- goWordRight: function (cm) { return cm.moveH(1, "word"); },
- delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
- delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
- delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
- delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
- delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
- delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
- indentAuto: function (cm) { return cm.indentSelection("smart"); },
- indentMore: function (cm) { return cm.indentSelection("add"); },
- indentLess: function (cm) { return cm.indentSelection("subtract"); },
- insertTab: function (cm) { return cm.replaceSelection("\t"); },
- insertSoftTab: function (cm) {
- var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
- for (var i = 0; i < ranges.length; i++) {
- var pos = ranges[i].from();
- var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
- spaces.push(spaceStr(tabSize - col % tabSize));
- }
- cm.replaceSelections(spaces);
- },
- defaultTab: function (cm) {
- if (cm.somethingSelected()) { cm.indentSelection("add"); }
- else { cm.execCommand("insertTab"); }
- },
- // Swap the two chars left and right of each selection's head.
- // Move cursor behind the two swapped characters afterwards.
- //
- // Doesn't consider line feeds a character.
- // Doesn't scan more than one line above to find a character.
- // Doesn't do anything on an empty line.
- // Doesn't do anything with non-empty selections.
- transposeChars: function (cm) { return runInOp(cm, function () {
- var ranges = cm.listSelections(), newSel = [];
- for (var i = 0; i < ranges.length; i++) {
- if (!ranges[i].empty()) { continue }
- var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
- if (line) {
- if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
- if (cur.ch > 0) {
- cur = new Pos(cur.line, cur.ch + 1);
- cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
- Pos(cur.line, cur.ch - 2), cur, "+transpose");
- } else if (cur.line > cm.doc.first) {
- var prev = getLine(cm.doc, cur.line - 1).text;
- if (prev) {
- cur = new Pos(cur.line, 1);
- cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
- prev.charAt(prev.length - 1),
- Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
- }
- }
- }
- newSel.push(new Range(cur, cur));
+ finishTouch();
+ });
+ on(d.scroller, "touchcancel", finishTouch);
+
+ // Sync scrolling between fake scrollbars and real scrollable
+ // area, ensure viewport is updated when scrolling.
+ on(d.scroller, "scroll", function () {
+ if (d.scroller.clientHeight) {
+ updateScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
}
- cm.setSelections(newSel);
- }); },
- newlineAndIndent: function (cm) { return runInOp(cm, function () {
- var sels = cm.listSelections();
- for (var i = sels.length - 1; i >= 0; i--)
- { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
- sels = cm.listSelections();
- for (var i$1 = 0; i$1 < sels.length; i$1++)
- { cm.indentLine(sels[i$1].from().line, null, true); }
- ensureCursorVisible(cm);
- }); },
- openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
- toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
- };
+ });
+ // Listen to wheel events in order to try and update the viewport on time.
+ on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
+ on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
- function lineStart(cm, lineN) {
- var line = getLine(cm.doc, lineN);
- var visual = visualLine(line);
- if (visual != line) { lineN = lineNo(visual); }
- return endOfLine(true, cm, visual, lineN, 1)
- }
- function lineEnd(cm, lineN) {
- var line = getLine(cm.doc, lineN);
- var visual = visualLineEnd(line);
- if (visual != line) { lineN = lineNo(visual); }
- return endOfLine(true, cm, line, lineN, -1)
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+ d.dragFunctions = {
+ enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
+ over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
+ start: function (e) { return onDragStart(cm, e); },
+ drop: operation(cm, onDrop),
+ leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
+ };
+
+ var inp = d.input.getField();
+ on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
+ on(inp, "keydown", operation(cm, onKeyDown));
+ on(inp, "keypress", operation(cm, onKeyPress));
+ on(inp, "focus", function (e) { return onFocus(cm, e); });
+ on(inp, "blur", function (e) { return onBlur(cm, e); });
}
- function lineStartSmart(cm, pos) {
- var start = lineStart(cm, pos.line);
- var line = getLine(cm.doc, start.line);
- var order = getOrder(line, cm.doc.direction);
- if (!order || order[0].level == 0) {
- var firstNonWS = Math.max(0, line.text.search(/\S/));
- var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
- return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
+
+ var initHooks = [];
+ CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
+
+ // Indent the given line. The how parameter can be "smart",
+ // "add"/null, "subtract", or "prev". When aggressive is false
+ // (typically set to true for forced single-line indents), empty
+ // lines are not indented, and places where the mode returns Pass
+ // are left alone.
+ function indentLine(cm, n, how, aggressive) {
+ var doc = cm.doc, state;
+ if (how == null) { how = "add"; }
+ if (how == "smart") {
+ // Fall back to "prev" when the mode doesn't have an indentation
+ // method.
+ if (!doc.mode.indent) { how = "prev"; }
+ else { state = getContextBefore(cm, n).state; }
}
- return start
- }
- // Run a handler that was bound to a key.
- function doHandleBinding(cm, bound, dropShift) {
- if (typeof bound == "string") {
- bound = commands[bound];
- if (!bound) { return false }
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ if (line.stateAfter) { line.stateAfter = null; }
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (!aggressive && !/\S/.test(line.text)) {
+ indentation = 0;
+ how = "not";
+ } else if (how == "smart") {
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass || indentation > 150) {
+ if (!aggressive) { return }
+ how = "prev";
+ }
}
- // Ensure previous input has been read, so that the handler sees a
- // consistent view of the document
- cm.display.input.ensurePolled();
- var prevShift = cm.display.shift, done = false;
- try {
- if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
- if (dropShift) { cm.display.shift = false; }
- done = bound(cm) != Pass;
- } finally {
- cm.display.shift = prevShift;
- cm.state.suppressEdits = false;
+ if (how == "prev") {
+ if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
+ else { indentation = 0; }
+ } else if (how == "add") {
+ indentation = curSpace + cm.options.indentUnit;
+ } else if (how == "subtract") {
+ indentation = curSpace - cm.options.indentUnit;
+ } else if (typeof how == "number") {
+ indentation = curSpace + how;
}
- return done
- }
+ indentation = Math.max(0, indentation);
- function lookupKeyForEditor(cm, name, handle) {
- for (var i = 0; i < cm.state.keyMaps.length; i++) {
- var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
- if (result) { return result }
- }
- return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
- || lookupKey(name, cm.options.keyMap, handle, cm)
- }
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
+ if (pos < indentation) { indentString += spaceStr(indentation - pos); }
- var stopSeq = new Delayed;
- function dispatchKey(cm, name, e, handle) {
- var seq = cm.state.keySeq;
- if (seq) {
- if (isModifierKey(name)) { return "handled" }
- stopSeq.set(50, function () {
- if (cm.state.keySeq == seq) {
- cm.state.keySeq = null;
- cm.display.input.reset();
+ if (indentString != curSpaceString) {
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ line.stateAfter = null;
+ return true
+ } else {
+ // Ensure that, if the cursor was in the whitespace at the start
+ // of the line, it is moved to the end of that space.
+ for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
+ var range = doc.sel.ranges[i$1];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos$1 = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
+ break
}
- });
- name = seq + " " + name;
+ }
}
- var result = lookupKeyForEditor(cm, name, handle);
-
- if (result == "multi")
- { cm.state.keySeq = name; }
- if (result == "handled")
- { signalLater(cm, "keyHandled", cm, name, e); }
+ }
- if (result == "handled" || result == "multi") {
- e_preventDefault(e);
- restartBlink(cm);
- }
+ // This will be set to a {lineWise: bool, text: [string]} object, so
+ // that, when pasting, we know what kind of selections the copied
+ // text was made out of.
+ var lastCopied = null;
- if (seq && !result && /\'$/.test(name)) {
- e_preventDefault(e);
- return true
- }
- return !!result
+ function setLastCopied(newLastCopied) {
+ lastCopied = newLastCopied;
}
- // Handle a key from the keydown event.
- function handleKeyBinding(cm, e) {
- var name = keyName(e, true);
- if (!name) { return false }
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
+ var doc = cm.doc;
+ cm.display.shift = false;
+ if (!sel) { sel = doc.sel; }
- if (e.shiftKey && !cm.state.keySeq) {
- // First try to resolve full name (including 'Shift-'). Failing
- // that, see if there is a cursor-motion command (starting with
- // 'go') bound to the keyname without 'Shift-'.
- return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
- || dispatchKey(cm, name, e, function (b) {
- if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
- { return doHandleBinding(cm, b) }
- })
- } else {
- return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
+ var paste = cm.state.pasteIncoming || origin == "paste";
+ var textLines = splitLinesAuto(inserted), multiPaste = null;
+ // When pasing N lines into N selections, insert one line per selection
+ if (paste && sel.ranges.length > 1) {
+ if (lastCopied && lastCopied.text.join("\n") == inserted) {
+ if (sel.ranges.length % lastCopied.text.length == 0) {
+ multiPaste = [];
+ for (var i = 0; i < lastCopied.text.length; i++)
+ { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
+ }
+ } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
+ multiPaste = map(textLines, function (l) { return [l]; });
+ }
}
- }
- // Handle a key from the keypress event
- function handleCharBinding(cm, e, ch) {
- return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
+ var updateInput;
+ // Normal behavior is to insert the new text into every selection
+ for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
+ var range$$1 = sel.ranges[i$1];
+ var from = range$$1.from(), to = range$$1.to();
+ if (range$$1.empty()) {
+ if (deleted && deleted > 0) // Handle deletion
+ { from = Pos(from.line, from.ch - deleted); }
+ else if (cm.state.overwrite && !paste) // Handle overwrite
+ { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
+ else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
+ { from = to = Pos(from.line, 0); }
+ }
+ updateInput = cm.curOp.updateInput;
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
+ makeChange(cm.doc, changeEvent);
+ signalLater(cm, "inputRead", cm, changeEvent);
+ }
+ if (inserted && !paste)
+ { triggerElectric(cm, inserted); }
+
+ ensureCursorVisible(cm);
+ cm.curOp.updateInput = updateInput;
+ cm.curOp.typing = true;
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
}
- var lastStoppedKey = null;
- function onKeyDown(e) {
- var cm = this;
- cm.curOp.focus = activeElt();
- if (signalDOMEvent(cm, e)) { return }
- // IE does strange things with escape.
- if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
- var code = e.keyCode;
- cm.display.shift = code == 16 || e.shiftKey;
- var handled = handleKeyBinding(cm, e);
- if (presto) {
- lastStoppedKey = handled ? code : null;
- // Opera has no cut event... we try to at least catch the key combo
- if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
- { cm.replaceSelection("", null, "cut"); }
+ function handlePaste(e, cm) {
+ var pasted = e.clipboardData && e.clipboardData.getData("Text");
+ if (pasted) {
+ e.preventDefault();
+ if (!cm.isReadOnly() && !cm.options.disableInput)
+ { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
+ return true
}
-
- // Turn mouse into crosshair when Alt is held on Mac.
- if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
- { showCrossHair(cm); }
}
- function showCrossHair(cm) {
- var lineDiv = cm.display.lineDiv;
- addClass(lineDiv, "CodeMirror-crosshair");
+ function triggerElectric(cm, inserted) {
+ // When an 'electric' character is inserted, immediately trigger a reindent
+ if (!cm.options.electricChars || !cm.options.smartIndent) { return }
+ var sel = cm.doc.sel;
- function up(e) {
- if (e.keyCode == 18 || !e.altKey) {
- rmClass(lineDiv, "CodeMirror-crosshair");
- off(document, "keyup", up);
- off(document, "mouseover", up);
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
+ var range$$1 = sel.ranges[i];
+ if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
+ var mode = cm.getModeAt(range$$1.head);
+ var indented = false;
+ if (mode.electricChars) {
+ for (var j = 0; j < mode.electricChars.length; j++)
+ { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
+ indented = indentLine(cm, range$$1.head.line, "smart");
+ break
+ } }
+ } else if (mode.electricInput) {
+ if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
+ { indented = indentLine(cm, range$$1.head.line, "smart"); }
}
+ if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
}
- on(document, "keyup", up);
- on(document, "mouseover", up);
}
- function onKeyUp(e) {
- if (e.keyCode == 16) { this.doc.sel.shift = false; }
- signalDOMEvent(this, e);
+ function copyableRanges(cm) {
+ var text = [], ranges = [];
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
+ var line = cm.doc.sel.ranges[i].head.line;
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
+ ranges.push(lineRange);
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
+ }
+ return {text: text, ranges: ranges}
}
- function onKeyPress(e) {
- var cm = this;
- if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
- var keyCode = e.keyCode, charCode = e.charCode;
- if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
- if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
- var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
- // Some browsers fire keypress events for backspace
- if (ch == "\x08") { return }
- if (handleCharBinding(cm, e, ch)) { return }
- cm.display.input.onKeyPress(e);
+ function disableBrowserMagic(field, spellcheck) {
+ field.setAttribute("autocorrect", "off");
+ field.setAttribute("autocapitalize", "off");
+ field.setAttribute("spellcheck", !!spellcheck);
}
- // A mouse down can be a single click, double click, triple click,
- // start of selection drag, start of text drag, new cursor
- // (ctrl-click), rectangle drag (alt-drag), or xwin
- // middle-click-paste. Or it might be a click on something we should
- // not interfere with, such as a scrollbar or widget.
- function onMouseDown(e) {
- var cm = this, display = cm.display;
- if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
- display.input.ensurePolled();
- display.shift = e.shiftKey;
+ function hiddenTextarea() {
+ var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // The textarea is kept positioned near the cursor to prevent the
+ // fact that it'll be scrolled into view on input from scrolling
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
+ // very slow. So make the area wide instead.
+ if (webkit) { te.style.width = "1000px"; }
+ else { te.setAttribute("wrap", "off"); }
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
+ if (ios) { te.style.border = "1px solid black"; }
+ disableBrowserMagic(te);
+ return div
+ }
- if (eventInWidget(display, e)) {
- if (!webkit) {
- // Briefly turn off draggability, to allow widgets to do
- // normal dragging things.
- display.scroller.draggable = false;
- setTimeout(function () { return display.scroller.draggable = true; }, 100);
- }
- return
- }
- if (clickInGutter(cm, e)) { return }
- var start = posFromMouse(cm, e);
- window.focus();
+ // The publicly visible API. Note that methodOp(f) means
+ // 'wrap f in an operation, performed on its `this` parameter'.
- switch (e_button(e)) {
- case 1:
- // #3261: make sure, that we're not starting a second selection
- if (cm.state.selectingText)
- { cm.state.selectingText(e); }
- else if (start)
- { leftButtonDown(cm, e, start); }
- else if (e_target(e) == display.scroller)
- { e_preventDefault(e); }
- break
- case 2:
- if (webkit) { cm.state.lastMiddleDown = +new Date; }
- if (start) { extendSelection(cm.doc, start); }
- setTimeout(function () { return display.input.focus(); }, 20);
- e_preventDefault(e);
- break
- case 3:
- if (captureRightClick) { onContextMenu(cm, e); }
- else { delayBlurEvent(cm); }
- break
- }
- }
+ // This is not the complete set of editor methods. Most of the
+ // methods defined on the Doc type are also injected into
+ // CodeMirror.prototype, for backwards compatibility and
+ // convenience.
- var lastClick;
- var lastDoubleClick;
- function leftButtonDown(cm, e, start) {
- if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
- else { cm.curOp.focus = activeElt(); }
+ var addEditorMethods = function(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
- var now = +new Date, type;
- if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
- type = "triple";
- } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
- type = "double";
- lastDoubleClick = {time: now, pos: start};
- } else {
- type = "single";
- lastClick = {time: now, pos: start};
- }
+ var helpers = CodeMirror.helpers = {};
- var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
- if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
- type == "single" && (contained = sel.contains(start)) > -1 &&
- (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
- (cmp(contained.to(), start) > 0 || start.xRel < 0))
- { leftButtonStartDrag(cm, e, start, modifier); }
- else
- { leftButtonSelect(cm, e, start, type, modifier); }
- }
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){window.focus(); this.display.input.focus();},
- // Start a text drag. When it ends, see if any dragging actually
- // happen, and treat as a click if it didn't.
- function leftButtonStartDrag(cm, e, start, modifier) {
- var display = cm.display, moved = false;
- var dragEnd = operation(cm, function (e) {
- if (webkit) { display.scroller.draggable = false; }
- cm.state.draggingText = false;
- off(document, "mouseup", dragEnd);
- off(document, "mousemove", mouseMove);
- off(display.scroller, "dragstart", dragStart);
- off(display.scroller, "drop", dragEnd);
- if (!moved) {
- e_preventDefault(e);
- if (!modifier)
- { extendSelection(cm.doc, start); }
- // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
- if (webkit || ie && ie_version == 9)
- { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
- else
- { display.input.focus(); }
- }
- });
- var mouseMove = function(e2) {
- moved = moved || Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) >= 10;
- };
- var dragStart = function () { return moved = true; };
- // Let the drag handler handle this.
- if (webkit) { display.scroller.draggable = true; }
- cm.state.draggingText = dragEnd;
- dragEnd.copy = mac ? e.altKey : e.ctrlKey;
- // IE's approach to draggable
- if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
- on(document, "mouseup", dragEnd);
- on(document, "mousemove", mouseMove);
- on(display.scroller, "dragstart", dragStart);
- on(display.scroller, "drop", dragEnd);
-
- delayBlurEvent(cm);
- setTimeout(function () { return display.input.focus(); }, 20);
- }
-
- // Normal selection, as opposed to text dragging.
- function leftButtonSelect(cm, e, start, type, addNew) {
- var display = cm.display, doc = cm.doc;
- e_preventDefault(e);
-
- var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
- if (addNew && !e.shiftKey) {
- ourIndex = doc.sel.contains(start);
- if (ourIndex > -1)
- { ourRange = ranges[ourIndex]; }
- else
- { ourRange = new Range(start, start); }
- } else {
- ourRange = doc.sel.primary();
- ourIndex = doc.sel.primIndex;
- }
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") { return }
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ { operation(this, optionHandlers[option])(this, value, old); }
+ signal(this, "optionChange", this, option);
+ },
- if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
- type = "rect";
- if (!addNew) { ourRange = new Range(start, start); }
- start = posFromMouse(cm, e, true, true);
- ourIndex = -1;
- } else if (type == "double") {
- var word = cm.findWordAt(start);
- if (cm.display.shift || doc.extend)
- { ourRange = extendRange(doc, ourRange, word.anchor, word.head); }
- else
- { ourRange = word; }
- } else if (type == "triple") {
- var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
- if (cm.display.shift || doc.extend)
- { ourRange = extendRange(doc, ourRange, line.anchor, line.head); }
- else
- { ourRange = line; }
- } else {
- ourRange = extendRange(doc, ourRange, start);
- }
+ getOption: function(option) {return this.options[option]},
+ getDoc: function() {return this.doc},
- if (!addNew) {
- ourIndex = 0;
- setSelection(doc, new Selection([ourRange], 0), sel_mouse);
- startSel = doc.sel;
- } else if (ourIndex == -1) {
- ourIndex = ranges.length;
- setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
- {scroll: false, origin: "*mouse"});
- } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
- setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
- {scroll: false, origin: "*mouse"});
- startSel = doc.sel;
- } else {
- replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
- }
+ addKeyMap: function(map$$1, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
+ },
+ removeKeyMap: function(map$$1) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ { if (maps[i] == map$$1 || maps[i].name == map$$1) {
+ maps.splice(i, 1);
+ return true
+ } }
+ },
- var lastPos = start;
- function extendTo(pos) {
- if (cmp(lastPos, pos) == 0) { return }
- lastPos = pos;
+ addOverlay: methodOp(function(spec, options) {
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+ if (mode.startState) { throw new Error("Overlays may not be stateful.") }
+ insertSorted(this.state.overlays,
+ {mode: mode, modeSpec: spec, opaque: options && options.opaque,
+ priority: (options && options.priority) || 0},
+ function (overlay) { return overlay.priority; });
+ this.state.modeGen++;
+ regChange(this);
+ }),
+ removeOverlay: methodOp(function(spec) {
+ var this$1 = this;
- if (type == "rect") {
- var ranges = [], tabSize = cm.options.tabSize;
- var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
- var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
- var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
- for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
- line <= end; line++) {
- var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
- if (left == right)
- { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
- else if (text.length > leftPos)
- { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
- }
- if (!ranges.length) { ranges.push(new Range(start, start)); }
- setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
- {origin: "*mouse", scroll: false});
- cm.scrollIntoView(pos);
- } else {
- var oldRange = ourRange;
- var anchor = oldRange.anchor, head = pos;
- if (type != "single") {
- var range$$1;
- if (type == "double")
- { range$$1 = cm.findWordAt(pos); }
- else
- { range$$1 = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); }
- if (cmp(range$$1.anchor, anchor) > 0) {
- head = range$$1.head;
- anchor = minPos(oldRange.from(), range$$1.anchor);
- } else {
- head = range$$1.anchor;
- anchor = maxPos(oldRange.to(), range$$1.head);
+ var overlays = this.state.overlays;
+ for (var i = 0; i < overlays.length; ++i) {
+ var cur = overlays[i].modeSpec;
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
+ overlays.splice(i, 1);
+ this$1.state.modeGen++;
+ regChange(this$1);
+ return
}
}
- var ranges$1 = startSel.ranges.slice(0);
- ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head);
- setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
- }
- }
+ }),
- var editorSize = display.wrapper.getBoundingClientRect();
- // Used to ensure timeout re-tries don't fire when another extend
- // happened in the meantime (clearTimeout isn't reliable -- at
- // least on Chrome, the timeouts still happen even when cleared,
- // if the clear happens after their scheduled firing time).
- var counter = 0;
+ indentLine: methodOp(function(n, dir, aggressive) {
+ if (typeof dir != "string" && typeof dir != "number") {
+ if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
+ else { dir = dir ? "add" : "subtract"; }
+ }
+ if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
+ }),
+ indentSelection: methodOp(function(how) {
+ var this$1 = this;
- function extend(e) {
- var curCount = ++counter;
- var cur = posFromMouse(cm, e, true, type == "rect");
- if (!cur) { return }
- if (cmp(cur, lastPos) != 0) {
- cm.curOp.focus = activeElt();
- extendTo(cur);
- var visible = visibleLines(display, doc);
- if (cur.line >= visible.to || cur.line < visible.from)
- { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
- } else {
- var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
- if (outside) { setTimeout(operation(cm, function () {
- if (counter != curCount) { return }
- display.scroller.scrollTop += outside;
- extend(e);
- }), 50); }
- }
- }
+ var ranges = this.doc.sel.ranges, end = -1;
+ for (var i = 0; i < ranges.length; i++) {
+ var range$$1 = ranges[i];
+ if (!range$$1.empty()) {
+ var from = range$$1.from(), to = range$$1.to();
+ var start = Math.max(end, from.line);
+ end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ { indentLine(this$1, j, how); }
+ var newRanges = this$1.doc.sel.ranges;
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
+ { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
+ } else if (range$$1.head.line > end) {
+ indentLine(this$1, range$$1.head.line, how, true);
+ end = range$$1.head.line;
+ if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
+ }
+ }
+ }),
- function done(e) {
- cm.state.selectingText = false;
- counter = Infinity;
- e_preventDefault(e);
- display.input.focus();
- off(document, "mousemove", move);
- off(document, "mouseup", up);
- doc.history.lastSelOrigin = null;
- }
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos, precise) {
+ return takeToken(this, pos, precise)
+ },
- var move = operation(cm, function (e) {
- if (!e_button(e)) { done(e); }
- else { extend(e); }
- });
- var up = operation(cm, done);
- cm.state.selectingText = up;
- on(document, "mousemove", move);
- on(document, "mouseup", up);
- }
+ getLineTokens: function(line, precise) {
+ return takeToken(this, Pos(line), precise, true)
+ },
+ getTokenTypeAt: function(pos) {
+ pos = clipPos(this.doc, pos);
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+ var type;
+ if (ch == 0) { type = styles[2]; }
+ else { for (;;) {
+ var mid = (before + after) >> 1;
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
+ else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
+ else { type = styles[mid * 2 + 2]; break }
+ } }
+ var cut = type ? type.indexOf("overlay ") : -1;
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
+ },
- // Determines whether an event happened in the gutter, and fires the
- // handlers for the corresponding event.
- function gutterEvent(cm, e, type, prevent) {
- var mX, mY;
- try { mX = e.clientX; mY = e.clientY; }
- catch(e) { return false }
- if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
- if (prevent) { e_preventDefault(e); }
+ getModeAt: function(pos) {
+ var mode = this.doc.mode;
+ if (!mode.innerMode) { return mode }
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
+ },
- var display = cm.display;
- var lineBox = display.lineDiv.getBoundingClientRect();
+ getHelper: function(pos, type) {
+ return this.getHelpers(pos, type)[0]
+ },
- if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
- mY -= lineBox.top - display.viewOffset;
+ getHelpers: function(pos, type) {
+ var this$1 = this;
- for (var i = 0; i < cm.options.gutters.length; ++i) {
- var g = display.gutters.childNodes[i];
- if (g && g.getBoundingClientRect().right >= mX) {
- var line = lineAtHeight(cm.doc, mY);
- var gutter = cm.options.gutters[i];
- signal(cm, type, cm, line, gutter, e);
- return e_defaultPrevented(e)
- }
- }
- }
+ var found = [];
+ if (!helpers.hasOwnProperty(type)) { return found }
+ var help = helpers[type], mode = this.getModeAt(pos);
+ if (typeof mode[type] == "string") {
+ if (help[mode[type]]) { found.push(help[mode[type]]); }
+ } else if (mode[type]) {
+ for (var i = 0; i < mode[type].length; i++) {
+ var val = help[mode[type][i]];
+ if (val) { found.push(val); }
+ }
+ } else if (mode.helperType && help[mode.helperType]) {
+ found.push(help[mode.helperType]);
+ } else if (help[mode.name]) {
+ found.push(help[mode.name]);
+ }
+ for (var i$1 = 0; i$1 < help._global.length; i$1++) {
+ var cur = help._global[i$1];
+ if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
+ { found.push(cur.val); }
+ }
+ return found
+ },
- function clickInGutter(cm, e) {
- return gutterEvent(cm, e, "gutterClick", true)
- }
+ getStateAfter: function(line, precise) {
+ var doc = this.doc;
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+ return getContextBefore(this, line + 1, precise).state
+ },
- // CONTEXT MENU HANDLING
+ cursorCoords: function(start, mode) {
+ var pos, range$$1 = this.doc.sel.primary();
+ if (start == null) { pos = range$$1.head; }
+ else if (typeof start == "object") { pos = clipPos(this.doc, start); }
+ else { pos = start ? range$$1.from() : range$$1.to(); }
+ return cursorCoords(this, pos, mode || "page")
+ },
- // To make the context menu work, we need to briefly unhide the
- // textarea (making it as unobtrusive as possible) to let the
- // right-click take effect on it.
- function onContextMenu(cm, e) {
- if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
- if (signalDOMEvent(cm, e, "contextmenu")) { return }
- cm.display.input.onContextMenu(e);
- }
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.doc, pos), mode || "page")
+ },
- function contextMenuInGutter(cm, e) {
- if (!hasHandler(cm, "gutterContextMenu")) { return false }
- return gutterEvent(cm, e, "gutterContextMenu", false)
- }
+ coordsChar: function(coords, mode) {
+ coords = fromCoordSystem(this, coords, mode || "page");
+ return coordsChar(this, coords.left, coords.top)
+ },
- function themeChanged(cm) {
- cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
- cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
- clearCaches(cm);
- }
+ lineAtHeight: function(height, mode) {
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+ return lineAtHeight(this.doc, height + this.display.viewOffset)
+ },
+ heightAtLine: function(line, mode, includeWidgets) {
+ var end = false, lineObj;
+ if (typeof line == "number") {
+ var last = this.doc.first + this.doc.size - 1;
+ if (line < this.doc.first) { line = this.doc.first; }
+ else if (line > last) { line = last; end = true; }
+ lineObj = getLine(this.doc, line);
+ } else {
+ lineObj = line;
+ }
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0)
+ },
- var Init = {toString: function(){return "CodeMirror.Init"}};
+ defaultTextHeight: function() { return textHeight(this.display) },
+ defaultCharWidth: function() { return charWidth(this.display) },
- var defaults = {};
- var optionHandlers = {};
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
- function defineOptions(CodeMirror) {
- var optionHandlers = CodeMirror.optionHandlers;
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.doc, pos));
+ var top = pos.bottom, left = pos.left;
+ node.style.position = "absolute";
+ node.setAttribute("cm-ignore-events", "true");
+ this.display.input.setUneditable(node);
+ display.sizer.appendChild(node);
+ if (vert == "over") {
+ top = pos.top;
+ } else if (vert == "above" || vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+ { top = pos.top - node.offsetHeight; }
+ else if (pos.bottom + node.offsetHeight <= vspace)
+ { top = pos.bottom; }
+ if (left + node.offsetWidth > hspace)
+ { left = hspace - node.offsetWidth; }
+ }
+ node.style.top = top + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") { left = 0; }
+ else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
+ },
- function option(name, deflt, handle, notOnInit) {
- CodeMirror.defaults[name] = deflt;
- if (handle) { optionHandlers[name] =
- notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
- }
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: onKeyUp,
+ triggerOnMouseDown: methodOp(onMouseDown),
- CodeMirror.defineOption = option;
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ { return commands[cmd].call(null, this) }
+ },
- // Passed to option handlers when there is no old value.
- CodeMirror.Init = Init;
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
- // These two are, on init, called from the constructor because they
- // have to be initialized before the editor can start at all.
- option("value", "", function (cm, val) { return cm.setValue(val); }, true);
- option("mode", null, function (cm, val) {
- cm.doc.modeOption = val;
- loadMode(cm);
- }, true);
+ findPosH: function(from, amount, unit, visually) {
+ var this$1 = this;
- option("indentUnit", 2, loadMode, true);
- option("indentWithTabs", false);
- option("smartIndent", true);
- option("tabSize", 4, function (cm) {
- resetModeState(cm);
- clearCaches(cm);
- regChange(cm);
- }, true);
- option("lineSeparator", null, function (cm, val) {
- cm.doc.lineSep = val;
- if (!val) { return }
- var newBreaks = [], lineNo = cm.doc.first;
- cm.doc.iter(function (line) {
- for (var pos = 0;;) {
- var found = line.text.indexOf(val, pos);
- if (found == -1) { break }
- pos = found + val.length;
- newBreaks.push(Pos(lineNo, found));
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ cur = findPosH(this$1.doc, cur, dir, unit, visually);
+ if (cur.hitSide) { break }
}
- lineNo++;
- });
- for (var i = newBreaks.length - 1; i >= 0; i--)
- { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
- });
- option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
- cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
- if (old != Init) { cm.refresh(); }
- });
- option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
- option("electricChars", true);
- option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
- throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
- }, true);
- option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
- option("rtlMoveVisually", !windows);
- option("wholeLineUpdateBefore", true);
+ return cur
+ },
- option("theme", "default", function (cm) {
- themeChanged(cm);
- guttersChanged(cm);
- }, true);
- option("keyMap", "default", function (cm, val, old) {
- var next = getKeyMap(val);
- var prev = old != Init && getKeyMap(old);
- if (prev && prev.detach) { prev.detach(cm, next); }
- if (next.attach) { next.attach(cm, prev || null); }
- });
- option("extraKeys", null);
+ moveH: methodOp(function(dir, unit) {
+ var this$1 = this;
- option("lineWrapping", false, wrappingChanged, true);
- option("gutters", [], function (cm) {
- setGuttersForLineNumbers(cm.options);
- guttersChanged(cm);
- }, true);
- option("fixedGutter", true, function (cm, val) {
- cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
- cm.refresh();
- }, true);
- option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
- option("scrollbarStyle", "native", function (cm) {
- initScrollbars(cm);
- updateScrollbars(cm);
- cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
- cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
- }, true);
- option("lineNumbers", false, function (cm) {
- setGuttersForLineNumbers(cm.options);
- guttersChanged(cm);
- }, true);
- option("firstLineNumber", 1, guttersChanged, true);
- option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
- option("showCursorWhenSelecting", false, updateSelection, true);
+ this.extendSelectionsBy(function (range$$1) {
+ if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
+ { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
+ else
+ { return dir < 0 ? range$$1.from() : range$$1.to() }
+ }, sel_move);
+ }),
- option("resetSelectionOnContextMenu", true);
- option("lineWiseCopyCut", true);
+ deleteH: methodOp(function(dir, unit) {
+ var sel = this.doc.sel, doc = this.doc;
+ if (sel.somethingSelected())
+ { doc.replaceSelection("", null, "+delete"); }
+ else
+ { deleteNearSelection(this, function (range$$1) {
+ var other = findPosH(doc, range$$1.head, dir, unit, false);
+ return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
+ }); }
+ }),
- option("readOnly", false, function (cm, val) {
- if (val == "nocursor") {
- onBlur(cm);
- cm.display.input.blur();
- cm.display.disabled = true;
- } else {
- cm.display.disabled = false;
- }
- cm.display.input.readOnlyChanged(val);
- });
- option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
- option("dragDrop", true, dragDropChanged);
- option("allowDropFileTypes", null);
+ findPosV: function(from, amount, unit, goalColumn) {
+ var this$1 = this;
- option("cursorBlinkRate", 530);
- option("cursorScrollMargin", 0);
- option("cursorHeight", 1, updateSelection, true);
- option("singleCursorHeightPerLine", true, updateSelection, true);
- option("workTime", 100);
- option("workDelay", 100);
- option("flattenSpans", true, resetModeState, true);
- option("addModeClass", false, resetModeState, true);
- option("pollInterval", 100);
- option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
- option("historyEventDelay", 1250);
- option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
- option("maxHighlightLength", 10000, resetModeState, true);
- option("moveInputWithCursor", true, function (cm, val) {
- if (!val) { cm.display.input.resetPosition(); }
- });
-
- option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
- option("autofocus", null);
- option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
- }
-
- function guttersChanged(cm) {
- updateGutters(cm);
- regChange(cm);
- alignHorizontally(cm);
- }
+ var dir = 1, x = goalColumn;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ var coords = cursorCoords(this$1, cur, "div");
+ if (x == null) { x = coords.left; }
+ else { coords.left = x; }
+ cur = findPosV(this$1, coords, dir, unit);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
- function dragDropChanged(cm, value, old) {
- var wasOn = old && old != Init;
- if (!value != !wasOn) {
- var funcs = cm.display.dragFunctions;
- var toggle = value ? on : off;
- toggle(cm.display.scroller, "dragstart", funcs.start);
- toggle(cm.display.scroller, "dragenter", funcs.enter);
- toggle(cm.display.scroller, "dragover", funcs.over);
- toggle(cm.display.scroller, "dragleave", funcs.leave);
- toggle(cm.display.scroller, "drop", funcs.drop);
- }
- }
+ moveV: methodOp(function(dir, unit) {
+ var this$1 = this;
- function wrappingChanged(cm) {
- if (cm.options.lineWrapping) {
- addClass(cm.display.wrapper, "CodeMirror-wrap");
- cm.display.sizer.style.minWidth = "";
- cm.display.sizerWidth = null;
- } else {
- rmClass(cm.display.wrapper, "CodeMirror-wrap");
- findMaxLine(cm);
- }
- estimateLineHeights(cm);
- regChange(cm);
- clearCaches(cm);
- setTimeout(function () { return updateScrollbars(cm); }, 100);
- }
+ var doc = this.doc, goals = [];
+ var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function (range$$1) {
+ if (collapse)
+ { return dir < 0 ? range$$1.from() : range$$1.to() }
+ var headPos = cursorCoords(this$1, range$$1.head, "div");
+ if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
+ goals.push(headPos.left);
+ var pos = findPosV(this$1, headPos, dir, unit);
+ if (unit == "page" && range$$1 == doc.sel.primary())
+ { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
+ return pos
+ }, sel_move);
+ if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
+ { doc.sel.ranges[i].goalColumn = goals[i]; } }
+ }),
- // A CodeMirror instance represents an editor. This is the object
- // that user code is usually dealing with.
+ // Find the word at the given position (as returned by coordsChar).
+ findWordAt: function(pos) {
+ var doc = this.doc, line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ var helper = this.getHelper(pos, "wordChars");
+ if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar, helper)
+ ? function (ch) { return isWordChar(ch, helper); }
+ : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
+ : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
+ while (start > 0 && check(line.charAt(start - 1))) { --start; }
+ while (end < line.length && check(line.charAt(end))) { ++end; }
+ }
+ return new Range(Pos(pos.line, start), Pos(pos.line, end))
+ },
- function CodeMirror$1(place, options) {
- var this$1 = this;
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) { return }
+ if (this.state.overwrite = !this.state.overwrite)
+ { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+ else
+ { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
- if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return this.display.input.getField() == activeElt() },
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
- this.options = options = options ? copyObj(options) : {};
- // Determine effective options based on given values and defaults.
- copyObj(defaults, options, false);
- setGuttersForLineNumbers(options);
+ scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
+ },
- var doc = options.value;
- if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
- this.doc = doc;
+ scrollIntoView: methodOp(function(range$$1, margin) {
+ if (range$$1 == null) {
+ range$$1 = {from: this.doc.sel.primary().head, to: null};
+ if (margin == null) { margin = this.options.cursorScrollMargin; }
+ } else if (typeof range$$1 == "number") {
+ range$$1 = {from: Pos(range$$1, 0), to: null};
+ } else if (range$$1.from == null) {
+ range$$1 = {from: range$$1, to: null};
+ }
+ if (!range$$1.to) { range$$1.to = range$$1.from; }
+ range$$1.margin = margin || 0;
- var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
- var display = this.display = new Display(place, doc, input);
- display.wrapper.CodeMirror = this;
- updateGutters(this);
- themeChanged(this);
- if (options.lineWrapping)
- { this.display.wrapper.className += " CodeMirror-wrap"; }
- initScrollbars(this);
+ if (range$$1.from.line != null) {
+ scrollToRange(this, range$$1);
+ } else {
+ scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
+ }
+ }),
- this.state = {
- keyMaps: [], // stores maps added by addKeyMap
- overlays: [], // highlighting overlays, as added by addOverlay
- modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
- overwrite: false,
- delayingBlurEvent: false,
- focused: false,
- suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
- pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
- selectingText: false,
- draggingText: false,
- highlight: new Delayed(), // stores highlight worker timeout
- keySeq: null, // Unfinished key sequence
- specialChars: null
- };
+ setSize: methodOp(function(width, height) {
+ var this$1 = this;
- if (options.autofocus && !mobile) { display.input.focus(); }
+ var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
+ if (width != null) { this.display.wrapper.style.width = interpret(width); }
+ if (height != null) { this.display.wrapper.style.height = interpret(height); }
+ if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
+ var lineNo$$1 = this.display.viewFrom;
+ this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
+ { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
+ ++lineNo$$1;
+ });
+ this.curOp.forceUpdate = true;
+ signal(this, "refresh", this);
+ }),
- // Override magic textarea content restore that IE sometimes does
- // on our hidden textarea on reload
- if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
+ operation: function(f){return runInOp(this, f)},
+ startOperation: function(){return startOperation(this)},
+ endOperation: function(){return endOperation(this)},
- registerEventHandlers(this);
- ensureGlobalHandlers();
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ this.curOp.forceUpdate = true;
+ clearCaches(this);
+ scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
+ updateGutterSpace(this);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
+ { estimateLineHeights(this); }
+ signal(this, "refresh", this);
+ }),
- startOperation(this);
- this.curOp.forceUpdate = true;
- attachDoc(this, doc);
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ attachDoc(this, doc);
+ clearCaches(this);
+ this.display.input.reset();
+ scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
+ this.curOp.forceScroll = true;
+ signalLater(this, "swapDoc", this, old);
+ return old
+ }),
- if ((options.autofocus && !mobile) || this.hasFocus())
- { setTimeout(bind(onFocus, this), 20); }
- else
- { onBlur(this); }
+ getInputField: function(){return this.display.input.getField()},
+ getWrapperElement: function(){return this.display.wrapper},
+ getScrollerElement: function(){return this.display.scroller},
+ getGutterElement: function(){return this.display.gutters}
+ };
+ eventMixin(CodeMirror);
- for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
- { optionHandlers[opt](this$1, options[opt], Init); } }
- maybeUpdateLineNumberWidth(this);
- if (options.finishInit) { options.finishInit(this); }
- for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
- endOperation(this);
- // Suppress optimizelegibility in Webkit, since it breaks text
- // measuring on line wrapping boundaries.
- if (webkit && options.lineWrapping &&
- getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
- { display.lineDiv.style.textRendering = "auto"; }
- }
+ CodeMirror.registerHelper = function(type, name, value) {
+ if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
+ helpers[type][name] = value;
+ };
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
+ CodeMirror.registerHelper(type, name, value);
+ helpers[type]._global.push({pred: predicate, val: value});
+ };
+ };
- // The default configuration options.
- CodeMirror$1.defaults = defaults;
- // Functions to run when options are changed.
- CodeMirror$1.optionHandlers = optionHandlers;
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
+ // right), unit can be "char", "column" (like char, but doesn't
+ // cross line boundaries), "word" (across next word), or "group" (to
+ // the start of next group of word or non-word-non-whitespace
+ // chars). The visually param controls whether, in right-to-left
+ // text, direction 1 means to move towards the next index in the
+ // string, or towards the character to the right of the current
+ // position. The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosH(doc, pos, dir, unit, visually) {
+ var oldPos = pos;
+ var origDir = dir;
+ var lineObj = getLine(doc, pos.line);
+ function findNextLine() {
+ var l = pos.line + dir;
+ if (l < doc.first || l >= doc.first + doc.size) { return false }
+ pos = new Pos(l, pos.ch, pos.sticky);
+ return lineObj = getLine(doc, l)
+ }
+ function moveOnce(boundToLine) {
+ var next;
+ if (visually) {
+ next = moveVisually(doc.cm, lineObj, pos, dir);
+ } else {
+ next = moveLogically(lineObj, pos, dir);
+ }
+ if (next == null) {
+ if (!boundToLine && findNextLine())
+ { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
+ else
+ { return false }
+ } else {
+ pos = next;
+ }
+ return true
+ }
- // Attach the necessary event handlers when initializing the editor
- function registerEventHandlers(cm) {
- var d = cm.display;
- on(d.scroller, "mousedown", operation(cm, onMouseDown));
- // Older IE's will not fire a second mousedown for a double click
- if (ie && ie_version < 11)
- { on(d.scroller, "dblclick", operation(cm, function (e) {
- if (signalDOMEvent(cm, e)) { return }
- var pos = posFromMouse(cm, e);
- if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
- e_preventDefault(e);
- var word = cm.findWordAt(pos);
- extendSelection(cm.doc, word.anchor, word.head);
- })); }
- else
- { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
- // Some browsers fire contextmenu *after* opening the menu, at
- // which point we can't mess with it anymore. Context menu is
- // handled in onMouseDown for these browsers.
- if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
+ if (unit == "char") {
+ moveOnce();
+ } else if (unit == "column") {
+ moveOnce(true);
+ } else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) { break }
+ var cur = lineObj.text.charAt(pos.ch) || "\n";
+ var type = isWordChar(cur, helper) ? "w"
+ : group && cur == "\n" ? "n"
+ : !group || /\s/.test(cur) ? null
+ : "p";
+ if (group && !first && !type) { type = "s"; }
+ if (sawType && sawType != type) {
+ if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
+ break
+ }
- // Used to suppress mouse event handling when a touch happens
- var touchFinished, prevTouch = {end: 0};
- function finishTouch() {
- if (d.activeTouch) {
- touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
- prevTouch = d.activeTouch;
- prevTouch.end = +new Date;
+ if (type) { sawType = type; }
+ if (dir > 0 && !moveOnce(!first)) { break }
}
}
- function isMouseLikeTouchEvent(e) {
- if (e.touches.length != 1) { return false }
- var touch = e.touches[0];
- return touch.radiusX <= 1 && touch.radiusY <= 1
+ var result = skipAtomic(doc, pos, oldPos, origDir, true);
+ if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
+ return result
+ }
+
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
+ // "page" or "line". The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosV(cm, pos, dir, unit) {
+ var doc = cm.doc, x = pos.left, y;
+ if (unit == "page") {
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+ var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
+ y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
+
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
}
- function farAway(touch, other) {
- if (other.left == null) { return true }
- var dx = other.left - touch.left, dy = other.top - touch.top;
- return dx * dx + dy * dy > 20 * 20
+ var target;
+ for (;;) {
+ target = coordsChar(cm, x, y);
+ if (!target.outside) { break }
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
+ y += dir * 5;
}
- on(d.scroller, "touchstart", function (e) {
- if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
- d.input.ensurePolled();
- clearTimeout(touchFinished);
- var now = +new Date;
- d.activeTouch = {start: now, moved: false,
- prev: now - prevTouch.end <= 300 ? prevTouch : null};
- if (e.touches.length == 1) {
- d.activeTouch.left = e.touches[0].pageX;
- d.activeTouch.top = e.touches[0].pageY;
- }
- }
+ return target
+ }
+
+ // CONTENTEDITABLE INPUT STYLE
+
+ var ContentEditableInput = function(cm) {
+ this.cm = cm;
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
+ this.polling = new Delayed();
+ this.composing = null;
+ this.gracePeriod = false;
+ this.readDOMTimeout = null;
+ };
+
+ ContentEditableInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = input.cm;
+ var div = input.div = display.lineDiv;
+ disableBrowserMagic(div, cm.options.spellcheck);
+
+ on(div, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+ // IE doesn't fire input events, so we schedule a read for the pasted content in this way
+ if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
});
- on(d.scroller, "touchmove", function () {
- if (d.activeTouch) { d.activeTouch.moved = true; }
+
+ on(div, "compositionstart", function (e) {
+ this$1.composing = {data: e.data, done: false};
});
- on(d.scroller, "touchend", function (e) {
- var touch = d.activeTouch;
- if (touch && !eventInWidget(d, e) && touch.left != null &&
- !touch.moved && new Date - touch.start < 300) {
- var pos = cm.coordsChar(d.activeTouch, "page"), range;
- if (!touch.prev || farAway(touch, touch.prev)) // Single tap
- { range = new Range(pos, pos); }
- else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
- { range = cm.findWordAt(pos); }
- else // Triple tap
- { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
- cm.setSelection(range.anchor, range.head);
- cm.focus();
- e_preventDefault(e);
+ on(div, "compositionupdate", function (e) {
+ if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
+ });
+ on(div, "compositionend", function (e) {
+ if (this$1.composing) {
+ if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
+ this$1.composing.done = true;
}
- finishTouch();
});
- on(d.scroller, "touchcancel", finishTouch);
- // Sync scrolling between fake scrollbars and real scrollable
- // area, ensure viewport is updated when scrolling.
- on(d.scroller, "scroll", function () {
- if (d.scroller.clientHeight) {
- setScrollTop(cm, d.scroller.scrollTop);
- setScrollLeft(cm, d.scroller.scrollLeft, true);
- signal(cm, "scroll", cm);
- }
+ on(div, "touchstart", function () { return input.forceCompositionEnd(); });
+
+ on(div, "input", function () {
+ if (!this$1.composing) { this$1.readFromDOMSoon(); }
});
- // Listen to wheel events in order to try and update the viewport on time.
- on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
- on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
+ function onCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.operation(function () {
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
+ cm.replaceSelection("", null, "cut");
+ });
+ }
+ }
+ if (e.clipboardData) {
+ e.clipboardData.clearData();
+ var content = lastCopied.text.join("\n");
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
+ e.clipboardData.setData("Text", content);
+ if (e.clipboardData.getData("Text") == content) {
+ e.preventDefault();
+ return
+ }
+ }
+ // Old-fashioned briefly-focus-a-textarea hack
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
+ te.value = lastCopied.text.join("\n");
+ var hadFocus = document.activeElement;
+ selectInput(te);
+ setTimeout(function () {
+ cm.display.lineSpace.removeChild(kludge);
+ hadFocus.focus();
+ if (hadFocus == div) { input.showPrimarySelection(); }
+ }, 50);
+ }
+ on(div, "copy", onCopyCut);
+ on(div, "cut", onCopyCut);
+ };
- // Prevent wrapper from ever scrolling
- on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+ ContentEditableInput.prototype.prepareSelection = function () {
+ var result = prepareSelection(this.cm, false);
+ result.focus = this.cm.state.focused;
+ return result
+ };
- d.dragFunctions = {
- enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
- over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
- start: function (e) { return onDragStart(cm, e); },
- drop: operation(cm, onDrop),
- leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
- };
+ ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
+ if (!info || !this.cm.display.view.length) { return }
+ if (info.focus || takeFocus) { this.showPrimarySelection(); }
+ this.showMultipleSelections(info);
+ };
- var inp = d.input.getField();
- on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
- on(inp, "keydown", operation(cm, onKeyDown));
- on(inp, "keypress", operation(cm, onKeyPress));
- on(inp, "focus", function (e) { return onFocus(cm, e); });
- on(inp, "blur", function (e) { return onBlur(cm, e); });
- }
+ ContentEditableInput.prototype.showPrimarySelection = function () {
+ var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
+ var from = prim.from(), to = prim.to();
- var initHooks = [];
- CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
+ if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
+ sel.removeAllRanges();
+ return
+ }
- // Indent the given line. The how parameter can be "smart",
- // "add"/null, "subtract", or "prev". When aggressive is false
- // (typically set to true for forced single-line indents), empty
- // lines are not indented, and places where the mode returns Pass
- // are left alone.
- function indentLine(cm, n, how, aggressive) {
- var doc = cm.doc, state;
- if (how == null) { how = "add"; }
- if (how == "smart") {
- // Fall back to "prev" when the mode doesn't have an indentation
- // method.
- if (!doc.mode.indent) { how = "prev"; }
- else { state = getStateBefore(cm, n); }
- }
+ var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
+ cmp(minPos(curAnchor, curFocus), from) == 0 &&
+ cmp(maxPos(curAnchor, curFocus), to) == 0)
+ { return }
- var tabSize = cm.options.tabSize;
- var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
- if (line.stateAfter) { line.stateAfter = null; }
- var curSpaceString = line.text.match(/^\s*/)[0], indentation;
- if (!aggressive && !/\S/.test(line.text)) {
- indentation = 0;
- how = "not";
- } else if (how == "smart") {
- indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
- if (indentation == Pass || indentation > 150) {
- if (!aggressive) { return }
- how = "prev";
- }
- }
- if (how == "prev") {
- if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
- else { indentation = 0; }
- } else if (how == "add") {
- indentation = curSpace + cm.options.indentUnit;
- } else if (how == "subtract") {
- indentation = curSpace - cm.options.indentUnit;
- } else if (typeof how == "number") {
- indentation = curSpace + how;
+ var view = cm.display.view;
+ var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
+ {node: view[0].measure.map[2], offset: 0};
+ var end = to.line < cm.display.viewTo && posToDOM(cm, to);
+ if (!end) {
+ var measure = view[view.length - 1].measure;
+ var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
+ end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
}
- indentation = Math.max(0, indentation);
- var indentString = "", pos = 0;
- if (cm.options.indentWithTabs)
- { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
- if (pos < indentation) { indentString += spaceStr(indentation - pos); }
+ if (!start || !end) {
+ sel.removeAllRanges();
+ return
+ }
- if (indentString != curSpaceString) {
- replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
- line.stateAfter = null;
- return true
- } else {
- // Ensure that, if the cursor was in the whitespace at the start
- // of the line, it is moved to the end of that space.
- for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
- var range = doc.sel.ranges[i$1];
- if (range.head.line == n && range.head.ch < curSpaceString.length) {
- var pos$1 = Pos(n, curSpaceString.length);
- replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
- break
+ var old = sel.rangeCount && sel.getRangeAt(0), rng;
+ try { rng = range(start.node, start.offset, end.offset, end.node); }
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
+ if (rng) {
+ if (!gecko && cm.state.focused) {
+ sel.collapse(start.node, start.offset);
+ if (!rng.collapsed) {
+ sel.removeAllRanges();
+ sel.addRange(rng);
}
+ } else {
+ sel.removeAllRanges();
+ sel.addRange(rng);
}
+ if (old && sel.anchorNode == null) { sel.addRange(old); }
+ else if (gecko) { this.startGracePeriod(); }
}
- }
-
- // This will be set to a {lineWise: bool, text: [string]} object, so
- // that, when pasting, we know what kind of selections the copied
- // text was made out of.
- var lastCopied = null;
+ this.rememberSelection();
+ };
- function setLastCopied(newLastCopied) {
- lastCopied = newLastCopied;
- }
+ ContentEditableInput.prototype.startGracePeriod = function () {
+ var this$1 = this;
- function applyTextInput(cm, inserted, deleted, sel, origin) {
- var doc = cm.doc;
- cm.display.shift = false;
- if (!sel) { sel = doc.sel; }
+ clearTimeout(this.gracePeriod);
+ this.gracePeriod = setTimeout(function () {
+ this$1.gracePeriod = false;
+ if (this$1.selectionChanged())
+ { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
+ }, 20);
+ };
- var paste = cm.state.pasteIncoming || origin == "paste";
- var textLines = splitLinesAuto(inserted), multiPaste = null;
- // When pasing N lines into N selections, insert one line per selection
- if (paste && sel.ranges.length > 1) {
- if (lastCopied && lastCopied.text.join("\n") == inserted) {
- if (sel.ranges.length % lastCopied.text.length == 0) {
- multiPaste = [];
- for (var i = 0; i < lastCopied.text.length; i++)
- { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
- }
- } else if (textLines.length == sel.ranges.length) {
- multiPaste = map(textLines, function (l) { return [l]; });
- }
- }
+ ContentEditableInput.prototype.showMultipleSelections = function (info) {
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
+ };
- var updateInput;
- // Normal behavior is to insert the new text into every selection
- for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
- var range$$1 = sel.ranges[i$1];
- var from = range$$1.from(), to = range$$1.to();
- if (range$$1.empty()) {
- if (deleted && deleted > 0) // Handle deletion
- { from = Pos(from.line, from.ch - deleted); }
- else if (cm.state.overwrite && !paste) // Handle overwrite
- { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
- else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
- { from = to = Pos(from.line, 0); }
- }
- updateInput = cm.curOp.updateInput;
- var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
- origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
- makeChange(cm.doc, changeEvent);
- signalLater(cm, "inputRead", cm, changeEvent);
- }
- if (inserted && !paste)
- { triggerElectric(cm, inserted); }
+ ContentEditableInput.prototype.rememberSelection = function () {
+ var sel = window.getSelection();
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
+ };
- ensureCursorVisible(cm);
- cm.curOp.updateInput = updateInput;
- cm.curOp.typing = true;
- cm.state.pasteIncoming = cm.state.cutIncoming = false;
- }
+ ContentEditableInput.prototype.selectionInEditor = function () {
+ var sel = window.getSelection();
+ if (!sel.rangeCount) { return false }
+ var node = sel.getRangeAt(0).commonAncestorContainer;
+ return contains(this.div, node)
+ };
- function handlePaste(e, cm) {
- var pasted = e.clipboardData && e.clipboardData.getData("Text");
- if (pasted) {
- e.preventDefault();
- if (!cm.isReadOnly() && !cm.options.disableInput)
- { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
- return true
+ ContentEditableInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor") {
+ if (!this.selectionInEditor())
+ { this.showSelection(this.prepareSelection(), true); }
+ this.div.focus();
}
- }
+ };
+ ContentEditableInput.prototype.blur = function () { this.div.blur(); };
+ ContentEditableInput.prototype.getField = function () { return this.div };
- function triggerElectric(cm, inserted) {
- // When an 'electric' character is inserted, immediately trigger a reindent
- if (!cm.options.electricChars || !cm.options.smartIndent) { return }
- var sel = cm.doc.sel;
+ ContentEditableInput.prototype.supportsTouch = function () { return true };
- for (var i = sel.ranges.length - 1; i >= 0; i--) {
- var range$$1 = sel.ranges[i];
- if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
- var mode = cm.getModeAt(range$$1.head);
- var indented = false;
- if (mode.electricChars) {
- for (var j = 0; j < mode.electricChars.length; j++)
- { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
- indented = indentLine(cm, range$$1.head.line, "smart");
- break
- } }
- } else if (mode.electricInput) {
- if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
- { indented = indentLine(cm, range$$1.head.line, "smart"); }
+ ContentEditableInput.prototype.receivedFocus = function () {
+ var input = this;
+ if (this.selectionInEditor())
+ { this.pollSelection(); }
+ else
+ { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
+
+ function poll() {
+ if (input.cm.state.focused) {
+ input.pollSelection();
+ input.polling.set(input.cm.options.pollInterval, poll);
}
- if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
}
- }
+ this.polling.set(this.cm.options.pollInterval, poll);
+ };
- function copyableRanges(cm) {
- var text = [], ranges = [];
- for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
- var line = cm.doc.sel.ranges[i].head.line;
- var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
- ranges.push(lineRange);
- text.push(cm.getRange(lineRange.anchor, lineRange.head));
+ ContentEditableInput.prototype.selectionChanged = function () {
+ var sel = window.getSelection();
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
+ };
+
+ ContentEditableInput.prototype.pollSelection = function () {
+ if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
+ var sel = window.getSelection(), cm = this.cm;
+ // On Android Chrome (version 56, at least), backspacing into an
+ // uneditable block element will put the cursor in that element,
+ // and then, because it's not editable, hide the virtual keyboard.
+ // Because Android doesn't allow us to actually detect backspace
+ // presses in a sane way, this code checks for when that happens
+ // and simulates a backspace press in this case.
+ if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
+ this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
+ this.blur();
+ this.focus();
+ return
}
- return {text: text, ranges: ranges}
- }
+ if (this.composing) { return }
+ this.rememberSelection();
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (anchor && head) { runInOp(cm, function () {
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
+ if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
+ }); }
+ };
- function disableBrowserMagic(field, spellcheck) {
- field.setAttribute("autocorrect", "off");
- field.setAttribute("autocapitalize", "off");
- field.setAttribute("spellcheck", !!spellcheck);
- }
+ ContentEditableInput.prototype.pollContent = function () {
+ if (this.readDOMTimeout != null) {
+ clearTimeout(this.readDOMTimeout);
+ this.readDOMTimeout = null;
+ }
- function hiddenTextarea() {
- var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
- var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
- // The textarea is kept positioned near the cursor to prevent the
- // fact that it'll be scrolled into view on input from scrolling
- // our fake cursor out of view. On webkit, when wrap=off, paste is
- // very slow. So make the area wide instead.
- if (webkit) { te.style.width = "1000px"; }
- else { te.setAttribute("wrap", "off"); }
- // If border: 0; -- iOS fails to open keyboard (issue #1287)
- if (ios) { te.style.border = "1px solid black"; }
- disableBrowserMagic(te);
- return div
- }
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
+ var from = sel.from(), to = sel.to();
+ if (from.ch == 0 && from.line > cm.firstLine())
+ { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
+ if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
+ { to = Pos(to.line + 1, 0); }
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
- // The publicly visible API. Note that methodOp(f) means
- // 'wrap f in an operation, performed on its `this` parameter'.
+ var fromIndex, fromLine, fromNode;
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
+ fromLine = lineNo(display.view[0].line);
+ fromNode = display.view[0].node;
+ } else {
+ fromLine = lineNo(display.view[fromIndex].line);
+ fromNode = display.view[fromIndex - 1].node.nextSibling;
+ }
+ var toIndex = findViewIndex(cm, to.line);
+ var toLine, toNode;
+ if (toIndex == display.view.length - 1) {
+ toLine = display.viewTo - 1;
+ toNode = display.lineDiv.lastChild;
+ } else {
+ toLine = lineNo(display.view[toIndex + 1].line) - 1;
+ toNode = display.view[toIndex + 1].node.previousSibling;
+ }
- // This is not the complete set of editor methods. Most of the
- // methods defined on the Doc type are also injected into
- // CodeMirror.prototype, for backwards compatibility and
- // convenience.
+ if (!fromNode) { return false }
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
+ while (newText.length > 1 && oldText.length > 1) {
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
+ else { break }
+ }
- var addEditorMethods = function(CodeMirror) {
- var optionHandlers = CodeMirror.optionHandlers;
+ var cutFront = 0, cutEnd = 0;
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
+ { ++cutFront; }
+ var newBot = lst(newText), oldBot = lst(oldText);
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
+ while (cutEnd < maxCutEnd &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
+ { ++cutEnd; }
+ // Try to move start of change to start of selection if ambiguous
+ if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
+ while (cutFront && cutFront > from.ch &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
+ cutFront--;
+ cutEnd++;
+ }
+ }
- var helpers = CodeMirror.helpers = {};
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
+ newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
- CodeMirror.prototype = {
- constructor: CodeMirror,
- focus: function(){window.focus(); this.display.input.focus();},
+ var chFrom = Pos(fromLine, cutFront);
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
+ return true
+ }
+ };
- setOption: function(option, value) {
- var options = this.options, old = options[option];
- if (options[option] == value && option != "mode") { return }
- options[option] = value;
- if (optionHandlers.hasOwnProperty(option))
- { operation(this, optionHandlers[option])(this, value, old); }
- signal(this, "optionChange", this, option);
- },
+ ContentEditableInput.prototype.ensurePolled = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.reset = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.forceCompositionEnd = function () {
+ if (!this.composing) { return }
+ clearTimeout(this.readDOMTimeout);
+ this.composing = null;
+ this.updateFromDOM();
+ this.div.blur();
+ this.div.focus();
+ };
+ ContentEditableInput.prototype.readFromDOMSoon = function () {
+ var this$1 = this;
- getOption: function(option) {return this.options[option]},
- getDoc: function() {return this.doc},
+ if (this.readDOMTimeout != null) { return }
+ this.readDOMTimeout = setTimeout(function () {
+ this$1.readDOMTimeout = null;
+ if (this$1.composing) {
+ if (this$1.composing.done) { this$1.composing = null; }
+ else { return }
+ }
+ this$1.updateFromDOM();
+ }, 80);
+ };
- addKeyMap: function(map$$1, bottom) {
- this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
- },
- removeKeyMap: function(map$$1) {
- var maps = this.state.keyMaps;
- for (var i = 0; i < maps.length; ++i)
- { if (maps[i] == map$$1 || maps[i].name == map$$1) {
- maps.splice(i, 1);
- return true
- } }
- },
+ ContentEditableInput.prototype.updateFromDOM = function () {
+ var this$1 = this;
- addOverlay: methodOp(function(spec, options) {
- var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
- if (mode.startState) { throw new Error("Overlays may not be stateful.") }
- insertSorted(this.state.overlays,
- {mode: mode, modeSpec: spec, opaque: options && options.opaque,
- priority: (options && options.priority) || 0},
- function (overlay) { return overlay.priority; });
- this.state.modeGen++;
- regChange(this);
- }),
- removeOverlay: methodOp(function(spec) {
- var this$1 = this;
+ if (this.cm.isReadOnly() || !this.pollContent())
+ { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
+ };
- var overlays = this.state.overlays;
- for (var i = 0; i < overlays.length; ++i) {
- var cur = overlays[i].modeSpec;
- if (cur == spec || typeof spec == "string" && cur.name == spec) {
- overlays.splice(i, 1);
- this$1.state.modeGen++;
- regChange(this$1);
- return
- }
- }
- }),
+ ContentEditableInput.prototype.setUneditable = function (node) {
+ node.contentEditable = "false";
+ };
- indentLine: methodOp(function(n, dir, aggressive) {
- if (typeof dir != "string" && typeof dir != "number") {
- if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
- else { dir = dir ? "add" : "subtract"; }
- }
- if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
- }),
- indentSelection: methodOp(function(how) {
- var this$1 = this;
+ ContentEditableInput.prototype.onKeyPress = function (e) {
+ if (e.charCode == 0) { return }
+ e.preventDefault();
+ if (!this.cm.isReadOnly())
+ { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
+ };
- var ranges = this.doc.sel.ranges, end = -1;
- for (var i = 0; i < ranges.length; i++) {
- var range$$1 = ranges[i];
- if (!range$$1.empty()) {
- var from = range$$1.from(), to = range$$1.to();
- var start = Math.max(end, from.line);
- end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
- for (var j = start; j < end; ++j)
- { indentLine(this$1, j, how); }
- var newRanges = this$1.doc.sel.ranges;
- if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
- { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
- } else if (range$$1.head.line > end) {
- indentLine(this$1, range$$1.head.line, how, true);
- end = range$$1.head.line;
- if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
- }
- }
- }),
+ ContentEditableInput.prototype.readOnlyChanged = function (val) {
+ this.div.contentEditable = String(val != "nocursor");
+ };
- // Fetch the parser token for a given character. Useful for hacks
- // that want to inspect the mode state (say, for completion).
- getTokenAt: function(pos, precise) {
- return takeToken(this, pos, precise)
- },
+ ContentEditableInput.prototype.onContextMenu = function () {};
+ ContentEditableInput.prototype.resetPosition = function () {};
- getLineTokens: function(line, precise) {
- return takeToken(this, Pos(line), precise, true)
- },
+ ContentEditableInput.prototype.needsContentAttribute = true;
- getTokenTypeAt: function(pos) {
- pos = clipPos(this.doc, pos);
- var styles = getLineStyles(this, getLine(this.doc, pos.line));
- var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
- var type;
- if (ch == 0) { type = styles[2]; }
- else { for (;;) {
- var mid = (before + after) >> 1;
- if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
- else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
- else { type = styles[mid * 2 + 2]; break }
- } }
- var cut = type ? type.indexOf("overlay ") : -1;
- return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
- },
+ function posToDOM(cm, pos) {
+ var view = findViewForLine(cm, pos.line);
+ if (!view || view.hidden) { return null }
+ var line = getLine(cm.doc, pos.line);
+ var info = mapFromLineView(view, line, pos.line);
- getModeAt: function(pos) {
- var mode = this.doc.mode;
- if (!mode.innerMode) { return mode }
- return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
- },
+ var order = getOrder(line, cm.doc.direction), side = "left";
+ if (order) {
+ var partPos = getBidiPartAt(order, pos.ch);
+ side = partPos % 2 ? "right" : "left";
+ }
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
+ result.offset = result.collapse == "right" ? result.end : result.start;
+ return result
+ }
- getHelper: function(pos, type) {
- return this.getHelpers(pos, type)[0]
- },
+ function isInGutter(node) {
+ for (var scan = node; scan; scan = scan.parentNode)
+ { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
+ return false
+ }
- getHelpers: function(pos, type) {
- var this$1 = this;
+ function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
- var found = [];
- if (!helpers.hasOwnProperty(type)) { return found }
- var help = helpers[type], mode = this.getModeAt(pos);
- if (typeof mode[type] == "string") {
- if (help[mode[type]]) { found.push(help[mode[type]]); }
- } else if (mode[type]) {
- for (var i = 0; i < mode[type].length; i++) {
- var val = help[mode[type][i]];
- if (val) { found.push(val); }
- }
- } else if (mode.helperType && help[mode.helperType]) {
- found.push(help[mode.helperType]);
- } else if (help[mode.name]) {
- found.push(help[mode.name]);
+ function domTextBetween(cm, from, to, fromLine, toLine) {
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
+ function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
+ function close() {
+ if (closing) {
+ text += lineSep;
+ closing = false;
+ }
+ }
+ function addText(str) {
+ if (str) {
+ close();
+ text += str;
+ }
+ }
+ function walk(node) {
+ if (node.nodeType == 1) {
+ var cmText = node.getAttribute("cm-text");
+ if (cmText != null) {
+ addText(cmText || node.textContent.replace(/\u200b/g, ""));
+ return
}
- for (var i$1 = 0; i$1 < help._global.length; i$1++) {
- var cur = help._global[i$1];
- if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
- { found.push(cur.val); }
+ var markerID = node.getAttribute("cm-marker"), range$$1;
+ if (markerID) {
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
+ if (found.length && (range$$1 = found[0].find(0)))
+ { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
+ return
}
- return found
- },
-
- getStateAfter: function(line, precise) {
- var doc = this.doc;
- line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
- return getStateBefore(this, line + 1, precise)
- },
+ if (node.getAttribute("contenteditable") == "false") { return }
+ var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
+ if (isBlock) { close(); }
+ for (var i = 0; i < node.childNodes.length; i++)
+ { walk(node.childNodes[i]); }
+ if (isBlock) { closing = true; }
+ } else if (node.nodeType == 3) {
+ addText(node.nodeValue);
+ }
+ }
+ for (;;) {
+ walk(from);
+ if (from == to) { break }
+ from = from.nextSibling;
+ }
+ return text
+ }
- cursorCoords: function(start, mode) {
- var pos, range$$1 = this.doc.sel.primary();
- if (start == null) { pos = range$$1.head; }
- else if (typeof start == "object") { pos = clipPos(this.doc, start); }
- else { pos = start ? range$$1.from() : range$$1.to(); }
- return cursorCoords(this, pos, mode || "page")
- },
+ function domToPos(cm, node, offset) {
+ var lineNode;
+ if (node == cm.display.lineDiv) {
+ lineNode = cm.display.lineDiv.childNodes[offset];
+ if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
+ node = null; offset = 0;
+ } else {
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
+ if (!lineNode || lineNode == cm.display.lineDiv) { return null }
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
+ }
+ }
+ for (var i = 0; i < cm.display.view.length; i++) {
+ var lineView = cm.display.view[i];
+ if (lineView.node == lineNode)
+ { return locateNodeInLineView(lineView, node, offset) }
+ }
+ }
- charCoords: function(pos, mode) {
- return charCoords(this, clipPos(this.doc, pos), mode || "page")
- },
+ function locateNodeInLineView(lineView, node, offset) {
+ var wrapper = lineView.text.firstChild, bad = false;
+ if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
+ if (node == wrapper) {
+ bad = true;
+ node = wrapper.childNodes[offset];
+ offset = 0;
+ if (!node) {
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
+ return badPos(Pos(lineNo(line), line.text.length), bad)
+ }
+ }
- coordsChar: function(coords, mode) {
- coords = fromCoordSystem(this, coords, mode || "page");
- return coordsChar(this, coords.left, coords.top)
- },
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
+ textNode = node.firstChild;
+ if (offset) { offset = textNode.nodeValue.length; }
+ }
+ while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
+ var measure = lineView.measure, maps = measure.maps;
- lineAtHeight: function(height, mode) {
- height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
- return lineAtHeight(this.doc, height + this.display.viewOffset)
- },
- heightAtLine: function(line, mode, includeWidgets) {
- var end = false, lineObj;
- if (typeof line == "number") {
- var last = this.doc.first + this.doc.size - 1;
- if (line < this.doc.first) { line = this.doc.first; }
- else if (line > last) { line = last; end = true; }
- lineObj = getLine(this.doc, line);
- } else {
- lineObj = line;
+ function find(textNode, topNode, offset) {
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
+ var map$$1 = i < 0 ? measure.map : maps[i];
+ for (var j = 0; j < map$$1.length; j += 3) {
+ var curNode = map$$1[j + 2];
+ if (curNode == textNode || curNode == topNode) {
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
+ var ch = map$$1[j] + offset;
+ if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
+ return Pos(line, ch)
+ }
}
- return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
- (end ? this.doc.height - heightAtLine(lineObj) : 0)
- },
-
- defaultTextHeight: function() { return textHeight(this.display) },
- defaultCharWidth: function() { return charWidth(this.display) },
+ }
+ }
+ var found = find(textNode, topNode, offset);
+ if (found) { return badPos(found, bad) }
- getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
+ found = find(after, after.firstChild, 0);
+ if (found)
+ { return badPos(Pos(found.line, found.ch - dist), bad) }
+ else
+ { dist += after.textContent.length; }
+ }
+ for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
+ found = find(before, before.firstChild, -1);
+ if (found)
+ { return badPos(Pos(found.line, found.ch + dist$1), bad) }
+ else
+ { dist$1 += before.textContent.length; }
+ }
+ }
- addWidget: function(pos, node, scroll, vert, horiz) {
- var display = this.display;
- pos = cursorCoords(this, clipPos(this.doc, pos));
- var top = pos.bottom, left = pos.left;
- node.style.position = "absolute";
- node.setAttribute("cm-ignore-events", "true");
- this.display.input.setUneditable(node);
- display.sizer.appendChild(node);
- if (vert == "over") {
- top = pos.top;
- } else if (vert == "above" || vert == "near") {
- var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
- hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
- // Default to positioning above (if specified and possible); otherwise default to positioning below
- if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
- { top = pos.top - node.offsetHeight; }
- else if (pos.bottom + node.offsetHeight <= vspace)
- { top = pos.bottom; }
- if (left + node.offsetWidth > hspace)
- { left = hspace - node.offsetWidth; }
- }
- node.style.top = top + "px";
- node.style.left = node.style.right = "";
- if (horiz == "right") {
- left = display.sizer.clientWidth - node.offsetWidth;
- node.style.right = "0px";
- } else {
- if (horiz == "left") { left = 0; }
- else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
- node.style.left = left + "px";
- }
- if (scroll)
- { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
- },
+ // TEXTAREA INPUT STYLE
- triggerOnKeyDown: methodOp(onKeyDown),
- triggerOnKeyPress: methodOp(onKeyPress),
- triggerOnKeyUp: onKeyUp,
+ var TextareaInput = function(cm) {
+ this.cm = cm;
+ // See input.poll and input.reset
+ this.prevInput = "";
- execCommand: function(cmd) {
- if (commands.hasOwnProperty(cmd))
- { return commands[cmd].call(null, this) }
- },
+ // Flag that indicates whether we expect input to appear real soon
+ // now (after some event like 'keypress' or 'input') and are
+ // polling intensively.
+ this.pollingFast = false;
+ // Self-resetting timeout for the poller
+ this.polling = new Delayed();
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
+ this.hasSelection = false;
+ this.composing = null;
+ };
- triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
+ TextareaInput.prototype.init = function (display) {
+ var this$1 = this;
- findPosH: function(from, amount, unit, visually) {
- var this$1 = this;
+ var input = this, cm = this.cm;
- var dir = 1;
- if (amount < 0) { dir = -1; amount = -amount; }
- var cur = clipPos(this.doc, from);
- for (var i = 0; i < amount; ++i) {
- cur = findPosH(this$1.doc, cur, dir, unit, visually);
- if (cur.hitSide) { break }
- }
- return cur
- },
+ // Wraps and hides input textarea
+ var div = this.wrapper = hiddenTextarea();
+ // The semihidden textarea that is focused when the editor is
+ // focused, and receives input.
+ var te = this.textarea = div.firstChild;
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
- moveH: methodOp(function(dir, unit) {
- var this$1 = this;
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
+ if (ios) { te.style.width = "0px"; }
- this.extendSelectionsBy(function (range$$1) {
- if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
- { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
- else
- { return dir < 0 ? range$$1.from() : range$$1.to() }
- }, sel_move);
- }),
+ on(te, "input", function () {
+ if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
+ input.poll();
+ });
- deleteH: methodOp(function(dir, unit) {
- var sel = this.doc.sel, doc = this.doc;
- if (sel.somethingSelected())
- { doc.replaceSelection("", null, "+delete"); }
- else
- { deleteNearSelection(this, function (range$$1) {
- var other = findPosH(doc, range$$1.head, dir, unit, false);
- return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
- }); }
- }),
+ on(te, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
- findPosV: function(from, amount, unit, goalColumn) {
- var this$1 = this;
+ cm.state.pasteIncoming = true;
+ input.fastPoll();
+ });
- var dir = 1, x = goalColumn;
- if (amount < 0) { dir = -1; amount = -amount; }
- var cur = clipPos(this.doc, from);
- for (var i = 0; i < amount; ++i) {
- var coords = cursorCoords(this$1, cur, "div");
- if (x == null) { x = coords.left; }
- else { coords.left = x; }
- cur = findPosV(this$1, coords, dir, unit);
- if (cur.hitSide) { break }
+ function prepareCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
+ } else {
+ input.prevInput = "";
+ te.value = ranges.text.join("\n");
+ selectInput(te);
}
- return cur
- },
+ }
+ if (e.type == "cut") { cm.state.cutIncoming = true; }
+ }
+ on(te, "cut", prepareCopyCut);
+ on(te, "copy", prepareCopyCut);
- moveV: methodOp(function(dir, unit) {
- var this$1 = this;
+ on(display.scroller, "paste", function (e) {
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
+ cm.state.pasteIncoming = true;
+ input.focus();
+ });
- var doc = this.doc, goals = [];
- var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
- doc.extendSelectionsBy(function (range$$1) {
- if (collapse)
- { return dir < 0 ? range$$1.from() : range$$1.to() }
- var headPos = cursorCoords(this$1, range$$1.head, "div");
- if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
- goals.push(headPos.left);
- var pos = findPosV(this$1, headPos, dir, unit);
- if (unit == "page" && range$$1 == doc.sel.primary())
- { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top); }
- return pos
- }, sel_move);
- if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
- { doc.sel.ranges[i].goalColumn = goals[i]; } }
- }),
+ // Prevent normal selection in the editor (we handle our own)
+ on(display.lineSpace, "selectstart", function (e) {
+ if (!eventInWidget(display, e)) { e_preventDefault(e); }
+ });
- // Find the word at the given position (as returned by coordsChar).
- findWordAt: function(pos) {
- var doc = this.doc, line = getLine(doc, pos.line).text;
- var start = pos.ch, end = pos.ch;
- if (line) {
- var helper = this.getHelper(pos, "wordChars");
- if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
- var startChar = line.charAt(start);
- var check = isWordChar(startChar, helper)
- ? function (ch) { return isWordChar(ch, helper); }
- : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
- : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
- while (start > 0 && check(line.charAt(start - 1))) { --start; }
- while (end < line.length && check(line.charAt(end))) { ++end; }
- }
- return new Range(Pos(pos.line, start), Pos(pos.line, end))
- },
+ on(te, "compositionstart", function () {
+ var start = cm.getCursor("from");
+ if (input.composing) { input.composing.range.clear(); }
+ input.composing = {
+ start: start,
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
+ };
+ });
+ on(te, "compositionend", function () {
+ if (input.composing) {
+ input.poll();
+ input.composing.range.clear();
+ input.composing = null;
+ }
+ });
+ };
- toggleOverwrite: function(value) {
- if (value != null && value == this.state.overwrite) { return }
- if (this.state.overwrite = !this.state.overwrite)
- { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
- else
- { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+ TextareaInput.prototype.prepareSelection = function () {
+ // Redraw the selection and/or cursor
+ var cm = this.cm, display = cm.display, doc = cm.doc;
+ var result = prepareSelection(cm);
- signal(this, "overwriteToggle", this, this.state.overwrite);
- },
- hasFocus: function() { return this.display.input.getField() == activeElt() },
- isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
+ if (cm.options.moveInputWithCursor) {
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top));
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left));
+ }
- scrollTo: methodOp(function(x, y) {
- if (x != null || y != null) { resolveScrollToPos(this); }
- if (x != null) { this.curOp.scrollLeft = x; }
- if (y != null) { this.curOp.scrollTop = y; }
- }),
- getScrollInfo: function() {
- var scroller = this.display.scroller;
- return {left: scroller.scrollLeft, top: scroller.scrollTop,
- height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
- width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
- clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
- },
+ return result
+ };
- scrollIntoView: methodOp(function(range$$1, margin) {
- if (range$$1 == null) {
- range$$1 = {from: this.doc.sel.primary().head, to: null};
- if (margin == null) { margin = this.options.cursorScrollMargin; }
- } else if (typeof range$$1 == "number") {
- range$$1 = {from: Pos(range$$1, 0), to: null};
- } else if (range$$1.from == null) {
- range$$1 = {from: range$$1, to: null};
- }
- if (!range$$1.to) { range$$1.to = range$$1.from; }
- range$$1.margin = margin || 0;
+ TextareaInput.prototype.showSelection = function (drawn) {
+ var cm = this.cm, display = cm.display;
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
+ if (drawn.teTop != null) {
+ this.wrapper.style.top = drawn.teTop + "px";
+ this.wrapper.style.left = drawn.teLeft + "px";
+ }
+ };
- if (range$$1.from.line != null) {
- resolveScrollToPos(this);
- this.curOp.scrollToPos = range$$1;
- } else {
- var sPos = calculateScrollPos(this, {
- left: Math.min(range$$1.from.left, range$$1.to.left),
- top: Math.min(range$$1.from.top, range$$1.to.top) - range$$1.margin,
- right: Math.max(range$$1.from.right, range$$1.to.right),
- bottom: Math.max(range$$1.from.bottom, range$$1.to.bottom) + range$$1.margin
- });
- this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
- }
- }),
+ // Reset the input to correspond to the selection (or to be empty,
+ // when not typing and nothing is selected)
+ TextareaInput.prototype.reset = function (typing) {
+ if (this.contextMenuPending || this.composing) { return }
+ var cm = this.cm;
+ if (cm.somethingSelected()) {
+ this.prevInput = "";
+ var content = cm.getSelection();
+ this.textarea.value = content;
+ if (cm.state.focused) { selectInput(this.textarea); }
+ if (ie && ie_version >= 9) { this.hasSelection = content; }
+ } else if (!typing) {
+ this.prevInput = this.textarea.value = "";
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ }
+ };
- setSize: methodOp(function(width, height) {
- var this$1 = this;
+ TextareaInput.prototype.getField = function () { return this.textarea };
- var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
- if (width != null) { this.display.wrapper.style.width = interpret(width); }
- if (height != null) { this.display.wrapper.style.height = interpret(height); }
- if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
- var lineNo$$1 = this.display.viewFrom;
- this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
- if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
- { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
- ++lineNo$$1;
- });
- this.curOp.forceUpdate = true;
- signal(this, "refresh", this);
- }),
+ TextareaInput.prototype.supportsTouch = function () { return false };
- operation: function(f){return runInOp(this, f)},
+ TextareaInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
+ try { this.textarea.focus(); }
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
+ }
+ };
- refresh: methodOp(function() {
- var oldHeight = this.display.cachedTextHeight;
- regChange(this);
- this.curOp.forceUpdate = true;
- clearCaches(this);
- this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
- updateGutterSpace(this);
- if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
- { estimateLineHeights(this); }
- signal(this, "refresh", this);
- }),
+ TextareaInput.prototype.blur = function () { this.textarea.blur(); };
- swapDoc: methodOp(function(doc) {
- var old = this.doc;
- old.cm = null;
- attachDoc(this, doc);
- clearCaches(this);
- this.display.input.reset();
- this.scrollTo(doc.scrollLeft, doc.scrollTop);
- this.curOp.forceScroll = true;
- signalLater(this, "swapDoc", this, old);
- return old
- }),
+ TextareaInput.prototype.resetPosition = function () {
+ this.wrapper.style.top = this.wrapper.style.left = 0;
+ };
- getInputField: function(){return this.display.input.getField()},
- getWrapperElement: function(){return this.display.wrapper},
- getScrollerElement: function(){return this.display.scroller},
- getGutterElement: function(){return this.display.gutters}
- };
- eventMixin(CodeMirror);
+ TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
- CodeMirror.registerHelper = function(type, name, value) {
- if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
- helpers[type][name] = value;
- };
- CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
- CodeMirror.registerHelper(type, name, value);
- helpers[type]._global.push({pred: predicate, val: value});
- };
- };
+ // Poll for input changes, using the normal rate of polling. This
+ // runs as long as the editor is focused.
+ TextareaInput.prototype.slowPoll = function () {
+ var this$1 = this;
- // Used for horizontal relative motion. Dir is -1 or 1 (left or
- // right), unit can be "char", "column" (like char, but doesn't
- // cross line boundaries), "word" (across next word), or "group" (to
- // the start of next group of word or non-word-non-whitespace
- // chars). The visually param controls whether, in right-to-left
- // text, direction 1 means to move towards the next index in the
- // string, or towards the character to the right of the current
- // position. The resulting position will have a hitSide=true
- // property if it reached the end of the document.
- function findPosH(doc, pos, dir, unit, visually) {
- var oldPos = pos;
- var origDir = dir;
- var lineObj = getLine(doc, pos.line);
- function findNextLine() {
- var l = pos.line + dir;
- if (l < doc.first || l >= doc.first + doc.size) { return false }
- pos = new Pos(l, pos.ch, pos.sticky);
- return lineObj = getLine(doc, l)
- }
- function moveOnce(boundToLine) {
- var next;
- if (visually) {
- next = moveVisually(doc.cm, lineObj, pos, dir);
- } else {
- next = moveLogically(lineObj, pos, dir);
- }
- if (next == null) {
- if (!boundToLine && findNextLine())
- { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
- else
- { return false }
- } else {
- pos = next;
- }
- return true
- }
-
- if (unit == "char") {
- moveOnce();
- } else if (unit == "column") {
- moveOnce(true);
- } else if (unit == "word" || unit == "group") {
- var sawType = null, group = unit == "group";
- var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
- for (var first = true;; first = false) {
- if (dir < 0 && !moveOnce(!first)) { break }
- var cur = lineObj.text.charAt(pos.ch) || "\n";
- var type = isWordChar(cur, helper) ? "w"
- : group && cur == "\n" ? "n"
- : !group || /\s/.test(cur) ? null
- : "p";
- if (group && !first && !type) { type = "s"; }
- if (sawType && sawType != type) {
- if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
- break
- }
+ if (this.pollingFast) { return }
+ this.polling.set(this.cm.options.pollInterval, function () {
+ this$1.poll();
+ if (this$1.cm.state.focused) { this$1.slowPoll(); }
+ });
+ };
- if (type) { sawType = type; }
- if (dir > 0 && !moveOnce(!first)) { break }
- }
+ // When an event has just come in that is likely to add or change
+ // something in the input textarea, we poll faster, to ensure that
+ // the change appears on the screen quickly.
+ TextareaInput.prototype.fastPoll = function () {
+ var missed = false, input = this;
+ input.pollingFast = true;
+ function p() {
+ var changed = input.poll();
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
+ else {input.pollingFast = false; input.slowPoll();}
}
- var result = skipAtomic(doc, pos, oldPos, origDir, true);
- if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
- return result
- }
-
- // For relative vertical movement. Dir may be -1 or 1. Unit can be
- // "page" or "line". The resulting position will have a hitSide=true
- // property if it reached the end of the document.
- function findPosV(cm, pos, dir, unit) {
- var doc = cm.doc, x = pos.left, y;
- if (unit == "page") {
- var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
- var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
- y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
+ input.polling.set(20, p);
+ };
- } else if (unit == "line") {
- y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
- }
- var target;
- for (;;) {
- target = coordsChar(cm, x, y);
- if (!target.outside) { break }
- if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
- y += dir * 5;
- }
- return target
- }
+ // Read input from the textarea, and update the document to match.
+ // When something is selected, it is present in the textarea, and
+ // selected (unless it is huge, in which case a placeholder is
+ // used). When nothing is selected, the cursor sits after previously
+ // seen text (can be empty), which is stored in prevInput (we must
+ // not reset the textarea when typing, because that breaks IME).
+ TextareaInput.prototype.poll = function () {
+ var this$1 = this;
- // CONTENTEDITABLE INPUT STYLE
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
+ // Since this is called a *lot*, try to bail out as cheaply as
+ // possible when it is clear that nothing happened. hasSelection
+ // will be the case when there is a lot of text in the textarea,
+ // in which case reading its value would be expensive.
+ if (this.contextMenuPending || !cm.state.focused ||
+ (hasSelection(input) && !prevInput && !this.composing) ||
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
+ { return false }
- var ContentEditableInput = function(cm) {
- this.cm = cm;
- this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
- this.polling = new Delayed();
- this.composing = null;
- this.gracePeriod = false;
- this.readDOMTimeout = null;
- };
+ var text = input.value;
+ // If nothing changed, bail.
+ if (text == prevInput && !cm.somethingSelected()) { return false }
+ // Work around nonsensical selection resetting in IE9/10, and
+ // inexplicable appearance of private area unicode characters on
+ // some key combos in Mac (#2689).
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
+ mac && /[\uf700-\uf7ff]/.test(text)) {
+ cm.display.input.reset();
+ return false
+ }
- ContentEditableInput.prototype.init = function (display) {
- var this$1 = this;
+ if (cm.doc.sel == cm.display.selForContextMenu) {
+ var first = text.charCodeAt(0);
+ if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
+ }
+ // Find the part of the input that is actually new
+ var same = 0, l = Math.min(prevInput.length, text.length);
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
- var input = this, cm = input.cm;
- var div = input.div = display.lineDiv;
- disableBrowserMagic(div, cm.options.spellcheck);
+ runInOp(cm, function () {
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
+ null, this$1.composing ? "*compose" : null);
- on(div, "paste", function (e) {
- if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
- // IE doesn't fire input events, so we schedule a read for the pasted content in this way
- if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
- });
+ // Don't leave long text in the textarea, since it makes further polling slow
+ if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
+ else { this$1.prevInput = text; }
- on(div, "compositionstart", function (e) {
- this$1.composing = {data: e.data, done: false};
- });
- on(div, "compositionupdate", function (e) {
- if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
- });
- on(div, "compositionend", function (e) {
if (this$1.composing) {
- if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
- this$1.composing.done = true;
+ this$1.composing.range.clear();
+ this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
+ {className: "CodeMirror-composing"});
}
});
+ return true
+ };
- on(div, "touchstart", function () { return input.forceCompositionEnd(); });
+ TextareaInput.prototype.ensurePolled = function () {
+ if (this.pollingFast && this.poll()) { this.pollingFast = false; }
+ };
- on(div, "input", function () {
- if (!this$1.composing) { this$1.readFromDOMSoon(); }
- });
+ TextareaInput.prototype.onKeyPress = function () {
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ this.fastPoll();
+ };
- function onCopyCut(e) {
- if (signalDOMEvent(cm, e)) { return }
- if (cm.somethingSelected()) {
- setLastCopied({lineWise: false, text: cm.getSelections()});
- if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
- } else if (!cm.options.lineWiseCopyCut) {
- return
- } else {
- var ranges = copyableRanges(cm);
- setLastCopied({lineWise: true, text: ranges.text});
- if (e.type == "cut") {
- cm.operation(function () {
- cm.setSelections(ranges.ranges, 0, sel_dontScroll);
- cm.replaceSelection("", null, "cut");
- });
- }
+ TextareaInput.prototype.onContextMenu = function (e) {
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+ if (!pos || presto) { return } // Opera is difficult.
+
+ // Reset the current text selection only if the click is done outside of the selection
+ // and 'resetSelectionOnContextMenu' option is true.
+ var reset = cm.options.resetSelectionOnContextMenu;
+ if (reset && cm.doc.sel.contains(pos) == -1)
+ { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
+
+ var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
+ input.wrapper.style.cssText = "position: absolute";
+ var wrapperBox = input.wrapper.getBoundingClientRect();
+ te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ var oldScrollY;
+ if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
+ display.input.focus();
+ if (webkit) { window.scrollTo(null, oldScrollY); }
+ display.input.reset();
+ // Adds "Select all" to context menu in FF
+ if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
+ input.contextMenuPending = true;
+ display.selForContextMenu = cm.doc.sel;
+ clearTimeout(display.detectingSelectAll);
+
+ // Select-all will be greyed out if there's nothing to select, so
+ // this adds a zero-width space so that we can later check whether
+ // it got selected.
+ function prepareSelectAllHack() {
+ if (te.selectionStart != null) {
+ var selected = cm.somethingSelected();
+ var extval = "\u200b" + (selected ? te.value : "");
+ te.value = "\u21da"; // Used to catch context-menu undo
+ te.value = extval;
+ input.prevInput = selected ? "" : "\u200b";
+ te.selectionStart = 1; te.selectionEnd = extval.length;
+ // Re-set this, in case some other handler touched the
+ // selection in the meantime.
+ display.selForContextMenu = cm.doc.sel;
}
- if (e.clipboardData) {
- e.clipboardData.clearData();
- var content = lastCopied.text.join("\n");
- // iOS exposes the clipboard API, but seems to discard content inserted into it
- e.clipboardData.setData("Text", content);
- if (e.clipboardData.getData("Text") == content) {
- e.preventDefault();
- return
- }
+ }
+ function rehide() {
+ input.contextMenuPending = false;
+ input.wrapper.style.cssText = oldWrapperCSS;
+ te.style.cssText = oldCSS;
+ if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
+
+ // Try to detect the user choosing select-all
+ if (te.selectionStart != null) {
+ if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
+ var i = 0, poll = function () {
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
+ te.selectionEnd > 0 && input.prevInput == "\u200b") {
+ operation(cm, selectAll)(cm);
+ } else if (i++ < 10) {
+ display.detectingSelectAll = setTimeout(poll, 500);
+ } else {
+ display.selForContextMenu = null;
+ display.input.reset();
+ }
+ };
+ display.detectingSelectAll = setTimeout(poll, 200);
}
- // Old-fashioned briefly-focus-a-textarea hack
- var kludge = hiddenTextarea(), te = kludge.firstChild;
- cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
- te.value = lastCopied.text.join("\n");
- var hadFocus = document.activeElement;
- selectInput(te);
- setTimeout(function () {
- cm.display.lineSpace.removeChild(kludge);
- hadFocus.focus();
- if (hadFocus == div) { input.showPrimarySelection(); }
- }, 50);
}
- on(div, "copy", onCopyCut);
- on(div, "cut", onCopyCut);
- };
- ContentEditableInput.prototype.prepareSelection = function () {
- var result = prepareSelection(this.cm, false);
- result.focus = this.cm.state.focused;
- return result
+ if (ie && ie_version >= 9) { prepareSelectAllHack(); }
+ if (captureRightClick) {
+ e_stop(e);
+ var mouseup = function () {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ };
+ on(window, "mouseup", mouseup);
+ } else {
+ setTimeout(rehide, 50);
+ }
};
- ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
- if (!info || !this.cm.display.view.length) { return }
- if (info.focus || takeFocus) { this.showPrimarySelection(); }
- this.showMultipleSelections(info);
+ TextareaInput.prototype.readOnlyChanged = function (val) {
+ if (!val) { this.reset(); }
+ this.textarea.disabled = val == "nocursor";
};
- ContentEditableInput.prototype.showPrimarySelection = function () {
- var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
- var from = prim.from(), to = prim.to();
-
- if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
- sel.removeAllRanges();
- return
- }
+ TextareaInput.prototype.setUneditable = function () {};
- var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
- var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
- if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
- cmp(minPos(curAnchor, curFocus), from) == 0 &&
- cmp(maxPos(curAnchor, curFocus), to) == 0)
- { return }
+ TextareaInput.prototype.needsContentAttribute = false;
- var view = cm.display.view;
- var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
- {node: view[0].measure.map[2], offset: 0};
- var end = to.line < cm.display.viewTo && posToDOM(cm, to);
- if (!end) {
- var measure = view[view.length - 1].measure;
- var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
- end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
+ function fromTextArea(textarea, options) {
+ options = options ? copyObj(options) : {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabIndex)
+ { options.tabindex = textarea.tabIndex; }
+ if (!options.placeholder && textarea.placeholder)
+ { options.placeholder = textarea.placeholder; }
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = activeElt();
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
- if (!start || !end) {
- sel.removeAllRanges();
- return
- }
+ function save() {textarea.value = cm.getValue();}
- var old = sel.rangeCount && sel.getRangeAt(0), rng;
- try { rng = range(start.node, start.offset, end.offset, end.node); }
- catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
- if (rng) {
- if (!gecko && cm.state.focused) {
- sel.collapse(start.node, start.offset);
- if (!rng.collapsed) {
- sel.removeAllRanges();
- sel.addRange(rng);
- }
- } else {
- sel.removeAllRanges();
- sel.addRange(rng);
+ var realSubmit;
+ if (textarea.form) {
+ on(textarea.form, "submit", save);
+ // Deplorable hack to make the submit method do the right thing.
+ if (!options.leaveSubmitMethodAlone) {
+ var form = textarea.form;
+ realSubmit = form.submit;
+ try {
+ var wrappedSubmit = form.submit = function () {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
}
- if (old && sel.anchorNode == null) { sel.addRange(old); }
- else if (gecko) { this.startGracePeriod(); }
}
- this.rememberSelection();
- };
- ContentEditableInput.prototype.startGracePeriod = function () {
- var this$1 = this;
+ options.finishInit = function (cm) {
+ cm.save = save;
+ cm.getTextArea = function () { return textarea; };
+ cm.toTextArea = function () {
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (typeof textarea.form.submit == "function")
+ { textarea.form.submit = realSubmit; }
+ }
+ };
+ };
- clearTimeout(this.gracePeriod);
- this.gracePeriod = setTimeout(function () {
- this$1.gracePeriod = false;
- if (this$1.selectionChanged())
- { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
- }, 20);
- };
+ textarea.style.display = "none";
+ var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
+ options);
+ return cm
+ }
- ContentEditableInput.prototype.showMultipleSelections = function (info) {
- removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
- removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
- };
+ function addLegacyProps(CodeMirror) {
+ CodeMirror.off = off;
+ CodeMirror.on = on;
+ CodeMirror.wheelEventPixels = wheelEventPixels;
+ CodeMirror.Doc = Doc;
+ CodeMirror.splitLines = splitLinesAuto;
+ CodeMirror.countColumn = countColumn;
+ CodeMirror.findColumn = findColumn;
+ CodeMirror.isWordChar = isWordCharBasic;
+ CodeMirror.Pass = Pass;
+ CodeMirror.signal = signal;
+ CodeMirror.Line = Line;
+ CodeMirror.changeEnd = changeEnd;
+ CodeMirror.scrollbarModel = scrollbarModel;
+ CodeMirror.Pos = Pos;
+ CodeMirror.cmpPos = cmp;
+ CodeMirror.modes = modes;
+ CodeMirror.mimeModes = mimeModes;
+ CodeMirror.resolveMode = resolveMode;
+ CodeMirror.getMode = getMode;
+ CodeMirror.modeExtensions = modeExtensions;
+ CodeMirror.extendMode = extendMode;
+ CodeMirror.copyState = copyState;
+ CodeMirror.startState = startState;
+ CodeMirror.innerMode = innerMode;
+ CodeMirror.commands = commands;
+ CodeMirror.keyMap = keyMap;
+ CodeMirror.keyName = keyName;
+ CodeMirror.isModifierKey = isModifierKey;
+ CodeMirror.lookupKey = lookupKey;
+ CodeMirror.normalizeKeyMap = normalizeKeyMap;
+ CodeMirror.StringStream = StringStream;
+ CodeMirror.SharedTextMarker = SharedTextMarker;
+ CodeMirror.TextMarker = TextMarker;
+ CodeMirror.LineWidget = LineWidget;
+ CodeMirror.e_preventDefault = e_preventDefault;
+ CodeMirror.e_stopPropagation = e_stopPropagation;
+ CodeMirror.e_stop = e_stop;
+ CodeMirror.addClass = addClass;
+ CodeMirror.contains = contains;
+ CodeMirror.rmClass = rmClass;
+ CodeMirror.keyNames = keyNames;
+ }
- ContentEditableInput.prototype.rememberSelection = function () {
- var sel = window.getSelection();
- this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
- this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
- };
+ // EDITOR CONSTRUCTOR
- ContentEditableInput.prototype.selectionInEditor = function () {
- var sel = window.getSelection();
- if (!sel.rangeCount) { return false }
- var node = sel.getRangeAt(0).commonAncestorContainer;
- return contains(this.div, node)
- };
+ defineOptions(CodeMirror$1);
- ContentEditableInput.prototype.focus = function () {
- if (this.cm.options.readOnly != "nocursor") {
- if (!this.selectionInEditor())
- { this.showSelection(this.prepareSelection(), true); }
- this.div.focus();
- }
- };
- ContentEditableInput.prototype.blur = function () { this.div.blur(); };
- ContentEditableInput.prototype.getField = function () { return this.div };
+ addEditorMethods(CodeMirror$1);
- ContentEditableInput.prototype.supportsTouch = function () { return true };
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
+ for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+ { CodeMirror$1.prototype[prop] = (function(method) {
+ return function() {return method.apply(this.doc, arguments)}
+ })(Doc.prototype[prop]); } }
- ContentEditableInput.prototype.receivedFocus = function () {
- var input = this;
- if (this.selectionInEditor())
- { this.pollSelection(); }
- else
- { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
+ eventMixin(Doc);
- function poll() {
- if (input.cm.state.focused) {
- input.pollSelection();
- input.polling.set(input.cm.options.pollInterval, poll);
- }
- }
- this.polling.set(this.cm.options.pollInterval, poll);
- };
+ // INPUT HANDLING
- ContentEditableInput.prototype.selectionChanged = function () {
- var sel = window.getSelection();
- return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
- sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
- };
+ CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
- ContentEditableInput.prototype.pollSelection = function () {
- if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
- var sel = window.getSelection(), cm = this.cm;
- // On Android Chrome (version 56, at least), backspacing into an
- // uneditable block element will put the cursor in that element,
- // and then, because it's not editable, hide the virtual keyboard.
- // Because Android doesn't allow us to actually detect backspace
- // presses in a sane way, this code checks for when that happens
- // and simulates a backspace press in this case.
- if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
- this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
- this.blur();
- this.focus();
- return
- }
- if (this.composing) { return }
- this.rememberSelection();
- var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
- var head = domToPos(cm, sel.focusNode, sel.focusOffset);
- if (anchor && head) { runInOp(cm, function () {
- setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
- if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
- }); }
- };
-
- ContentEditableInput.prototype.pollContent = function () {
- if (this.readDOMTimeout != null) {
- clearTimeout(this.readDOMTimeout);
- this.readDOMTimeout = null;
- }
-
- var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
- var from = sel.from(), to = sel.to();
- if (from.ch == 0 && from.line > cm.firstLine())
- { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
- if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
- { to = Pos(to.line + 1, 0); }
- if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
-
- var fromIndex, fromLine, fromNode;
- if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
- fromLine = lineNo(display.view[0].line);
- fromNode = display.view[0].node;
- } else {
- fromLine = lineNo(display.view[fromIndex].line);
- fromNode = display.view[fromIndex - 1].node.nextSibling;
- }
- var toIndex = findViewIndex(cm, to.line);
- var toLine, toNode;
- if (toIndex == display.view.length - 1) {
- toLine = display.viewTo - 1;
- toNode = display.lineDiv.lastChild;
- } else {
- toLine = lineNo(display.view[toIndex + 1].line) - 1;
- toNode = display.view[toIndex + 1].node.previousSibling;
- }
-
- if (!fromNode) { return false }
- var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
- var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
- while (newText.length > 1 && oldText.length > 1) {
- if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
- else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
- else { break }
- }
-
- var cutFront = 0, cutEnd = 0;
- var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
- while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
- { ++cutFront; }
- var newBot = lst(newText), oldBot = lst(oldText);
- var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
- oldBot.length - (oldText.length == 1 ? cutFront : 0));
- while (cutEnd < maxCutEnd &&
- newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
- { ++cutEnd; }
- // Try to move start of change to start of selection if ambiguous
- if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
- while (cutFront && cutFront > from.ch &&
- newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
- cutFront--;
- cutEnd++;
- }
- }
-
- newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
- newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
+ // MODE DEFINITION AND QUERYING
- var chFrom = Pos(fromLine, cutFront);
- var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
- if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
- replaceRange(cm.doc, newText, chFrom, chTo, "+input");
- return true
- }
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ CodeMirror$1.defineMode = function(name/*, mode, …*/) {
+ if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
+ defineMode.apply(this, arguments);
};
- ContentEditableInput.prototype.ensurePolled = function () {
- this.forceCompositionEnd();
- };
- ContentEditableInput.prototype.reset = function () {
- this.forceCompositionEnd();
- };
- ContentEditableInput.prototype.forceCompositionEnd = function () {
- if (!this.composing) { return }
- clearTimeout(this.readDOMTimeout);
- this.composing = null;
- this.updateFromDOM();
- this.div.blur();
- this.div.focus();
- };
- ContentEditableInput.prototype.readFromDOMSoon = function () {
- var this$1 = this;
+ CodeMirror$1.defineMIME = defineMIME;
- if (this.readDOMTimeout != null) { return }
- this.readDOMTimeout = setTimeout(function () {
- this$1.readDOMTimeout = null;
- if (this$1.composing) {
- if (this$1.composing.done) { this$1.composing = null; }
- else { return }
- }
- this$1.updateFromDOM();
- }, 80);
- };
+ // Minimal default mode.
+ CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
+ CodeMirror$1.defineMIME("text/plain", "null");
- ContentEditableInput.prototype.updateFromDOM = function () {
- var this$1 = this;
+ // EXTENSIONS
- if (this.cm.isReadOnly() || !this.pollContent())
- { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
+ CodeMirror$1.defineExtension = function (name, func) {
+ CodeMirror$1.prototype[name] = func;
};
-
- ContentEditableInput.prototype.setUneditable = function (node) {
- node.contentEditable = "false";
+ CodeMirror$1.defineDocExtension = function (name, func) {
+ Doc.prototype[name] = func;
};
- ContentEditableInput.prototype.onKeyPress = function (e) {
- if (e.charCode == 0) { return }
- e.preventDefault();
- if (!this.cm.isReadOnly())
- { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
- };
+ CodeMirror$1.fromTextArea = fromTextArea;
- ContentEditableInput.prototype.readOnlyChanged = function (val) {
- this.div.contentEditable = String(val != "nocursor");
- };
+ addLegacyProps(CodeMirror$1);
- ContentEditableInput.prototype.onContextMenu = function () {};
- ContentEditableInput.prototype.resetPosition = function () {};
+ CodeMirror$1.version = "5.30.0";
- ContentEditableInput.prototype.needsContentAttribute = true;
+ return CodeMirror$1;
- function posToDOM(cm, pos) {
- var view = findViewForLine(cm, pos.line);
- if (!view || view.hidden) { return null }
- var line = getLine(cm.doc, pos.line);
- var info = mapFromLineView(view, line, pos.line);
+ })));
+
+
+/***/ }),
+/* 341 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
- var order = getOrder(line, cm.doc.direction), side = "left";
- if (order) {
- var partPos = getBidiPartAt(order, pos.ch);
- side = partPos % 2 ? "right" : "left";
+ (function(mod) {
+ if (true) // CommonJS
+ mod(__webpack_require__(340), __webpack_require__(342), __webpack_require__(343))
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript"], mod)
+ else // Plain browser env
+ mod(CodeMirror)
+ })(function(CodeMirror) {
+ "use strict"
+
+ // Depth means the amount of open braces in JS context, in XML
+ // context 0 means not in tag, 1 means in tag, and 2 means in tag
+ // and js block comment.
+ function Context(state, mode, depth, prev) {
+ this.state = state; this.mode = mode; this.depth = depth; this.prev = prev
}
- var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
- result.offset = result.collapse == "right" ? result.end : result.start;
- return result
- }
- function isInGutter(node) {
- for (var scan = node; scan; scan = scan.parentNode)
- { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
- return false
- }
+ function copyContext(context) {
+ return new Context(CodeMirror.copyState(context.mode, context.state),
+ context.mode,
+ context.depth,
+ context.prev && copyContext(context.prev))
+ }
- function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
+ CodeMirror.defineMode("jsx", function(config, modeConfig) {
+ var xmlMode = CodeMirror.getMode(config, {name: "xml", allowMissing: true, multilineTagIndentPastTag: false})
+ var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || "javascript")
- function domTextBetween(cm, from, to, fromLine, toLine) {
- var text = "", closing = false, lineSep = cm.doc.lineSeparator();
- function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
- function close() {
- if (closing) {
- text += lineSep;
- closing = false;
+ function flatXMLIndent(state) {
+ var tagName = state.tagName
+ state.tagName = null
+ var result = xmlMode.indent(state, "")
+ state.tagName = tagName
+ return result
}
- }
- function addText(str) {
- if (str) {
- close();
- text += str;
+
+ function token(stream, state) {
+ if (state.context.mode == xmlMode)
+ return xmlToken(stream, state, state.context)
+ else
+ return jsToken(stream, state, state.context)
}
- }
- function walk(node) {
- if (node.nodeType == 1) {
- var cmText = node.getAttribute("cm-text");
- if (cmText != null) {
- addText(cmText || node.textContent.replace(/\u200b/g, ""));
- return
+
+ function xmlToken(stream, state, cx) {
+ if (cx.depth == 2) { // Inside a JS /* */ comment
+ if (stream.match(/^.*?\*\//)) cx.depth = 1
+ else stream.skipToEnd()
+ return "comment"
}
- var markerID = node.getAttribute("cm-marker"), range$$1;
- if (markerID) {
- var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
- if (found.length && (range$$1 = found[0].find()))
- { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
- return
+
+ if (stream.peek() == "{") {
+ xmlMode.skipAttribute(cx.state)
+
+ var indent = flatXMLIndent(cx.state), xmlContext = cx.state.context
+ // If JS starts on same line as tag
+ if (xmlContext && stream.match(/^[^>]*>\s*$/, false)) {
+ while (xmlContext.prev && !xmlContext.startOfLine)
+ xmlContext = xmlContext.prev
+ // If tag starts the line, use XML indentation level
+ if (xmlContext.startOfLine) indent -= config.indentUnit
+ // Else use JS indentation level
+ else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented
+ // Else if inside of tag
+ } else if (cx.depth == 1) {
+ indent += config.indentUnit
+ }
+
+ state.context = new Context(CodeMirror.startState(jsMode, indent),
+ jsMode, 0, state.context)
+ return null
}
- if (node.getAttribute("contenteditable") == "false") { return }
- var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
- if (isBlock) { close(); }
- for (var i = 0; i < node.childNodes.length; i++)
- { walk(node.childNodes[i]); }
- if (isBlock) { closing = true; }
- } else if (node.nodeType == 3) {
- addText(node.nodeValue);
- }
- }
- for (;;) {
- walk(from);
- if (from == to) { break }
- from = from.nextSibling;
- }
- return text
- }
- function domToPos(cm, node, offset) {
- var lineNode;
- if (node == cm.display.lineDiv) {
- lineNode = cm.display.lineDiv.childNodes[offset];
- if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
- node = null; offset = 0;
- } else {
- for (lineNode = node;; lineNode = lineNode.parentNode) {
- if (!lineNode || lineNode == cm.display.lineDiv) { return null }
- if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
- }
- }
- for (var i = 0; i < cm.display.view.length; i++) {
- var lineView = cm.display.view[i];
- if (lineView.node == lineNode)
- { return locateNodeInLineView(lineView, node, offset) }
- }
- }
+ if (cx.depth == 1) { // Inside of tag
+ if (stream.peek() == "<") { // Tag inside of tag
+ xmlMode.skipAttribute(cx.state)
+ state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)),
+ xmlMode, 0, state.context)
+ return null
+ } else if (stream.match("//")) {
+ stream.skipToEnd()
+ return "comment"
+ } else if (stream.match("/*")) {
+ cx.depth = 2
+ return token(stream, state)
+ }
+ }
- function locateNodeInLineView(lineView, node, offset) {
- var wrapper = lineView.text.firstChild, bad = false;
- if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
- if (node == wrapper) {
- bad = true;
- node = wrapper.childNodes[offset];
- offset = 0;
- if (!node) {
- var line = lineView.rest ? lst(lineView.rest) : lineView.line;
- return badPos(Pos(lineNo(line), line.text.length), bad)
+ var style = xmlMode.token(stream, cx.state), cur = stream.current(), stop
+ if (/\btag\b/.test(style)) {
+ if (/>$/.test(cur)) {
+ if (cx.state.context) cx.depth = 0
+ else state.context = state.context.prev
+ } else if (/^ -1) {
+ stream.backUp(cur.length - stop)
+ }
+ return style
}
- }
- var textNode = node.nodeType == 3 ? node : null, topNode = node;
- if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
- textNode = node.firstChild;
- if (offset) { offset = textNode.nodeValue.length; }
- }
- while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
- var measure = lineView.measure, maps = measure.maps;
+ function jsToken(stream, state, cx) {
+ if (stream.peek() == "<" && jsMode.expressionAllowed(stream, cx.state)) {
+ jsMode.skipExpression(cx.state)
+ state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, "")),
+ xmlMode, 0, state.context)
+ return null
+ }
- function find(textNode, topNode, offset) {
- for (var i = -1; i < (maps ? maps.length : 0); i++) {
- var map$$1 = i < 0 ? measure.map : maps[i];
- for (var j = 0; j < map$$1.length; j += 3) {
- var curNode = map$$1[j + 2];
- if (curNode == textNode || curNode == topNode) {
- var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
- var ch = map$$1[j] + offset;
- if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
- return Pos(line, ch)
+ var style = jsMode.token(stream, cx.state)
+ if (!style && cx.depth != null) {
+ var cur = stream.current()
+ if (cur == "{") {
+ cx.depth++
+ } else if (cur == "}") {
+ if (--cx.depth == 0) state.context = state.context.prev
}
}
+ return style
}
- }
- var found = find(textNode, topNode, offset);
- if (found) { return badPos(found, bad) }
- // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
- for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
- found = find(after, after.firstChild, 0);
- if (found)
- { return badPos(Pos(found.line, found.ch - dist), bad) }
- else
- { dist += after.textContent.length; }
- }
- for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
- found = find(before, before.firstChild, -1);
- if (found)
- { return badPos(Pos(found.line, found.ch + dist$1), bad) }
- else
- { dist$1 += before.textContent.length; }
- }
- }
+ return {
+ startState: function() {
+ return {context: new Context(CodeMirror.startState(jsMode), jsMode)}
+ },
- // TEXTAREA INPUT STYLE
+ copyState: function(state) {
+ return {context: copyContext(state.context)}
+ },
- var TextareaInput = function(cm) {
- this.cm = cm;
- // See input.poll and input.reset
- this.prevInput = "";
+ token: token,
- // Flag that indicates whether we expect input to appear real soon
- // now (after some event like 'keypress' or 'input') and are
- // polling intensively.
- this.pollingFast = false;
- // Self-resetting timeout for the poller
- this.polling = new Delayed();
- // Tracks when input.reset has punted to just putting a short
- // string into the textarea instead of the full selection.
- this.inaccurateSelection = false;
- // Used to work around IE issue with selection being forgotten when focus moves away from textarea
- this.hasSelection = false;
- this.composing = null;
- };
+ indent: function(state, textAfter, fullLine) {
+ return state.context.mode.indent(state.context.state, textAfter, fullLine)
+ },
- TextareaInput.prototype.init = function (display) {
- var this$1 = this;
+ innerMode: function(state) {
+ return state.context
+ }
+ }
+ }, "xml", "javascript")
- var input = this, cm = this.cm;
+ CodeMirror.defineMIME("text/jsx", "jsx")
+ CodeMirror.defineMIME("text/typescript-jsx", {name: "jsx", base: {name: "javascript", typescript: true}})
+ });
+
+
+/***/ }),
+/* 342 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
- // Wraps and hides input textarea
- var div = this.wrapper = hiddenTextarea();
- // The semihidden textarea that is focused when the editor is
- // focused, and receives input.
- var te = this.textarea = div.firstChild;
- display.wrapper.insertBefore(div, display.wrapper.firstChild);
+ (function(mod) {
+ if (true) // CommonJS
+ mod(__webpack_require__(340));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+ })(function(CodeMirror) {
+ "use strict";
- // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
- if (ios) { te.style.width = "0px"; }
+ var htmlConfig = {
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+ 'track': true, 'wbr': true, 'menuitem': true},
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+ 'th': true, 'tr': true},
+ contextGrabbers: {
+ 'dd': {'dd': true, 'dt': true},
+ 'dt': {'dd': true, 'dt': true},
+ 'li': {'li': true},
+ 'option': {'option': true, 'optgroup': true},
+ 'optgroup': {'optgroup': true},
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+ 'rp': {'rp': true, 'rt': true},
+ 'rt': {'rp': true, 'rt': true},
+ 'tbody': {'tbody': true, 'tfoot': true},
+ 'td': {'td': true, 'th': true},
+ 'tfoot': {'tbody': true},
+ 'th': {'td': true, 'th': true},
+ 'thead': {'tbody': true, 'tfoot': true},
+ 'tr': {'tr': true}
+ },
+ doNotIndent: {"pre": true},
+ allowUnquoted: true,
+ allowMissing: true,
+ caseFold: true
+ }
- on(te, "input", function () {
- if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
- input.poll();
- });
+ var xmlConfig = {
+ autoSelfClosers: {},
+ implicitlyClosed: {},
+ contextGrabbers: {},
+ doNotIndent: {},
+ allowUnquoted: false,
+ allowMissing: false,
+ caseFold: false
+ }
- on(te, "paste", function (e) {
- if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+ CodeMirror.defineMode("xml", function(editorConf, config_) {
+ var indentUnit = editorConf.indentUnit
+ var config = {}
+ var defaults = config_.htmlMode ? htmlConfig : xmlConfig
+ for (var prop in defaults) config[prop] = defaults[prop]
+ for (var prop in config_) config[prop] = config_[prop]
- cm.state.pasteIncoming = true;
- input.fastPoll();
- });
+ // Return variables for tokenizers
+ var type, setStyle;
- function prepareCopyCut(e) {
- if (signalDOMEvent(cm, e)) { return }
- if (cm.somethingSelected()) {
- setLastCopied({lineWise: false, text: cm.getSelections()});
- if (input.inaccurateSelection) {
- input.prevInput = "";
- input.inaccurateSelection = false;
- te.value = lastCopied.text.join("\n");
- selectInput(te);
+ function inText(stream, state) {
+ function chain(parser) {
+ state.tokenize = parser;
+ return parser(stream, state);
+ }
+
+ var ch = stream.next();
+ if (ch == "<") {
+ if (stream.eat("!")) {
+ if (stream.eat("[")) {
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+ else return null;
+ } else if (stream.match("--")) {
+ return chain(inBlock("comment", "-->"));
+ } else if (stream.match("DOCTYPE", true, true)) {
+ stream.eatWhile(/[\w\._\-]/);
+ return chain(doctype(1));
+ } else {
+ return null;
+ }
+ } else if (stream.eat("?")) {
+ stream.eatWhile(/[\w\._\-]/);
+ state.tokenize = inBlock("meta", "?>");
+ return "meta";
+ } else {
+ type = stream.eat("/") ? "closeTag" : "openTag";
+ state.tokenize = inTag;
+ return "tag bracket";
}
- } else if (!cm.options.lineWiseCopyCut) {
- return
- } else {
- var ranges = copyableRanges(cm);
- setLastCopied({lineWise: true, text: ranges.text});
- if (e.type == "cut") {
- cm.setSelections(ranges.ranges, null, sel_dontScroll);
+ } else if (ch == "&") {
+ var ok;
+ if (stream.eat("#")) {
+ if (stream.eat("x")) {
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+ } else {
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+ }
} else {
- input.prevInput = "";
- te.value = ranges.text.join("\n");
- selectInput(te);
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
+ return ok ? "atom" : "error";
+ } else {
+ stream.eatWhile(/[^&<]/);
+ return null;
}
- if (e.type == "cut") { cm.state.cutIncoming = true; }
}
- on(te, "cut", prepareCopyCut);
- on(te, "copy", prepareCopyCut);
-
- on(display.scroller, "paste", function (e) {
- if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
- cm.state.pasteIncoming = true;
- input.focus();
- });
-
- // Prevent normal selection in the editor (we handle our own)
- on(display.lineSpace, "selectstart", function (e) {
- if (!eventInWidget(display, e)) { e_preventDefault(e); }
- });
+ inText.isInText = true;
- on(te, "compositionstart", function () {
- var start = cm.getCursor("from");
- if (input.composing) { input.composing.range.clear(); }
- input.composing = {
- start: start,
- range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
- };
- });
- on(te, "compositionend", function () {
- if (input.composing) {
- input.poll();
- input.composing.range.clear();
- input.composing = null;
+ function inTag(stream, state) {
+ var ch = stream.next();
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+ state.tokenize = inText;
+ type = ch == ">" ? "endTag" : "selfcloseTag";
+ return "tag bracket";
+ } else if (ch == "=") {
+ type = "equals";
+ return null;
+ } else if (ch == "<") {
+ state.tokenize = inText;
+ state.state = baseState;
+ state.tagName = state.tagStart = null;
+ var next = state.tokenize(stream, state);
+ return next ? next + " tag error" : "tag error";
+ } else if (/[\'\"]/.test(ch)) {
+ state.tokenize = inAttribute(ch);
+ state.stringStartCol = stream.column();
+ return state.tokenize(stream, state);
+ } else {
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
+ return "word";
}
- });
- };
-
- TextareaInput.prototype.prepareSelection = function () {
- // Redraw the selection and/or cursor
- var cm = this.cm, display = cm.display, doc = cm.doc;
- var result = prepareSelection(cm);
-
- // Move the hidden textarea near the cursor to prevent scrolling artifacts
- if (cm.options.moveInputWithCursor) {
- var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
- var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
- result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
- headPos.top + lineOff.top - wrapOff.top));
- result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
- headPos.left + lineOff.left - wrapOff.left));
}
- return result
- };
-
- TextareaInput.prototype.showSelection = function (drawn) {
- var cm = this.cm, display = cm.display;
- removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
- removeChildrenAndAdd(display.selectionDiv, drawn.selection);
- if (drawn.teTop != null) {
- this.wrapper.style.top = drawn.teTop + "px";
- this.wrapper.style.left = drawn.teLeft + "px";
+ function inAttribute(quote) {
+ var closure = function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.next() == quote) {
+ state.tokenize = inTag;
+ break;
+ }
+ }
+ return "string";
+ };
+ closure.isInAttribute = true;
+ return closure;
}
- };
- // Reset the input to correspond to the selection (or to be empty,
- // when not typing and nothing is selected)
- TextareaInput.prototype.reset = function (typing) {
- if (this.contextMenuPending) { return }
- var minimal, selected, cm = this.cm, doc = cm.doc;
- if (cm.somethingSelected()) {
- this.prevInput = "";
- var range$$1 = doc.sel.primary();
- minimal = hasCopyEvent &&
- (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000);
- var content = minimal ? "-" : selected || cm.getSelection();
- this.textarea.value = content;
- if (cm.state.focused) { selectInput(this.textarea); }
- if (ie && ie_version >= 9) { this.hasSelection = content; }
- } else if (!typing) {
- this.prevInput = this.textarea.value = "";
- if (ie && ie_version >= 9) { this.hasSelection = null; }
+ function inBlock(style, terminator) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.match(terminator)) {
+ state.tokenize = inText;
+ break;
+ }
+ stream.next();
+ }
+ return style;
+ };
+ }
+ function doctype(depth) {
+ return function(stream, state) {
+ var ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == "<") {
+ state.tokenize = doctype(depth + 1);
+ return state.tokenize(stream, state);
+ } else if (ch == ">") {
+ if (depth == 1) {
+ state.tokenize = inText;
+ break;
+ } else {
+ state.tokenize = doctype(depth - 1);
+ return state.tokenize(stream, state);
+ }
+ }
+ }
+ return "meta";
+ };
}
- this.inaccurateSelection = minimal;
- };
- TextareaInput.prototype.getField = function () { return this.textarea };
+ function Context(state, tagName, startOfLine) {
+ this.prev = state.context;
+ this.tagName = tagName;
+ this.indent = state.indented;
+ this.startOfLine = startOfLine;
+ if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
+ this.noIndent = true;
+ }
+ function popContext(state) {
+ if (state.context) state.context = state.context.prev;
+ }
+ function maybePopContext(state, nextTagName) {
+ var parentTagName;
+ while (true) {
+ if (!state.context) {
+ return;
+ }
+ parentTagName = state.context.tagName;
+ if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
+ !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+ return;
+ }
+ popContext(state);
+ }
+ }
- TextareaInput.prototype.supportsTouch = function () { return false };
+ function baseState(type, stream, state) {
+ if (type == "openTag") {
+ state.tagStart = stream.column();
+ return tagNameState;
+ } else if (type == "closeTag") {
+ return closeTagNameState;
+ } else {
+ return baseState;
+ }
+ }
+ function tagNameState(type, stream, state) {
+ if (type == "word") {
+ state.tagName = stream.current();
+ setStyle = "tag";
+ return attrState;
+ } else {
+ setStyle = "error";
+ return tagNameState;
+ }
+ }
+ function closeTagNameState(type, stream, state) {
+ if (type == "word") {
+ var tagName = stream.current();
+ if (state.context && state.context.tagName != tagName &&
+ config.implicitlyClosed.hasOwnProperty(state.context.tagName))
+ popContext(state);
+ if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
+ setStyle = "tag";
+ return closeState;
+ } else {
+ setStyle = "tag error";
+ return closeStateErr;
+ }
+ } else {
+ setStyle = "error";
+ return closeStateErr;
+ }
+ }
- TextareaInput.prototype.focus = function () {
- if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
- try { this.textarea.focus(); }
- catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
+ function closeState(type, _stream, state) {
+ if (type != "endTag") {
+ setStyle = "error";
+ return closeState;
+ }
+ popContext(state);
+ return baseState;
+ }
+ function closeStateErr(type, stream, state) {
+ setStyle = "error";
+ return closeState(type, stream, state);
}
- };
- TextareaInput.prototype.blur = function () { this.textarea.blur(); };
+ function attrState(type, _stream, state) {
+ if (type == "word") {
+ setStyle = "attribute";
+ return attrEqState;
+ } else if (type == "endTag" || type == "selfcloseTag") {
+ var tagName = state.tagName, tagStart = state.tagStart;
+ state.tagName = state.tagStart = null;
+ if (type == "selfcloseTag" ||
+ config.autoSelfClosers.hasOwnProperty(tagName)) {
+ maybePopContext(state, tagName);
+ } else {
+ maybePopContext(state, tagName);
+ state.context = new Context(state, tagName, tagStart == state.indented);
+ }
+ return baseState;
+ }
+ setStyle = "error";
+ return attrState;
+ }
+ function attrEqState(type, stream, state) {
+ if (type == "equals") return attrValueState;
+ if (!config.allowMissing) setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrValueState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
+ setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrContinuedState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ return attrState(type, stream, state);
+ }
- TextareaInput.prototype.resetPosition = function () {
- this.wrapper.style.top = this.wrapper.style.left = 0;
- };
+ return {
+ startState: function(baseIndent) {
+ var state = {tokenize: inText,
+ state: baseState,
+ indented: baseIndent || 0,
+ tagName: null, tagStart: null,
+ context: null}
+ if (baseIndent != null) state.baseIndent = baseIndent
+ return state
+ },
- TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
+ token: function(stream, state) {
+ if (!state.tagName && stream.sol())
+ state.indented = stream.indentation();
- // Poll for input changes, using the normal rate of polling. This
- // runs as long as the editor is focused.
- TextareaInput.prototype.slowPoll = function () {
- var this$1 = this;
+ if (stream.eatSpace()) return null;
+ type = null;
+ var style = state.tokenize(stream, state);
+ if ((style || type) && style != "comment") {
+ setStyle = null;
+ state.state = state.state(type || style, stream, state);
+ if (setStyle)
+ style = setStyle == "error" ? style + " error" : setStyle;
+ }
+ return style;
+ },
- if (this.pollingFast) { return }
- this.polling.set(this.cm.options.pollInterval, function () {
- this$1.poll();
- if (this$1.cm.state.focused) { this$1.slowPoll(); }
- });
- };
+ indent: function(state, textAfter, fullLine) {
+ var context = state.context;
+ // Indent multi-line strings (e.g. css).
+ if (state.tokenize.isInAttribute) {
+ if (state.tagStart == state.indented)
+ return state.stringStartCol + 1;
+ else
+ return state.indented + indentUnit;
+ }
+ if (context && context.noIndent) return CodeMirror.Pass;
+ if (state.tokenize != inTag && state.tokenize != inText)
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+ // Indent the starts of attribute names.
+ if (state.tagName) {
+ if (config.multilineTagIndentPastTag !== false)
+ return state.tagStart + state.tagName.length + 2;
+ else
+ return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
+ }
+ if (config.alignCDATA && /$/,
+ blockCommentStart: "",
- // Read input from the textarea, and update the document to match.
- // When something is selected, it is present in the textarea, and
- // selected (unless it is huge, in which case a placeholder is
- // used). When nothing is selected, the cursor sits after previously
- // seen text (can be empty), which is stored in prevInput (we must
- // not reset the textarea when typing, because that breaks IME).
- TextareaInput.prototype.poll = function () {
- var this$1 = this;
+ configuration: config.htmlMode ? "html" : "xml",
+ helperType: config.htmlMode ? "html" : "xml",
- var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
- // Since this is called a *lot*, try to bail out as cheaply as
- // possible when it is clear that nothing happened. hasSelection
- // will be the case when there is a lot of text in the textarea,
- // in which case reading its value would be expensive.
- if (this.contextMenuPending || !cm.state.focused ||
- (hasSelection(input) && !prevInput && !this.composing) ||
- cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
- { return false }
+ skipAttribute: function(state) {
+ if (state.state == attrValueState)
+ state.state = attrState
+ }
+ };
+ });
- var text = input.value;
- // If nothing changed, bail.
- if (text == prevInput && !cm.somethingSelected()) { return false }
- // Work around nonsensical selection resetting in IE9/10, and
- // inexplicable appearance of private area unicode characters on
- // some key combos in Mac (#2689).
- if (ie && ie_version >= 9 && this.hasSelection === text ||
- mac && /[\uf700-\uf7ff]/.test(text)) {
- cm.display.input.reset();
- return false
- }
+ CodeMirror.defineMIME("text/xml", "xml");
+ CodeMirror.defineMIME("application/xml", "xml");
+ if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
- if (cm.doc.sel == cm.display.selForContextMenu) {
- var first = text.charCodeAt(0);
- if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
- if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
- }
- // Find the part of the input that is actually new
- var same = 0, l = Math.min(prevInput.length, text.length);
- while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
+ });
+
+
+/***/ }),
+/* 343 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
- runInOp(cm, function () {
- applyTextInput(cm, text.slice(same), prevInput.length - same,
- null, this$1.composing ? "*compose" : null);
+ (function(mod) {
+ if (true) // CommonJS
+ mod(__webpack_require__(340));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+ })(function(CodeMirror) {
+ "use strict";
- // Don't leave long text in the textarea, since it makes further polling slow
- if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
- else { this$1.prevInput = text; }
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var statementIndent = parserConfig.statementIndent;
+ var jsonldMode = parserConfig.jsonld;
+ var jsonMode = parserConfig.json || jsonldMode;
+ var isTS = parserConfig.typescript;
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
- if (this$1.composing) {
- this$1.composing.range.clear();
- this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
- {className: "CodeMirror-composing"});
- }
- });
- return true
- };
+ // Tokenizer
- TextareaInput.prototype.ensurePolled = function () {
- if (this.pollingFast && this.poll()) { this.pollingFast = false; }
- };
+ var keywords = function(){
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
- TextareaInput.prototype.onKeyPress = function () {
- if (ie && ie_version >= 9) { this.hasSelection = null; }
- this.fastPoll();
- };
+ var jsKeywords = {
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+ "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "void": C, "throw": C, "debugger": C,
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
+ "function": kw("function"), "catch": kw("catch"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "typeof": operator, "instanceof": operator,
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
+ "await": C
+ };
- TextareaInput.prototype.onContextMenu = function (e) {
- var input = this, cm = input.cm, display = cm.display, te = input.textarea;
- var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
- if (!pos || presto) { return } // Opera is difficult.
+ // Extend the 'normal' keywords with the TypeScript language extensions
+ if (isTS) {
+ var type = {type: "variable", style: "type"};
+ var tsKeywords = {
+ // object-like things
+ "interface": kw("class"),
+ "implements": C,
+ "namespace": C,
+ "module": kw("module"),
+ "enum": kw("module"),
- // Reset the current text selection only if the click is done outside of the selection
- // and 'resetSelectionOnContextMenu' option is true.
- var reset = cm.options.resetSelectionOnContextMenu;
- if (reset && cm.doc.sel.contains(pos) == -1)
- { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
+ // scope modifiers
+ "public": kw("modifier"),
+ "private": kw("modifier"),
+ "protected": kw("modifier"),
+ "abstract": kw("modifier"),
+ "readonly": kw("modifier"),
- var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
- input.wrapper.style.cssText = "position: absolute";
- var wrapperBox = input.wrapper.getBoundingClientRect();
- te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
- var oldScrollY;
- if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
- display.input.focus();
- if (webkit) { window.scrollTo(null, oldScrollY); }
- display.input.reset();
- // Adds "Select all" to context menu in FF
- if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
- input.contextMenuPending = true;
- display.selForContextMenu = cm.doc.sel;
- clearTimeout(display.detectingSelectAll);
+ // types
+ "string": type, "number": type, "boolean": type, "any": type
+ };
- // Select-all will be greyed out if there's nothing to select, so
- // this adds a zero-width space so that we can later check whether
- // it got selected.
- function prepareSelectAllHack() {
- if (te.selectionStart != null) {
- var selected = cm.somethingSelected();
- var extval = "\u200b" + (selected ? te.value : "");
- te.value = "\u21da"; // Used to catch context-menu undo
- te.value = extval;
- input.prevInput = selected ? "" : "\u200b";
- te.selectionStart = 1; te.selectionEnd = extval.length;
- // Re-set this, in case some other handler touched the
- // selection in the meantime.
- display.selForContextMenu = cm.doc.sel;
+ for (var attr in tsKeywords) {
+ jsKeywords[attr] = tsKeywords[attr];
+ }
+ }
+
+ return jsKeywords;
+ }();
+
+ var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+
+ function readRegexp(stream) {
+ var escaped = false, next, inSet = false;
+ while ((next = stream.next()) != null) {
+ if (!escaped) {
+ if (next == "/" && !inSet) return;
+ if (next == "[") inSet = true;
+ else if (inSet && next == "]") inSet = false;
+ }
+ escaped = !escaped && next == "\\";
}
}
- function rehide() {
- input.contextMenuPending = false;
- input.wrapper.style.cssText = oldWrapperCSS;
- te.style.cssText = oldCSS;
- if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
- // Try to detect the user choosing select-all
- if (te.selectionStart != null) {
- if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
- var i = 0, poll = function () {
- if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
- te.selectionEnd > 0 && input.prevInput == "\u200b") {
- operation(cm, selectAll)(cm);
- } else if (i++ < 10) {
- display.detectingSelectAll = setTimeout(poll, 500);
- } else {
- display.selForContextMenu = null;
- display.input.reset();
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
+ return ret("number", "number");
+ } else if (ch == "." && stream.match("..")) {
+ return ret("spread", "meta");
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "=" && stream.eat(">")) {
+ return ret("=>", "operator");
+ } else if (ch == "0" && stream.eat(/x/i)) {
+ stream.eatWhile(/[\da-f]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/o/i)) {
+ stream.eatWhile(/[0-7]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/b/i)) {
+ stream.eatWhile(/[01]/i);
+ return ret("number", "number");
+ } else if (/\d/.test(ch)) {
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+ return ret("number", "number");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else if (expressionAllowed(stream, state, 1)) {
+ readRegexp(stream);
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
+ return ret("regexp", "string-2");
+ } else {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current());
+ }
+ } else if (ch == "`") {
+ state.tokenize = tokenQuasi;
+ return tokenQuasi(stream, state);
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return ret("error", "error");
+ } else if (isOperatorChar.test(ch)) {
+ if (ch != ">" || !state.lexical || state.lexical.type != ">")
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current());
+ } else if (wordRE.test(ch)) {
+ stream.eatWhile(wordRE);
+ var word = stream.current()
+ if (state.lastType != ".") {
+ if (keywords.propertyIsEnumerable(word)) {
+ var kw = keywords[word]
+ return ret(kw.type, kw.style, word)
}
- };
- display.detectingSelectAll = setTimeout(poll, 200);
+ if (word == "async" && stream.match(/^\s*[\(\w]/, false))
+ return ret("async", "keyword", word)
+ }
+ return ret("variable", "variable", word)
}
}
- if (ie && ie_version >= 9) { prepareSelectAllHack(); }
- if (captureRightClick) {
- e_stop(e);
- var mouseup = function () {
- off(window, "mouseup", mouseup);
- setTimeout(rehide, 20);
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next;
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
+ state.tokenize = tokenBase;
+ return ret("jsonld-keyword", "meta");
+ }
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) break;
+ escaped = !escaped && next == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
};
- on(window, "mouseup", mouseup);
- } else {
- setTimeout(rehide, 50);
- }
- };
-
- TextareaInput.prototype.readOnlyChanged = function (val) {
- if (!val) { this.reset(); }
- };
-
- TextareaInput.prototype.setUneditable = function () {};
-
- TextareaInput.prototype.needsContentAttribute = false;
-
- function fromTextArea(textarea, options) {
- options = options ? copyObj(options) : {};
- options.value = textarea.value;
- if (!options.tabindex && textarea.tabIndex)
- { options.tabindex = textarea.tabIndex; }
- if (!options.placeholder && textarea.placeholder)
- { options.placeholder = textarea.placeholder; }
- // Set autofocus to true if this textarea is focused, or if it has
- // autofocus and no other element is focused.
- if (options.autofocus == null) {
- var hasFocus = activeElt();
- options.autofocus = hasFocus == textarea ||
- textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
- function save() {textarea.value = cm.getValue();}
-
- var realSubmit;
- if (textarea.form) {
- on(textarea.form, "submit", save);
- // Deplorable hack to make the submit method do the right thing.
- if (!options.leaveSubmitMethodAlone) {
- var form = textarea.form;
- realSubmit = form.submit;
- try {
- var wrappedSubmit = form.submit = function () {
- save();
- form.submit = realSubmit;
- form.submit();
- form.submit = wrappedSubmit;
- };
- } catch(e) {}
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
}
+ return ret("comment", "comment");
}
- options.finishInit = function (cm) {
- cm.save = save;
- cm.getTextArea = function () { return textarea; };
- cm.toTextArea = function () {
- cm.toTextArea = isNaN; // Prevent this from being ran twice
- save();
- textarea.parentNode.removeChild(cm.getWrapperElement());
- textarea.style.display = "";
- if (textarea.form) {
- off(textarea.form, "submit", save);
- if (typeof textarea.form.submit == "function")
- { textarea.form.submit = realSubmit; }
+ function tokenQuasi(stream, state) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
+ state.tokenize = tokenBase;
+ break;
}
- };
- };
-
- textarea.style.display = "none";
- var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
- options);
- return cm
- }
-
- function addLegacyProps(CodeMirror) {
- CodeMirror.off = off;
- CodeMirror.on = on;
- CodeMirror.wheelEventPixels = wheelEventPixels;
- CodeMirror.Doc = Doc;
- CodeMirror.splitLines = splitLinesAuto;
- CodeMirror.countColumn = countColumn;
- CodeMirror.findColumn = findColumn;
- CodeMirror.isWordChar = isWordCharBasic;
- CodeMirror.Pass = Pass;
- CodeMirror.signal = signal;
- CodeMirror.Line = Line;
- CodeMirror.changeEnd = changeEnd;
- CodeMirror.scrollbarModel = scrollbarModel;
- CodeMirror.Pos = Pos;
- CodeMirror.cmpPos = cmp;
- CodeMirror.modes = modes;
- CodeMirror.mimeModes = mimeModes;
- CodeMirror.resolveMode = resolveMode;
- CodeMirror.getMode = getMode;
- CodeMirror.modeExtensions = modeExtensions;
- CodeMirror.extendMode = extendMode;
- CodeMirror.copyState = copyState;
- CodeMirror.startState = startState;
- CodeMirror.innerMode = innerMode;
- CodeMirror.commands = commands;
- CodeMirror.keyMap = keyMap;
- CodeMirror.keyName = keyName;
- CodeMirror.isModifierKey = isModifierKey;
- CodeMirror.lookupKey = lookupKey;
- CodeMirror.normalizeKeyMap = normalizeKeyMap;
- CodeMirror.StringStream = StringStream;
- CodeMirror.SharedTextMarker = SharedTextMarker;
- CodeMirror.TextMarker = TextMarker;
- CodeMirror.LineWidget = LineWidget;
- CodeMirror.e_preventDefault = e_preventDefault;
- CodeMirror.e_stopPropagation = e_stopPropagation;
- CodeMirror.e_stop = e_stop;
- CodeMirror.addClass = addClass;
- CodeMirror.contains = contains;
- CodeMirror.rmClass = rmClass;
- CodeMirror.keyNames = keyNames;
- }
-
- // EDITOR CONSTRUCTOR
-
- defineOptions(CodeMirror$1);
-
- addEditorMethods(CodeMirror$1);
-
- // Set up methods on CodeMirror's prototype to redirect to the editor's document.
- var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
- for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
- { CodeMirror$1.prototype[prop] = (function(method) {
- return function() {return method.apply(this.doc, arguments)}
- })(Doc.prototype[prop]); } }
-
- eventMixin(Doc);
-
- // INPUT HANDLING
-
- CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
-
- // MODE DEFINITION AND QUERYING
+ escaped = !escaped && next == "\\";
+ }
+ return ret("quasi", "string-2", stream.current());
+ }
- // Extra arguments are stored as the mode's dependencies, which is
- // used by (legacy) mechanisms like loadmode.js to automatically
- // load a mode. (Preferred mechanism is the require/define calls.)
- CodeMirror$1.defineMode = function(name/*, mode, …*/) {
- if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
- defineMode.apply(this, arguments);
- };
+ var brackets = "([{}])";
+ // This is a crude lookahead trick to try and notice that we're
+ // parsing the argument patterns for a fat-arrow function before we
+ // actually hit the arrow token. It only works if the arrow is on
+ // the same line as the arguments and there's no strange noise
+ // (comments) in between. Fallback is to only notice when we hit the
+ // arrow, and not declare the arguments as locals for the arrow
+ // body.
+ function findFatArrow(stream, state) {
+ if (state.fatArrowAt) state.fatArrowAt = null;
+ var arrow = stream.string.indexOf("=>", stream.start);
+ if (arrow < 0) return;
- CodeMirror$1.defineMIME = defineMIME;
+ if (isTS) { // Try to skip TypeScript return type declarations after the arguments
+ var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
+ if (m) arrow = m.index
+ }
- // Minimal default mode.
- CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
- CodeMirror$1.defineMIME("text/plain", "null");
+ var depth = 0, sawSomething = false;
+ for (var pos = arrow - 1; pos >= 0; --pos) {
+ var ch = stream.string.charAt(pos);
+ var bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (!depth) { ++pos; break; }
+ if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.test(ch)) {
+ sawSomething = true;
+ } else if (/["'\/]/.test(ch)) {
+ return;
+ } else if (sawSomething && !depth) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && !depth) state.fatArrowAt = pos;
+ }
- // EXTENSIONS
+ // Parser
- CodeMirror$1.defineExtension = function (name, func) {
- CodeMirror$1.prototype[name] = func;
- };
- CodeMirror$1.defineDocExtension = function (name, func) {
- Doc.prototype[name] = func;
- };
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
- CodeMirror$1.fromTextArea = fromTextArea;
+ function JSLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
- addLegacyProps(CodeMirror$1);
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ for (var cx = state.context; cx; cx = cx.prev) {
+ for (var v = cx.vars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+ }
- CodeMirror$1.version = "5.25.2";
+ function parseJS(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
- return CodeMirror$1;
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
- })));
-
-
-/***/ }),
-/* 320 */
-/***/ (function(module, exports, __webpack_require__) {
-
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: http://codemirror.net/LICENSE
+ while(true) {
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ return style;
+ }
+ }
+ }
- (function(mod) {
- if (true) // CommonJS
- mod(__webpack_require__(319), __webpack_require__(321), __webpack_require__(322))
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript"], mod)
- else // Plain browser env
- mod(CodeMirror)
- })(function(CodeMirror) {
- "use strict"
+ // Combinator utils
- // Depth means the amount of open braces in JS context, in XML
- // context 0 means not in tag, 1 means in tag, and 2 means in tag
- // and js block comment.
- function Context(state, mode, depth, prev) {
- this.state = state; this.mode = mode; this.depth = depth; this.prev = prev
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
-
- function copyContext(context) {
- return new Context(CodeMirror.copyState(context.mode, context.state),
- context.mode,
- context.depth,
- context.prev && copyContext(context.prev))
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
}
-
- CodeMirror.defineMode("jsx", function(config, modeConfig) {
- var xmlMode = CodeMirror.getMode(config, {name: "xml", allowMissing: true, multilineTagIndentPastTag: false})
- var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || "javascript")
-
- function flatXMLIndent(state) {
- var tagName = state.tagName
- state.tagName = null
- var result = xmlMode.indent(state, "")
- state.tagName = tagName
- return result
+ function register(varname) {
+ function inList(list) {
+ for (var v = list; v; v = v.next)
+ if (v.name == varname) return true;
+ return false;
}
-
- function token(stream, state) {
- if (state.context.mode == xmlMode)
- return xmlToken(stream, state, state.context)
- else
- return jsToken(stream, state, state.context)
+ var state = cx.state;
+ cx.marked = "def";
+ if (state.context) {
+ if (inList(state.localVars)) return;
+ state.localVars = {name: varname, next: state.localVars};
+ } else {
+ if (inList(state.globalVars)) return;
+ if (parserConfig.globalVars)
+ state.globalVars = {name: varname, next: state.globalVars};
}
+ }
- function xmlToken(stream, state, cx) {
- if (cx.depth == 2) { // Inside a JS /* */ comment
- if (stream.match(/^.*?\*\//)) cx.depth = 1
- else stream.skipToEnd()
- return "comment"
- }
-
- if (stream.peek() == "{") {
- xmlMode.skipAttribute(cx.state)
-
- var indent = flatXMLIndent(cx.state), xmlContext = cx.state.context
- // If JS starts on same line as tag
- if (xmlContext && stream.match(/^[^>]*>\s*$/, false)) {
- while (xmlContext.prev && !xmlContext.startOfLine)
- xmlContext = xmlContext.prev
- // If tag starts the line, use XML indentation level
- if (xmlContext.startOfLine) indent -= config.indentUnit
- // Else use JS indentation level
- else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented
- // Else if inside of tag
- } else if (cx.depth == 1) {
- indent += config.indentUnit
- }
-
- state.context = new Context(CodeMirror.startState(jsMode, indent),
- jsMode, 0, state.context)
- return null
- }
+ // Combinators
- if (cx.depth == 1) { // Inside of tag
- if (stream.peek() == "<") { // Tag inside of tag
- xmlMode.skipAttribute(cx.state)
- state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)),
- xmlMode, 0, state.context)
- return null
- } else if (stream.match("//")) {
- stream.skipToEnd()
- return "comment"
- } else if (stream.match("/*")) {
- cx.depth = 2
- return token(stream, state)
- }
- }
-
- var style = xmlMode.token(stream, cx.state), cur = stream.current(), stop
- if (/\btag\b/.test(style)) {
- if (/>$/.test(cur)) {
- if (cx.state.context) cx.depth = 0
- else state.context = state.context.prev
- } else if (/^ -1) {
- stream.backUp(cur.length - stop)
- }
- return style
+ var defaultVars = {name: "this", next: {name: "arguments"}};
+ function pushcontext() {
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+ cx.state.localVars = defaultVars;
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars;
+ cx.state.context = cx.state.context.prev;
+ }
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state, indent = state.indented;
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
}
+ }
+ poplex.lex = true;
- function jsToken(stream, state, cx) {
- if (stream.peek() == "<" && jsMode.expressionAllowed(stream, cx.state)) {
- jsMode.skipExpression(cx.state)
- state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, "")),
- xmlMode, 0, state.context)
- return null
- }
+ function expect(wanted) {
+ function exp(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";") return pass();
+ else return cont(exp);
+ };
+ return exp;
+ }
- var style = jsMode.token(stream, cx.state)
- if (!style && cx.depth != null) {
- var cur = stream.current()
- if (cur == "{") {
- cx.depth++
- } else if (cur == "}") {
- if (--cx.depth == 0) state.context = state.context.prev
- }
- }
- return style
+ function statement(type, value) {
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "{") return cont(pushlex("}"), block, poplex);
+ if (type == ";") return cont();
+ if (type == "if") {
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
+ cx.state.cc.pop()();
+ return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
}
-
- return {
- startState: function() {
- return {context: new Context(CodeMirror.startState(jsMode), jsMode)}
- },
-
- copyState: function(state) {
- return {context: copyContext(state.context)}
- },
-
- token: token,
-
- indent: function(state, textAfter, fullLine) {
- return state.context.mode.indent(state.context.state, textAfter, fullLine)
- },
-
- innerMode: function(state) {
- return state.context
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
+ if (type == "variable") {
+ if (isTS && value == "type") {
+ cx.marked = "keyword"
+ return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
+ } if (isTS && value == "declare") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else {
+ return cont(pushlex("stat"), maybelabel);
}
}
- }, "xml", "javascript")
-
- CodeMirror.defineMIME("text/jsx", "jsx")
- CodeMirror.defineMIME("text/typescript-jsx", {name: "jsx", base: {name: "javascript", typescript: true}})
- });
-
-
-/***/ }),
-/* 321 */
-/***/ (function(module, exports, __webpack_require__) {
-
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: http://codemirror.net/LICENSE
-
- (function(mod) {
- if (true) // CommonJS
- mod(__webpack_require__(319));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
-
- var htmlConfig = {
- autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
- 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
- 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
- 'track': true, 'wbr': true, 'menuitem': true},
- implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
- 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
- 'th': true, 'tr': true},
- contextGrabbers: {
- 'dd': {'dd': true, 'dt': true},
- 'dt': {'dd': true, 'dt': true},
- 'li': {'li': true},
- 'option': {'option': true, 'optgroup': true},
- 'optgroup': {'optgroup': true},
- 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
- 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
- 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
- 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
- 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
- 'rp': {'rp': true, 'rt': true},
- 'rt': {'rp': true, 'rt': true},
- 'tbody': {'tbody': true, 'tfoot': true},
- 'td': {'td': true, 'th': true},
- 'tfoot': {'tbody': true},
- 'th': {'td': true, 'th': true},
- 'thead': {'tbody': true, 'tfoot': true},
- 'tr': {'tr': true}
- },
- doNotIndent: {"pre": true},
- allowUnquoted: true,
- allowMissing: true,
- caseFold: true
- }
-
- var xmlConfig = {
- autoSelfClosers: {},
- implicitlyClosed: {},
- contextGrabbers: {},
- doNotIndent: {},
- allowUnquoted: false,
- allowMissing: false,
- caseFold: false
- }
-
- CodeMirror.defineMode("xml", function(editorConf, config_) {
- var indentUnit = editorConf.indentUnit
- var config = {}
- var defaults = config_.htmlMode ? htmlConfig : xmlConfig
- for (var prop in defaults) config[prop] = defaults[prop]
- for (var prop in config_) config[prop] = config_[prop]
+ if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"),
+ block, poplex, poplex);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+ statement, poplex, popcontext);
+ if (type == "class") return cont(pushlex("form"), className, poplex);
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
+ if (type == "module") return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
+ if (type == "async") return cont(statement)
+ if (value == "@") return cont(expression, statement)
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function expression(type) {
+ return expressionInner(type, false);
+ }
+ function expressionNoComma(type) {
+ return expressionInner(type, true);
+ }
+ function parenExpr(type) {
+ if (type != "(") return pass()
+ return cont(pushlex(")"), expression, expect(")"), poplex)
+ }
+ function expressionInner(type, noComma) {
+ if (cx.state.fatArrowAt == cx.stream.start) {
+ var body = noComma ? arrowBodyNoComma : arrowBody;
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
+ }
- // Return variables for tokenizers
- var type, setStyle;
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+ if (type == "function") return cont(functiondef, maybeop);
+ if (type == "class") return cont(pushlex("form"), classExpression, poplex);
+ if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
+ if (type == "quasi") return pass(quasi, maybeop);
+ if (type == "new") return cont(maybeTarget(noComma));
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+ function maybeexpressionNoComma(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expressionNoComma);
+ }
- function inText(stream, state) {
- function chain(parser) {
- state.tokenize = parser;
- return parser(stream, state);
+ function maybeoperatorComma(type, value) {
+ if (type == ",") return cont(expression);
+ return maybeoperatorNoComma(type, value, false);
+ }
+ function maybeoperatorNoComma(type, value, noComma) {
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+ var expr = noComma == false ? expression : expressionNoComma;
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
+ if (type == "operator") {
+ if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
+ if (value == "?") return cont(expression, expect(":"), expr);
+ return cont(expr);
}
-
- var ch = stream.next();
- if (ch == "<") {
- if (stream.eat("!")) {
- if (stream.eat("[")) {
- if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
- else return null;
- } else if (stream.match("--")) {
- return chain(inBlock("comment", "-->"));
- } else if (stream.match("DOCTYPE", true, true)) {
- stream.eatWhile(/[\w\._\-]/);
- return chain(doctype(1));
- } else {
- return null;
- }
- } else if (stream.eat("?")) {
- stream.eatWhile(/[\w\._\-]/);
- state.tokenize = inBlock("meta", "?>");
- return "meta";
- } else {
- type = stream.eat("/") ? "closeTag" : "openTag";
- state.tokenize = inTag;
- return "tag bracket";
- }
- } else if (ch == "&") {
- var ok;
- if (stream.eat("#")) {
- if (stream.eat("x")) {
- ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
- } else {
- ok = stream.eatWhile(/[\d]/) && stream.eat(";");
- }
- } else {
- ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
- }
- return ok ? "atom" : "error";
- } else {
- stream.eatWhile(/[^&<]/);
- return null;
+ if (type == "quasi") { return pass(quasi, me); }
+ if (type == ";") return;
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
+ if (type == ".") return cont(property, me);
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+ if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
+ if (type == "regexp") {
+ cx.state.lastType = cx.marked = "operator"
+ cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
+ return cont(expr)
}
}
- inText.isInText = true;
-
- function inTag(stream, state) {
- var ch = stream.next();
- if (ch == ">" || (ch == "/" && stream.eat(">"))) {
- state.tokenize = inText;
- type = ch == ">" ? "endTag" : "selfcloseTag";
- return "tag bracket";
- } else if (ch == "=") {
- type = "equals";
- return null;
- } else if (ch == "<") {
- state.tokenize = inText;
- state.state = baseState;
- state.tagName = state.tagStart = null;
- var next = state.tokenize(stream, state);
- return next ? next + " tag error" : "tag error";
- } else if (/[\'\"]/.test(ch)) {
- state.tokenize = inAttribute(ch);
- state.stringStartCol = stream.column();
- return state.tokenize(stream, state);
- } else {
- stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
- return "word";
+ function quasi(type, value) {
+ if (type != "quasi") return pass();
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
+ return cont(expression, continueQuasi);
+ }
+ function continueQuasi(type) {
+ if (type == "}") {
+ cx.marked = "string-2";
+ cx.state.tokenize = tokenQuasi;
+ return cont(quasi);
}
}
-
- function inAttribute(quote) {
- var closure = function(stream, state) {
- while (!stream.eol()) {
- if (stream.next() == quote) {
- state.tokenize = inTag;
- break;
- }
- }
- return "string";
- };
- closure.isInAttribute = true;
- return closure;
+ function arrowBody(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expression);
}
-
- function inBlock(style, terminator) {
- return function(stream, state) {
- while (!stream.eol()) {
- if (stream.match(terminator)) {
- state.tokenize = inText;
- break;
- }
- stream.next();
- }
- return style;
- };
+ function arrowBodyNoComma(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expressionNoComma);
}
- function doctype(depth) {
- return function(stream, state) {
- var ch;
- while ((ch = stream.next()) != null) {
- if (ch == "<") {
- state.tokenize = doctype(depth + 1);
- return state.tokenize(stream, state);
- } else if (ch == ">") {
- if (depth == 1) {
- state.tokenize = inText;
- break;
- } else {
- state.tokenize = doctype(depth - 1);
- return state.tokenize(stream, state);
- }
- }
- }
- return "meta";
+ function maybeTarget(noComma) {
+ return function(type) {
+ if (type == ".") return cont(noComma ? targetNoComma : target);
+ else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
+ else return pass(noComma ? expressionNoComma : expression);
};
}
-
- function Context(state, tagName, startOfLine) {
- this.prev = state.context;
- this.tagName = tagName;
- this.indent = state.indented;
- this.startOfLine = startOfLine;
- if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
- this.noIndent = true;
+ function target(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
}
- function popContext(state) {
- if (state.context) state.context = state.context.prev;
+ function targetNoComma(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
}
- function maybePopContext(state, nextTagName) {
- var parentTagName;
- while (true) {
- if (!state.context) {
- return;
- }
- parentTagName = state.context.tagName;
- if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
- !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
- return;
- }
- popContext(state);
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperatorComma, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type, value) {
+ if (type == "async") {
+ cx.marked = "property";
+ return cont(objprop);
+ } else if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(getterSetter);
+ var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
+ if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
+ cx.state.fatArrowAt = cx.stream.pos + m[0].length
+ return cont(afterprop);
+ } else if (type == "number" || type == "string") {
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
+ return cont(afterprop);
+ } else if (type == "jsonld-keyword") {
+ return cont(afterprop);
+ } else if (type == "modifier") {
+ return cont(objprop)
+ } else if (type == "[") {
+ return cont(expression, expect("]"), afterprop);
+ } else if (type == "spread") {
+ return cont(expression, afterprop);
+ } else if (type == ":") {
+ return pass(afterprop)
}
}
-
- function baseState(type, stream, state) {
- if (type == "openTag") {
- state.tagStart = stream.column();
- return tagNameState;
- } else if (type == "closeTag") {
- return closeTagNameState;
- } else {
- return baseState;
+ function getterSetter(type) {
+ if (type != "variable") return pass(afterprop);
+ cx.marked = "property";
+ return cont(functiondef);
+ }
+ function afterprop(type) {
+ if (type == ":") return cont(expressionNoComma);
+ if (type == "(") return pass(functiondef);
+ }
+ function commasep(what, end, sep) {
+ function proceed(type, value) {
+ if (sep ? sep.indexOf(type) > -1 : type == ",") {
+ var lex = cx.state.lexical;
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+ return cont(function(type, value) {
+ if (type == end || value == end) return pass()
+ return pass(what)
+ }, proceed);
+ }
+ if (type == end || value == end) return cont();
+ return cont(expect(end));
}
+ return function(type, value) {
+ if (type == end || value == end) return cont();
+ return pass(what, proceed);
+ };
}
- function tagNameState(type, stream, state) {
- if (type == "word") {
- state.tagName = stream.current();
- setStyle = "tag";
- return attrState;
- } else {
- setStyle = "error";
- return tagNameState;
+ function contCommasep(what, end, info) {
+ for (var i = 3; i < arguments.length; i++)
+ cx.cc.push(arguments[i]);
+ return cont(pushlex(end, info), commasep(what, end), poplex);
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function maybetype(type, value) {
+ if (isTS) {
+ if (type == ":") return cont(typeexpr);
+ if (value == "?") return cont(maybetype);
}
}
- function closeTagNameState(type, stream, state) {
- if (type == "word") {
- var tagName = stream.current();
- if (state.context && state.context.tagName != tagName &&
- config.implicitlyClosed.hasOwnProperty(state.context.tagName))
- popContext(state);
- if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
- setStyle = "tag";
- return closeState;
+ function typeexpr(type, value) {
+ if (type == "variable") {
+ if (value == "keyof") {
+ cx.marked = "keyword"
+ return cont(typeexpr)
} else {
- setStyle = "tag error";
- return closeStateErr;
+ cx.marked = "type"
+ return cont(afterType)
}
- } else {
- setStyle = "error";
- return closeStateErr;
}
+ if (type == "string" || type == "number" || type == "atom") return cont(afterType);
+ if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
+ if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
+ if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
}
-
- function closeState(type, _stream, state) {
- if (type != "endTag") {
- setStyle = "error";
- return closeState;
- }
- popContext(state);
- return baseState;
+ function maybeReturnType(type) {
+ if (type == "=>") return cont(typeexpr)
}
- function closeStateErr(type, stream, state) {
- setStyle = "error";
- return closeState(type, stream, state);
+ function typeprop(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property"
+ return cont(typeprop)
+ } else if (value == "?") {
+ return cont(typeprop)
+ } else if (type == ":") {
+ return cont(typeexpr)
+ } else if (type == "[") {
+ return cont(expression, maybetype, expect("]"), typeprop)
+ }
}
-
- function attrState(type, _stream, state) {
- if (type == "word") {
- setStyle = "attribute";
- return attrEqState;
- } else if (type == "endTag" || type == "selfcloseTag") {
- var tagName = state.tagName, tagStart = state.tagStart;
- state.tagName = state.tagStart = null;
- if (type == "selfcloseTag" ||
- config.autoSelfClosers.hasOwnProperty(tagName)) {
- maybePopContext(state, tagName);
- } else {
- maybePopContext(state, tagName);
- state.context = new Context(state, tagName, tagStart == state.indented);
- }
- return baseState;
+ function typearg(type) {
+ if (type == "variable") return cont(typearg)
+ else if (type == ":") return cont(typeexpr)
+ }
+ function afterType(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ if (value == "|" || type == ".") return cont(typeexpr)
+ if (type == "[") return cont(expect("]"), afterType)
+ if (value == "extends") return cont(typeexpr)
+ }
+ function maybeTypeArgs(_, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ }
+ function vardef() {
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
+ }
+ function pattern(type, value) {
+ if (type == "modifier") return cont(pattern)
+ if (type == "variable") { register(value); return cont(); }
+ if (type == "spread") return cont(pattern);
+ if (type == "[") return contCommasep(pattern, "]");
+ if (type == "{") return contCommasep(proppattern, "}");
+ }
+ function proppattern(type, value) {
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
+ register(value);
+ return cont(maybeAssign);
}
- setStyle = "error";
- return attrState;
+ if (type == "variable") cx.marked = "property";
+ if (type == "spread") return cont(pattern);
+ if (type == "}") return pass();
+ return cont(expect(":"), pattern, maybeAssign);
}
- function attrEqState(type, stream, state) {
- if (type == "equals") return attrValueState;
- if (!config.allowMissing) setStyle = "error";
- return attrState(type, stream, state);
+ function maybeAssign(_type, value) {
+ if (value == "=") return cont(expressionNoComma);
}
- function attrValueState(type, stream, state) {
- if (type == "string") return attrContinuedState;
- if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
- setStyle = "error";
- return attrState(type, stream, state);
+ function vardefCont(type) {
+ if (type == ",") return cont(vardef);
}
- function attrContinuedState(type, stream, state) {
- if (type == "string") return attrContinuedState;
- return attrState(type, stream, state);
+ function maybeelse(type, value) {
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
+ }
+ function forspec(type) {
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
+ }
+ function forspec1(type) {
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
+ if (type == ";") return cont(forspec2);
+ if (type == "variable") return cont(formaybeinof);
+ return pass(expression, expect(";"), forspec2);
+ }
+ function formaybeinof(_type, value) {
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return cont(maybeoperatorComma, forspec2);
+ }
+ function forspec2(type, value) {
+ if (type == ";") return cont(forspec3);
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return pass(expression, expect(";"), forspec3);
+ }
+ function forspec3(type) {
+ if (type != ")") cont(expression);
+ }
+ function functiondef(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
+ if (type == "variable") {register(value); return cont(functiondef);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, functiondef)
+ }
+ function funarg(type, value) {
+ if (value == "@") cont(expression, funarg)
+ if (type == "spread" || type == "modifier") return cont(funarg);
+ return pass(pattern, maybetype, maybeAssign);
+ }
+ function classExpression(type, value) {
+ // Class expressions may have an optional name.
+ if (type == "variable") return className(type, value);
+ return classNameAfter(type, value);
+ }
+ function className(type, value) {
+ if (type == "variable") {register(value); return cont(classNameAfter);}
+ }
+ function classNameAfter(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, classNameAfter)
+ if (value == "extends" || value == "implements" || (isTS && type == ","))
+ return cont(isTS ? typeexpr : expression, classNameAfter);
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
+ }
+ function classBody(type, value) {
+ if (type == "modifier" || type == "async" ||
+ (type == "variable" &&
+ (value == "static" || value == "get" || value == "set") &&
+ cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ return cont(isTS ? classfield : functiondef, classBody);
+ }
+ if (type == "[")
+ return cont(expression, expect("]"), isTS ? classfield : functiondef, classBody)
+ if (value == "*") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == ";") return cont(classBody);
+ if (type == "}") return cont();
+ if (value == "@") return cont(expression, classBody)
+ }
+ function classfield(type, value) {
+ if (value == "?") return cont(classfield)
+ if (type == ":") return cont(typeexpr, maybeAssign)
+ if (value == "=") return cont(expressionNoComma)
+ return pass(functiondef)
+ }
+ function afterExport(type, value) {
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
+ if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
+ return pass(statement);
+ }
+ function exportField(type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
+ if (type == "variable") return pass(expressionNoComma, exportField);
+ }
+ function afterImport(type) {
+ if (type == "string") return cont();
+ return pass(importSpec, maybeMoreImports, maybeFrom);
+ }
+ function importSpec(type, value) {
+ if (type == "{") return contCommasep(importSpec, "}");
+ if (type == "variable") register(value);
+ if (value == "*") cx.marked = "keyword";
+ return cont(maybeAs);
+ }
+ function maybeMoreImports(type) {
+ if (type == ",") return cont(importSpec, maybeMoreImports)
+ }
+ function maybeAs(_type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
+ }
+ function maybeFrom(_type, value) {
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
+ }
+ function arrayLiteral(type) {
+ if (type == "]") return cont();
+ return pass(commasep(expressionNoComma, "]"));
+ }
+
+ function isContinuedStatement(state, textAfter) {
+ return state.lastType == "operator" || state.lastType == "," ||
+ isOperatorChar.test(textAfter.charAt(0)) ||
+ /[,.]/.test(textAfter.charAt(0));
+ }
+
+ function expressionAllowed(stream, state, backUp) {
+ return state.tokenize == tokenBase &&
+ /^(?:operator|sof|keyword [bc]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
}
+ // Interface
+
return {
- startState: function(baseIndent) {
- var state = {tokenize: inText,
- state: baseState,
- indented: baseIndent || 0,
- tagName: null, tagStart: null,
- context: null}
- if (baseIndent != null) state.baseIndent = baseIndent
- return state
+ startState: function(basecolumn) {
+ var state = {
+ tokenize: tokenBase,
+ lastType: "sof",
+ cc: [],
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
+ indented: basecolumn || 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
},
token: function(stream, state) {
- if (!state.tagName && stream.sol())
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
state.indented = stream.indentation();
-
- if (stream.eatSpace()) return null;
- type = null;
- var style = state.tokenize(stream, state);
- if ((style || type) && style != "comment") {
- setStyle = null;
- state.state = state.state(type || style, stream, state);
- if (setStyle)
- style = setStyle == "error" ? style + " error" : setStyle;
+ findFatArrow(stream, state);
}
- return style;
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+ return parseJS(state, style, type, content, stream);
},
- indent: function(state, textAfter, fullLine) {
- var context = state.context;
- // Indent multi-line strings (e.g. css).
- if (state.tokenize.isInAttribute) {
- if (state.tagStart == state.indented)
- return state.stringStartCol + 1;
- else
- return state.indented + indentUnit;
- }
- if (context && context.noIndent) return CodeMirror.Pass;
- if (state.tokenize != inTag && state.tokenize != inText)
- return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
- // Indent the starts of attribute names.
- if (state.tagName) {
- if (config.multilineTagIndentPastTag !== false)
- return state.tagStart + state.tagName.length + 2;
- else
- return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
- }
- if (config.alignCDATA && /= 0; --i) {
+ var c = state.cc[i];
+ if (c == poplex) lexical = lexical.prev;
+ else if (c != maybeelse) break;
}
- while (context && context.prev && !context.startOfLine)
- context = context.prev;
- if (context) return context.indent + indentUnit;
- else return state.baseIndent || 0;
+ while ((lexical.type == "stat" || lexical.type == "form") &&
+ (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
+ (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
+ !/^[,\.=+\-*:?[\(]/.test(textAfter))))
+ lexical = lexical.prev;
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+ lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "form") return lexical.indented + indentUnit;
+ else if (type == "stat")
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
},
- electricInput: /<\/[\s\w:]+>$/,
- blockCommentStart: "",
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
+ blockCommentStart: jsonMode ? null : "/*",
+ blockCommentEnd: jsonMode ? null : "*/",
+ lineComment: jsonMode ? null : "//",
+ fold: "brace",
+ closeBrackets: "()[]{}''\"\"``",
- configuration: config.htmlMode ? "html" : "xml",
- helperType: config.htmlMode ? "html" : "xml",
+ helperType: jsonMode ? "json" : "javascript",
+ jsonldMode: jsonldMode,
+ jsonMode: jsonMode,
- skipAttribute: function(state) {
- if (state.state == attrValueState)
- state.state = attrState
+ expressionAllowed: expressionAllowed,
+
+ skipExpression: function(state) {
+ var top = state.cc[state.cc.length - 1]
+ if (top == expression || top == expressionNoComma) state.cc.pop()
}
};
});
- CodeMirror.defineMIME("text/xml", "xml");
- CodeMirror.defineMIME("application/xml", "xml");
- if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
- CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
+
+ CodeMirror.defineMIME("text/javascript", "javascript");
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
+ CodeMirror.defineMIME("application/javascript", "javascript");
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
/***/ }),
-/* 322 */
+/* 344 */
/***/ (function(module, exports, __webpack_require__) {
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: http://codemirror.net/LICENSE
-
- (function(mod) {
- if (true) // CommonJS
- mod(__webpack_require__(319));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
"use strict";
- function expressionAllowed(stream, state, backUp) {
- return /^(?:operator|sof|keyword c|case|new|export|default|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
- (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
- }
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
- CodeMirror.defineMode("javascript", function(config, parserConfig) {
- var indentUnit = config.indentUnit;
- var statementIndent = parserConfig.statementIndent;
- var jsonldMode = parserConfig.jsonld;
- var jsonMode = parserConfig.json || jsonldMode;
- var isTS = parserConfig.typescript;
- var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
+ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
- // Tokenizer
+ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
- var keywords = function(){
- function kw(type) {return {type: type, style: "keyword"};}
- var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
- var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+ var _react = __webpack_require__(327);
- var jsKeywords = {
- "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
- "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C,
- "var": kw("var"), "const": kw("var"), "let": kw("var"),
- "function": kw("function"), "catch": kw("catch"),
- "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
- "in": operator, "typeof": operator, "instanceof": operator,
- "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
- "this": kw("this"), "class": kw("class"), "super": kw("atom"),
- "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
- "await": C, "async": kw("async")
- };
+ var _react2 = _interopRequireDefault(_react);
- // Extend the 'normal' keywords with the TypeScript language extensions
- if (isTS) {
- var type = {type: "variable", style: "variable-3"};
- var tsKeywords = {
- // object-like things
- "interface": kw("class"),
- "implements": C,
- "namespace": C,
- "module": kw("module"),
- "enum": kw("module"),
- "type": kw("type"),
+ var _propTypes = __webpack_require__(328);
- // scope modifiers
- "public": kw("modifier"),
- "private": kw("modifier"),
- "protected": kw("modifier"),
- "abstract": kw("modifier"),
+ var _propTypes2 = _interopRequireDefault(_propTypes);
- // operators
- "as": operator,
+ var _reactDom = __webpack_require__(345);
- // types
- "string": type, "number": type, "boolean": type, "any": type
- };
+ var _server = __webpack_require__(346);
- for (var attr in tsKeywords) {
- jsKeywords[attr] = tsKeywords[attr];
- }
- }
+ var _server2 = _interopRequireDefault(_server);
- return jsKeywords;
- }();
+ var _babelStandalone = __webpack_require__(355);
- var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
- var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function readRegexp(stream) {
- var escaped = false, next, inSet = false;
- while ((next = stream.next()) != null) {
- if (!escaped) {
- if (next == "/" && !inSet) return;
- if (next == "[") inSet = true;
- else if (inSet && next == "]") inSet = false;
- }
- escaped = !escaped && next == "\\";
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+ function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
+
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable max-statements */
+
+
+ var Preview = function (_Component) {
+ _inherits(Preview, _Component);
+
+ function Preview() {
+ var _ref;
+
+ var _temp, _this, _ret;
+
+ _classCallCheck(this, Preview);
+
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
}
- }
- // Used as scratch variables to communicate multiple values without
- // consing up tons of objects.
- var type, content;
- function ret(tp, style, cont) {
- type = tp; content = cont;
- return style;
- }
- function tokenBase(stream, state) {
- var ch = stream.next();
- if (ch == '"' || ch == "'") {
- state.tokenize = tokenString(ch);
- return state.tokenize(stream, state);
- } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
- return ret("number", "number");
- } else if (ch == "." && stream.match("..")) {
- return ret("spread", "meta");
- } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
- return ret(ch);
- } else if (ch == "=" && stream.eat(">")) {
- return ret("=>", "operator");
- } else if (ch == "0" && stream.eat(/x/i)) {
- stream.eatWhile(/[\da-f]/i);
- return ret("number", "number");
- } else if (ch == "0" && stream.eat(/o/i)) {
- stream.eatWhile(/[0-7]/i);
- return ret("number", "number");
- } else if (ch == "0" && stream.eat(/b/i)) {
- stream.eatWhile(/[01]/i);
- return ret("number", "number");
- } else if (/\d/.test(ch)) {
- stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
- return ret("number", "number");
- } else if (ch == "/") {
- if (stream.eat("*")) {
- state.tokenize = tokenComment;
- return tokenComment(stream, state);
- } else if (stream.eat("/")) {
- stream.skipToEnd();
- return ret("comment", "comment");
- } else if (expressionAllowed(stream, state, 1)) {
- readRegexp(stream);
- stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
- return ret("regexp", "string-2");
+ return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Preview.__proto__ || Object.getPrototypeOf(Preview)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
+ error: null
+ }, _this._compileCode = function () {
+ var _this$props = _this.props,
+ code = _this$props.code,
+ context = _this$props.context,
+ noRender = _this$props.noRender,
+ scope = _this$props.scope;
+
+ var generateContextTypes = function generateContextTypes(c) {
+ return "{ " + Object.keys(c).map(function (val) {
+ return val + ": PropTypes.any.isRequired";
+ }).join(", ") + " }";
+ };
+
+ var scopeWithProps = _extends({}, scope, { PropTypes: _propTypes2.default });
+
+ if (noRender) {
+ return (0, _babelStandalone.transform)("\n ((" + Object.keys(scopeWithProps).join(", ") + ", mountNode) => {\n class Comp extends React.Component {\n\n getChildContext() {\n return " + JSON.stringify(context) + ";\n }\n\n render() {\n return (\n " + code + "\n );\n }\n }\n\n Comp.childContextTypes = " + generateContextTypes(context) + ";\n\n return Comp;\n });\n ", { presets: ["es2015", "react", "stage-1"] }).code;
} else {
- stream.eatWhile(isOperatorChar);
- return ret("operator", "operator", stream.current());
+ return (0, _babelStandalone.transform)("\n ((" + Object.keys(scopeWithProps).join(",") + ", mountNode) => {\n " + code + "\n });\n ", { presets: ["es2015", "react", "stage-1"] }).code;
}
- } else if (ch == "`") {
- state.tokenize = tokenQuasi;
- return tokenQuasi(stream, state);
- } else if (ch == "#") {
- stream.skipToEnd();
- return ret("error", "error");
- } else if (isOperatorChar.test(ch)) {
- if (ch != ">" || !state.lexical || state.lexical.type != ">")
- stream.eatWhile(isOperatorChar);
- return ret("operator", "operator", stream.current());
- } else if (wordRE.test(ch)) {
- stream.eatWhile(wordRE);
- var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
- return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
- ret("variable", "variable", word);
- }
- }
+ }, _this._executeCode = function () {
+ var mountNode = _this.mount;
+ var _this$props2 = _this.props,
+ scope = _this$props2.scope,
+ noRender = _this$props2.noRender,
+ previewComponent = _this$props2.previewComponent;
- function tokenString(quote) {
- return function(stream, state) {
- var escaped = false, next;
- if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
- state.tokenize = tokenBase;
- return ret("jsonld-keyword", "meta");
- }
- while ((next = stream.next()) != null) {
- if (next == quote && !escaped) break;
- escaped = !escaped && next == "\\";
- }
- if (!escaped) state.tokenize = tokenBase;
- return ret("string", "string");
- };
- }
- function tokenComment(stream, state) {
- var maybeEnd = false, ch;
- while (ch = stream.next()) {
- if (ch == "/" && maybeEnd) {
- state.tokenize = tokenBase;
- break;
- }
- maybeEnd = (ch == "*");
- }
- return ret("comment", "comment");
- }
+ var scopeWithProps = _extends({}, scope, { PropTypes: _propTypes2.default });
- function tokenQuasi(stream, state) {
- var escaped = false, next;
- while ((next = stream.next()) != null) {
- if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
- state.tokenize = tokenBase;
- break;
+ var tempScope = [];
+
+ try {
+ Object.keys(scopeWithProps).forEach(function (s) {
+ return tempScope.push(scopeWithProps[s]);
+ });
+ tempScope.push(mountNode);
+ var compiledCode = _this._compileCode();
+ if (noRender) {
+ /* eslint-disable no-eval, max-len */
+ var Comp = _react2.default.createElement(eval(compiledCode).apply(undefined, tempScope));
+ _server2.default.renderToString(_react2.default.createElement(previewComponent, {}, Comp));
+ (0, _reactDom.render)(_react2.default.createElement(previewComponent, {}, Comp), mountNode);
+ } else {
+ eval(compiledCode).apply(undefined, tempScope);
+ }
+ /* eslint-enable no-eval, max-len */
+ clearTimeout(_this.timeoutID);
+ _this.setState({ error: null });
+ } catch (err) {
+ var error = err.toString();
+ clearTimeout(_this.timeoutID); //eslint-disable-line no-undef
+ _this.timeoutID = setTimeout(function () {
+ _this.setState({ error: error });
+ }, 500);
}
- escaped = !escaped && next == "\\";
- }
- return ret("quasi", "string-2", stream.current());
+ }, _this.componentDidMount = function () {
+ _this._executeCode();
+ }, _this.componentDidUpdate = function (prevProps) {
+ if (_this.props.code !== prevProps.code) {
+ _this._executeCode();
+ }
+ }, _temp), _possibleConstructorReturn(_this, _ret);
}
- var brackets = "([{}])";
- // This is a crude lookahead trick to try and notice that we're
- // parsing the argument patterns for a fat-arrow function before we
- // actually hit the arrow token. It only works if the arrow is on
- // the same line as the arguments and there's no strange noise
- // (comments) in between. Fallback is to only notice when we hit the
- // arrow, and not declare the arguments as locals for the arrow
- // body.
- function findFatArrow(stream, state) {
- if (state.fatArrowAt) state.fatArrowAt = null;
- var arrow = stream.string.indexOf("=>", stream.start);
- if (arrow < 0) return;
+ _createClass(Preview, [{
+ key: "render",
+ value: function render() {
+ var _this2 = this;
- if (isTS) { // Try to skip TypeScript return type declarations after the arguments
- var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
- if (m) arrow = m.index
- }
+ var error = this.state.error;
- var depth = 0, sawSomething = false;
- for (var pos = arrow - 1; pos >= 0; --pos) {
- var ch = stream.string.charAt(pos);
- var bracket = brackets.indexOf(ch);
- if (bracket >= 0 && bracket < 3) {
- if (!depth) { ++pos; break; }
- if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
- } else if (bracket >= 3 && bracket < 6) {
- ++depth;
- } else if (wordRE.test(ch)) {
- sawSomething = true;
- } else if (/["'\/]/.test(ch)) {
- return;
- } else if (sawSomething && !depth) {
- ++pos;
- break;
- }
+ return _react2.default.createElement(
+ "div",
+ null,
+ error !== null ? _react2.default.createElement(
+ "div",
+ { className: "playgroundError" },
+ error
+ ) : null,
+ _react2.default.createElement("div", { ref: function ref(c) {
+ _this2.mount = c;
+ }, className: "previewArea" })
+ );
}
- if (sawSomething && !depth) state.fatArrowAt = pos;
- }
+ }]);
- // Parser
+ return Preview;
+ }(_react.Component);
- var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
+ Preview.defaultProps = {
+ previewComponent: "div"
+ };
+ Preview.propTypes = {
+ code: _propTypes2.default.string.isRequired,
+ scope: _propTypes2.default.object.isRequired,
+ previewComponent: _propTypes2.default.node,
+ noRender: _propTypes2.default.bool,
+ context: _propTypes2.default.object
+ };
+ exports.default = Preview;
+
+/***/ }),
+/* 345 */
+/***/ (function(module, exports) {
+
+ module.exports = __WEBPACK_EXTERNAL_MODULE_345__;
+
+/***/ }),
+/* 346 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ /* WEBPACK VAR INJECTION */(function(process) {'use strict';
- function JSLexical(indented, column, type, align, prev, info) {
- this.indented = indented;
- this.column = column;
- this.type = type;
- this.prev = prev;
- this.info = info;
- if (align != null) this.align = align;
- }
+ if (process.env.NODE_ENV === 'production') {
+ module.exports = __webpack_require__(347);
+ } else {
+ module.exports = __webpack_require__(352);
+ }
- function inScope(state, varname) {
- for (var v = state.localVars; v; v = v.next)
- if (v.name == varname) return true;
- for (var cx = state.context; cx; cx = cx.prev) {
- for (var v = cx.vars; v; v = v.next)
- if (v.name == varname) return true;
- }
- }
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
+
+/***/ }),
+/* 347 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ /*
+ React v16.0.0
+ react-dom-server.browser.production.min.js
- function parseJS(state, style, type, content, stream) {
- var cc = state.cc;
- // Communicate our context to the combinators.
- // (Less wasteful than consing up a hundred closures on every call.)
- cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
+ Copyright (c) 2013-present, Facebook, Inc.
- if (!state.lexical.hasOwnProperty("align"))
- state.lexical.align = true;
+ This source code is licensed under the MIT license found in the
+ LICENSE file in the root directory of this source tree.
+ */
+ 'use strict';var h=__webpack_require__(334);__webpack_require__(332);var m=__webpack_require__(327),n=__webpack_require__(348),aa=__webpack_require__(349),ba=__webpack_require__(351);
+ function w(a){for(var b=arguments.length-1,g="Minified React error #"+a+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant\x3d"+a,d=0;d=e.hasBooleanValue+e.hasNumericValue+e.hasOverloadedBooleanValue?void 0:w("50",f);k.hasOwnProperty(f)&&(e.attributeName=k[f]);d.hasOwnProperty(f)&&(e.attributeNamespace=d[f]);a.hasOwnProperty(f)&&(e.mutationMethod=a[f]);D.properties[f]=e}}},D=
+ {ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",ATTRIBUTE_NAME_CHAR:":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",
+ properties:{},shouldSetAttribute:function(a,b){if(D.isReservedProp(a)||!("o"!==a[0]&&"O"!==a[0]||"n"!==a[1]&&"N"!==a[1]))return!1;if(null===b)return!0;switch(typeof b){case "boolean":return D.shouldAttributeAcceptBooleanValue(a);case "undefined":case "number":case "string":case "object":return!0;default:return!1}},getPropertyInfo:function(a){return D.properties.hasOwnProperty(a)?D.properties[a]:null},shouldAttributeAcceptBooleanValue:function(a){if(D.isReservedProp(a))return!0;var b=D.getPropertyInfo(a);
+ if(b)return b.hasBooleanValue||b.hasStringBooleanValue||b.hasOverloadedBooleanValue;a=a.toLowerCase().slice(0,5);return"data-"===a||"aria-"===a},isReservedProp:function(a){return ca.hasOwnProperty(a)},injection:C},E=D,da=/["'&<>]/;
+ function F(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=da.exec(a);if(b){var g="",d,k=0;for(d=b.index;db||g.hasOverloadedBooleanValue&&!1===b)return"";var d=g.attributeName;if(g.hasBooleanValue||g.hasOverloadedBooleanValue&&!0===b)return d+'\x3d""';if("boolean"!==typeof b||E.shouldAttributeAcceptBooleanValue(a))return d+
+ "\x3d"+('"'+F(b)+'"')}else if(E.shouldSetAttribute(a,b))return null==b?"":a+"\x3d"+('"'+F(b)+'"');return null},createMarkupForCustomAttribute:function(a,b){return fa(a)&&null!=b?a+"\x3d"+('"'+F(b)+'"'):""}},J={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},ha=h({menuitem:!0},J),K={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,
+ columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ia=["Webkit","ms","Moz","O"];
+ Object.keys(K).forEach(function(a){ia.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);K[b]=K[a]})});var L=y.Namespaces,ja=y.getIntrinsicNamespace,ka=y.getChildNamespace,M=m.Children.toArray,la={listing:!0,pre:!0,textarea:!0};function N(a){return"string"===typeof a?a:"function"===typeof a?a.displayName||a.name:null}var ma=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,O={},na=ba(function(a){return aa(a)});
+ function oa(a){var b="";m.Children.forEach(a,function(a){null==a||"string"!==typeof a&&"number"!==typeof a||(b+=a)});return b}function pa(a,b){if(a=a.contextTypes){var g={},d;for(d in a)g[d]=b[d];b=g}else b=n;return b}var qa={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null};function P(a,b){void 0===a&&w("152",N(b)||"Component")}
+ function ra(a,b){for(;m.isValidElement(a);){var g=a.type;if("function"!==typeof g)break;var d=pa(g,b),k=[],f=!1,e={isMounted:function(){return!1},enqueueForceUpdate:function(){if(null===k)return null},enqueueReplaceState:function(a,b){f=!0;k=[b]},enqueueSetState:function(a,b){if(null===k)return null;k.push(b)}};if(g.prototype&&g.prototype.isReactComponent)var c=new g(a.props,d,e);else if(c=g(a.props,d,e),null==c||null==c.render){a=c;P(a,g);continue}c.props=a.props;c.context=d;c.updater=e;e=c.state;
+ void 0===e&&(c.state=e=null);if(c.componentWillMount)if(c.componentWillMount(),k.length){e=k;var q=f;k=null;f=!1;if(q&&1===e.length)c.state=e[0];else{var r=q?e[0]:c.state,l=!0;for(q=q?1:0;q=
+ d.children.length)b+=d.footer,this.previousWasTextNode=!1,this.stack.pop(),"select"===d.tag&&(this.currentSelectValue=null);else{var k=d.children[d.childIndex++];b+=this.render(k,d.context,d.domNamespace)}}return b};a.prototype.render=function(a,g,d){if("string"===typeof a||"number"===typeof a){d=""+a;if(""===d)return"";if(this.makeStaticMarkup)return F(d);if(this.previousWasTextNode)return"\x3c!-- --\x3e"+F(d);this.previousWasTextNode=!0;return F(d)}g=ra(a,g);a=g.child;g=g.context;if(null===a||!1===
+ a)return"";if(m.isValidElement(a))return this.renderDOM(a,g,d);a=M(a);this.stack.push({domNamespace:d,children:a,childIndex:0,context:g,footer:""});return""};a.prototype.renderDOM=function(a,g,d){var b=a.type.toLowerCase();d===L.html&&ja(b);O.hasOwnProperty(b)||(ma.test(b)?void 0:w("65",b),O[b]=!0);var f=a.props;if("input"===b)f=h({type:void 0},f,{defaultChecked:void 0,defaultValue:void 0,value:null!=f.value?f.value:f.defaultValue,checked:null!=f.checked?f.checked:f.defaultChecked});else if("textarea"===
+ b){var e=f.value;if(null==e){e=f.defaultValue;var c=f.children;null!=c&&(null!=e?w("92"):void 0,Array.isArray(c)&&(1>=c.length?void 0:w("93"),c=c[0]),e=""+c);null==e&&(e="")}f=h({},f,{value:void 0,children:""+e})}else if("select"===b)this.currentSelectValue=null!=f.value?f.value:f.defaultValue,f=h({},f,{value:void 0});else if("option"===b){c=this.currentSelectValue;var q=oa(f.children);if(null!=c){var r=null!=f.value?f.value+"":q;e=!1;if(Array.isArray(c))for(var l=0;l= 0; i--) cx.cc.push(arguments[i]);
- }
- function cont() {
- pass.apply(null, arguments);
- return true;
- }
- function register(varname) {
- function inList(list) {
- for (var v = list; v; v = v.next)
- if (v.name == varname) return true;
- return false;
- }
- var state = cx.state;
- cx.marked = "def";
- if (state.context) {
- if (inList(state.localVars)) return;
- state.localVars = {name: varname, next: state.localVars};
- } else {
- if (inList(state.globalVars)) return;
- if (parserConfig.globalVars)
- state.globalVars = {name: varname, next: state.globalVars};
+ if (process.env.NODE_ENV !== 'production') {
+ Object.freeze(emptyObject);
+ }
+
+ module.exports = emptyObject;
+ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329)))
+
+/***/ }),
+/* 349 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @typechecks
+ */
+
+ 'use strict';
+
+ var hyphenate = __webpack_require__(350);
+
+ var msPattern = /^ms-/;
+
+ /**
+ * Hyphenates a camelcased CSS property name, for example:
+ *
+ * > hyphenateStyleName('backgroundColor')
+ * < "background-color"
+ * > hyphenateStyleName('MozTransition')
+ * < "-moz-transition"
+ * > hyphenateStyleName('msTransition')
+ * < "-ms-transition"
+ *
+ * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
+ * is converted to `-ms-`.
+ *
+ * @param {string} string
+ * @return {string}
+ */
+ function hyphenateStyleName(string) {
+ return hyphenate(string).replace(msPattern, '-ms-');
+ }
+
+ module.exports = hyphenateStyleName;
+
+/***/ }),
+/* 350 */
+/***/ (function(module, exports) {
+
+ 'use strict';
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @typechecks
+ */
+
+ var _uppercasePattern = /([A-Z])/g;
+
+ /**
+ * Hyphenates a camelcased string, for example:
+ *
+ * > hyphenate('backgroundColor')
+ * < "background-color"
+ *
+ * For CSS style names, use `hyphenateStyleName` instead which works properly
+ * with all vendor prefixes, including `ms`.
+ *
+ * @param {string} string
+ * @return {string}
+ */
+ function hyphenate(string) {
+ return string.replace(_uppercasePattern, '-$1').toLowerCase();
+ }
+
+ module.exports = hyphenate;
+
+/***/ }),
+/* 351 */
+/***/ (function(module, exports) {
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ *
+ * @typechecks static-only
+ */
+
+ 'use strict';
+
+ /**
+ * Memoizes the return value of a function that accepts one string argument.
+ */
+
+ function memoizeStringOnly(callback) {
+ var cache = {};
+ return function (string) {
+ if (!cache.hasOwnProperty(string)) {
+ cache[string] = callback.call(this, string);
}
- }
+ return cache[string];
+ };
+ }
- // Combinators
+ module.exports = memoizeStringOnly;
+
+/***/ }),
+/* 352 */
+/***/ (function(module, exports, __webpack_require__) {
+
+ /* WEBPACK VAR INJECTION */(function(process) {/** @license React v16.0.0
+ * react-dom-server.browser.development.js
+ *
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+ 'use strict';
- var defaultVars = {name: "this", next: {name: "arguments"}};
- function pushcontext() {
- cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
- cx.state.localVars = defaultVars;
- }
- function popcontext() {
- cx.state.localVars = cx.state.context.vars;
- cx.state.context = cx.state.context.prev;
+
+ if (process.env.NODE_ENV !== "production") {
+ (function() {
+
+ 'use strict';
+
+ var objectAssign$1 = __webpack_require__(334);
+ var invariant = __webpack_require__(332);
+ var require$$0 = __webpack_require__(333);
+ var react = __webpack_require__(327);
+ var emptyFunction = __webpack_require__(331);
+ var propTypes = __webpack_require__(328);
+ var emptyObject = __webpack_require__(348);
+ var hyphenateStyleName = __webpack_require__(349);
+ var memoizeStringOnly = __webpack_require__(351);
+ var checkPropTypes = __webpack_require__(336);
+ var camelizeStyleName = __webpack_require__(353);
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @providesModule reactProdInvariant
+ *
+ */
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @providesModule DOMNamespaces
+ */
+
+ var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
+ var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
+ var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
+
+ var Namespaces$1 = {
+ html: HTML_NAMESPACE,
+ mathml: MATH_NAMESPACE,
+ svg: SVG_NAMESPACE
+ };
+
+ // Assumes there is no parent namespace.
+ function getIntrinsicNamespace$1(type) {
+ switch (type) {
+ case 'svg':
+ return SVG_NAMESPACE;
+ case 'math':
+ return MATH_NAMESPACE;
+ default:
+ return HTML_NAMESPACE;
}
- function pushlex(type, info) {
- var result = function() {
- var state = cx.state, indent = state.indented;
- if (state.lexical.type == "stat") indent = state.lexical.indented;
- else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
- indent = outer.indented;
- state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
- };
- result.lex = true;
- return result;
+ }
+
+ function getChildNamespace$1(parentNamespace, type) {
+ if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
+ // No (or default) parent namespace: potential entry point.
+ return getIntrinsicNamespace$1(type);
}
- function poplex() {
- var state = cx.state;
- if (state.lexical.prev) {
- if (state.lexical.type == ")")
- state.indented = state.lexical.indented;
- state.lexical = state.lexical.prev;
- }
+ if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
+ // We're leaving SVG.
+ return HTML_NAMESPACE;
}
- poplex.lex = true;
+ // By default, pass namespace below.
+ return parentNamespace;
+ }
- function expect(wanted) {
- function exp(type) {
- if (type == wanted) return cont();
- else if (wanted == ";") return pass();
- else return cont(exp);
- };
- return exp;
- }
+ var Namespaces_1 = Namespaces$1;
+ var getIntrinsicNamespace_1 = getIntrinsicNamespace$1;
+ var getChildNamespace_1 = getChildNamespace$1;
- function statement(type, value) {
- if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
- if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
- if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
- if (type == "{") return cont(pushlex("}"), block, poplex);
- if (type == ";") return cont();
- if (type == "if") {
- if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
- cx.state.cc.pop()();
- return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
+ var DOMNamespaces = {
+ Namespaces: Namespaces_1,
+ getIntrinsicNamespace: getIntrinsicNamespace_1,
+ getChildNamespace: getChildNamespace_1
+ };
+
+ // These attributes should be all lowercase to allow for
+ // case insensitive checks
+ var RESERVED_PROPS$1 = {
+ children: true,
+ dangerouslySetInnerHTML: true,
+ autoFocus: true,
+ defaultValue: true,
+ defaultChecked: true,
+ innerHTML: true,
+ suppressContentEditableWarning: true,
+ style: true
+ };
+
+ function checkMask(value, bitmask) {
+ return (value & bitmask) === bitmask;
+ }
+
+ var DOMPropertyInjection = {
+ /**
+ * Mapping from normalized, camelcased property names to a configuration that
+ * specifies how the associated DOM property should be accessed or rendered.
+ */
+ MUST_USE_PROPERTY: 0x1,
+ HAS_BOOLEAN_VALUE: 0x4,
+ HAS_NUMERIC_VALUE: 0x8,
+ HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
+ HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
+ HAS_STRING_BOOLEAN_VALUE: 0x40,
+
+ /**
+ * Inject some specialized knowledge about the DOM. This takes a config object
+ * with the following properties:
+ *
+ * Properties: object mapping DOM property name to one of the
+ * DOMPropertyInjection constants or null. If your attribute isn't in here,
+ * it won't get written to the DOM.
+ *
+ * DOMAttributeNames: object mapping React attribute name to the DOM
+ * attribute name. Attribute names not specified use the **lowercase**
+ * normalized name.
+ *
+ * DOMAttributeNamespaces: object mapping React attribute name to the DOM
+ * attribute namespace URL. (Attribute names not specified use no namespace.)
+ *
+ * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
+ * Property names not specified use the normalized name.
+ *
+ * DOMMutationMethods: Properties that require special mutation methods. If
+ * `value` is undefined, the mutation method should unset the property.
+ *
+ * @param {object} domPropertyConfig the config as described above.
+ */
+ injectDOMPropertyConfig: function (domPropertyConfig) {
+ var Injection = DOMPropertyInjection;
+ var Properties = domPropertyConfig.Properties || {};
+ var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
+ var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
+ var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
+
+ for (var propName in Properties) {
+ !!DOMProperty.properties.hasOwnProperty(propName) ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : void 0;
+
+ var lowerCased = propName.toLowerCase();
+ var propConfig = Properties[propName];
+
+ var propertyInfo = {
+ attributeName: lowerCased,
+ attributeNamespace: null,
+ propertyName: propName,
+ mutationMethod: null,
+
+ mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
+ hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
+ hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
+ hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
+ hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE),
+ hasStringBooleanValue: checkMask(propConfig, Injection.HAS_STRING_BOOLEAN_VALUE)
+ };
+ !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : void 0;
+
+ if (DOMAttributeNames.hasOwnProperty(propName)) {
+ var attributeName = DOMAttributeNames[propName];
+
+ propertyInfo.attributeName = attributeName;
+ }
+
+ if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
+ propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
+ }
+
+ if (DOMMutationMethods.hasOwnProperty(propName)) {
+ propertyInfo.mutationMethod = DOMMutationMethods[propName];
+ }
+
+ // Downcase references to whitelist properties to check for membership
+ // without case-sensitivity. This allows the whitelist to pick up
+ // `allowfullscreen`, which should be written using the property configuration
+ // for `allowFullscreen`
+ DOMProperty.properties[propName] = propertyInfo;
}
- if (type == "function") return cont(functiondef);
- if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
- if (type == "variable") return cont(pushlex("stat"), maybelabel);
- if (type == "switch") return cont(pushlex("form"), parenExpr, pushlex("}", "switch"), expect("{"),
- block, poplex, poplex);
- if (type == "case") return cont(expression, expect(":"));
- if (type == "default") return cont(expect(":"));
- if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
- statement, poplex, popcontext);
- if (type == "class") return cont(pushlex("form"), className, poplex);
- if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
- if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
- if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
- if (type == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
- if (type == "async") return cont(statement)
- if (value == "@") return cont(expression, statement)
- return pass(pushlex("stat"), expression, expect(";"), poplex);
- }
- function expression(type) {
- return expressionInner(type, false);
- }
- function expressionNoComma(type) {
- return expressionInner(type, true);
- }
- function parenExpr(type) {
- if (type != "(") return pass()
- return cont(pushlex(")"), expression, expect(")"), poplex)
}
- function expressionInner(type, noComma) {
- if (cx.state.fatArrowAt == cx.stream.start) {
- var body = noComma ? arrowBodyNoComma : arrowBody;
- if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
- else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
- }
+ };
- var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
- if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
- if (type == "function") return cont(functiondef, maybeop);
- if (type == "class") return cont(pushlex("form"), classExpression, poplex);
- if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
- if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
- if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
- if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
- if (type == "{") return contCommasep(objprop, "}", null, maybeop);
- if (type == "quasi") return pass(quasi, maybeop);
- if (type == "new") return cont(maybeTarget(noComma));
- return cont();
- }
- function maybeexpression(type) {
- if (type.match(/[;\}\)\],]/)) return pass();
- return pass(expression);
- }
- function maybeexpressionNoComma(type) {
- if (type.match(/[;\}\)\],]/)) return pass();
- return pass(expressionNoComma);
- }
-
- function maybeoperatorComma(type, value) {
- if (type == ",") return cont(expression);
- return maybeoperatorNoComma(type, value, false);
- }
- function maybeoperatorNoComma(type, value, noComma) {
- var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
- var expr = noComma == false ? expression : expressionNoComma;
- if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
- if (type == "operator") {
- if (/\+\+|--/.test(value)) return cont(me);
- if (value == "?") return cont(expression, expect(":"), expr);
- return cont(expr);
- }
- if (type == "quasi") { return pass(quasi, me); }
- if (type == ";") return;
- if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
- if (type == ".") return cont(property, me);
- if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
- }
- function quasi(type, value) {
- if (type != "quasi") return pass();
- if (value.slice(value.length - 2) != "${") return cont(quasi);
- return cont(expression, continueQuasi);
- }
- function continueQuasi(type) {
- if (type == "}") {
- cx.marked = "string-2";
- cx.state.tokenize = tokenQuasi;
- return cont(quasi);
- }
- }
- function arrowBody(type) {
- findFatArrow(cx.stream, cx.state);
- return pass(type == "{" ? statement : expression);
- }
- function arrowBodyNoComma(type) {
- findFatArrow(cx.stream, cx.state);
- return pass(type == "{" ? statement : expressionNoComma);
- }
- function maybeTarget(noComma) {
- return function(type) {
- if (type == ".") return cont(noComma ? targetNoComma : target);
- else return pass(noComma ? expressionNoComma : expression);
- };
- }
- function target(_, value) {
- if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
- }
- function targetNoComma(_, value) {
- if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
- }
- function maybelabel(type) {
- if (type == ":") return cont(poplex, statement);
- return pass(maybeoperatorComma, expect(";"), poplex);
- }
- function property(type) {
- if (type == "variable") {cx.marked = "property"; return cont();}
- }
- function objprop(type, value) {
- if (type == "async") {
- cx.marked = "property";
- return cont(objprop);
- } else if (type == "variable" || cx.style == "keyword") {
- cx.marked = "property";
- if (value == "get" || value == "set") return cont(getterSetter);
- return cont(afterprop);
- } else if (type == "number" || type == "string") {
- cx.marked = jsonldMode ? "property" : (cx.style + " property");
- return cont(afterprop);
- } else if (type == "jsonld-keyword") {
- return cont(afterprop);
- } else if (type == "modifier") {
- return cont(objprop)
- } else if (type == "[") {
- return cont(expression, expect("]"), afterprop);
- } else if (type == "spread") {
- return cont(expression);
- } else if (type == ":") {
- return pass(afterprop)
- }
- }
- function getterSetter(type) {
- if (type != "variable") return pass(afterprop);
- cx.marked = "property";
- return cont(functiondef);
- }
- function afterprop(type) {
- if (type == ":") return cont(expressionNoComma);
- if (type == "(") return pass(functiondef);
- }
- function commasep(what, end, sep) {
- function proceed(type, value) {
- if (sep ? sep.indexOf(type) > -1 : type == ",") {
- var lex = cx.state.lexical;
- if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
- return cont(function(type, value) {
- if (type == end || value == end) return pass()
- return pass(what)
- }, proceed);
- }
- if (type == end || value == end) return cont();
- return cont(expect(end));
- }
- return function(type, value) {
- if (type == end || value == end) return cont();
- return pass(what, proceed);
- };
- }
- function contCommasep(what, end, info) {
- for (var i = 3; i < arguments.length; i++)
- cx.cc.push(arguments[i]);
- return cont(pushlex(end, info), commasep(what, end), poplex);
- }
- function block(type) {
- if (type == "}") return cont();
- return pass(statement, block);
- }
- function maybetype(type, value) {
- if (isTS) {
- if (type == ":") return cont(typeexpr);
- if (value == "?") return cont(maybetype);
- }
- }
- function typeexpr(type) {
- if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);}
- if (type == "string" || type == "number" || type == "atom") return cont(afterType);
- if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex)
- if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
- }
- function maybeReturnType(type) {
- if (type == "=>") return cont(typeexpr)
- }
- function typeprop(type, value) {
- if (type == "variable" || cx.style == "keyword") {
- cx.marked = "property"
- return cont(typeprop)
- } else if (value == "?") {
- return cont(typeprop)
- } else if (type == ":") {
- return cont(typeexpr)
- }
- }
- function typearg(type) {
- if (type == "variable") return cont(typearg)
- else if (type == ":") return cont(typeexpr)
- }
- function afterType(type, value) {
- if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
- if (value == "|" || type == ".") return cont(typeexpr)
- if (type == "[") return cont(expect("]"), afterType)
- }
- function vardef() {
- return pass(pattern, maybetype, maybeAssign, vardefCont);
- }
- function pattern(type, value) {
- if (type == "modifier") return cont(pattern)
- if (type == "variable") { register(value); return cont(); }
- if (type == "spread") return cont(pattern);
- if (type == "[") return contCommasep(pattern, "]");
- if (type == "{") return contCommasep(proppattern, "}");
- }
- function proppattern(type, value) {
- if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
- register(value);
- return cont(maybeAssign);
- }
- if (type == "variable") cx.marked = "property";
- if (type == "spread") return cont(pattern);
- if (type == "}") return pass();
- return cont(expect(":"), pattern, maybeAssign);
- }
- function maybeAssign(_type, value) {
- if (value == "=") return cont(expressionNoComma);
- }
- function vardefCont(type) {
- if (type == ",") return cont(vardef);
- }
- function maybeelse(type, value) {
- if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
- }
- function forspec(type) {
- if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
- }
- function forspec1(type) {
- if (type == "var") return cont(vardef, expect(";"), forspec2);
- if (type == ";") return cont(forspec2);
- if (type == "variable") return cont(formaybeinof);
- return pass(expression, expect(";"), forspec2);
- }
- function formaybeinof(_type, value) {
- if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
- return cont(maybeoperatorComma, forspec2);
- }
- function forspec2(type, value) {
- if (type == ";") return cont(forspec3);
- if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
- return pass(expression, expect(";"), forspec3);
- }
- function forspec3(type) {
- if (type != ")") cont(expression);
- }
- function functiondef(type, value) {
- if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
- if (type == "variable") {register(value); return cont(functiondef);}
- if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext);
- if (isTS && value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, functiondef)
- }
- function funarg(type) {
- if (type == "spread") return cont(funarg);
- return pass(pattern, maybetype, maybeAssign);
- }
- function classExpression(type, value) {
- // Class expressions may have an optional name.
- if (type == "variable") return className(type, value);
- return classNameAfter(type, value);
- }
- function className(type, value) {
- if (type == "variable") {register(value); return cont(classNameAfter);}
- }
- function classNameAfter(type, value) {
- if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, classNameAfter)
- if (value == "extends" || value == "implements" || (isTS && type == ","))
- return cont(isTS ? typeexpr : expression, classNameAfter);
- if (type == "{") return cont(pushlex("}"), classBody, poplex);
- }
- function classBody(type, value) {
- if (type == "variable" || cx.style == "keyword") {
- if ((value == "async" || value == "static" || value == "get" || value == "set" ||
- (isTS && (value == "public" || value == "private" || value == "protected" || value == "readonly" || value == "abstract"))) &&
- cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) {
- cx.marked = "keyword";
- return cont(classBody);
- }
- cx.marked = "property";
- return cont(isTS ? classfield : functiondef, classBody);
- }
- if (type == "[")
- return cont(expression, expect("]"), isTS ? classfield : functiondef, classBody)
- if (value == "*") {
- cx.marked = "keyword";
- return cont(classBody);
- }
- if (type == ";") return cont(classBody);
- if (type == "}") return cont();
- if (value == "@") return cont(expression, classBody)
- }
- function classfield(type, value) {
- if (value == "?") return cont(classfield)
- if (type == ":") return cont(typeexpr, maybeAssign)
- if (value == "=") return cont(expressionNoComma)
- return pass(functiondef)
- }
- function afterExport(type, value) {
- if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
- if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
- if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
- return pass(statement);
- }
- function exportField(type, value) {
- if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
- if (type == "variable") return pass(expressionNoComma, exportField);
- }
- function afterImport(type) {
- if (type == "string") return cont();
- return pass(importSpec, maybeMoreImports, maybeFrom);
- }
- function importSpec(type, value) {
- if (type == "{") return contCommasep(importSpec, "}");
- if (type == "variable") register(value);
- if (value == "*") cx.marked = "keyword";
- return cont(maybeAs);
- }
- function maybeMoreImports(type) {
- if (type == ",") return cont(importSpec, maybeMoreImports)
- }
- function maybeAs(_type, value) {
- if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
- }
- function maybeFrom(_type, value) {
- if (value == "from") { cx.marked = "keyword"; return cont(expression); }
- }
- function arrayLiteral(type) {
- if (type == "]") return cont();
- return pass(commasep(expressionNoComma, "]"));
- }
-
- function isContinuedStatement(state, textAfter) {
- return state.lastType == "operator" || state.lastType == "," ||
- isOperatorChar.test(textAfter.charAt(0)) ||
- /[,.]/.test(textAfter.charAt(0));
- }
-
- // Interface
-
- return {
- startState: function(basecolumn) {
- var state = {
- tokenize: tokenBase,
- lastType: "sof",
- cc: [],
- lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
- localVars: parserConfig.localVars,
- context: parserConfig.localVars && {vars: parserConfig.localVars},
- indented: basecolumn || 0
- };
- if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
- state.globalVars = parserConfig.globalVars;
- return state;
- },
-
- token: function(stream, state) {
- if (stream.sol()) {
- if (!state.lexical.hasOwnProperty("align"))
- state.lexical.align = false;
- state.indented = stream.indentation();
- findFatArrow(stream, state);
- }
- if (state.tokenize != tokenComment && stream.eatSpace()) return null;
- var style = state.tokenize(stream, state);
- if (type == "comment") return style;
- state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
- return parseJS(state, style, type, content, stream);
- },
-
- indent: function(state, textAfter) {
- if (state.tokenize == tokenComment) return CodeMirror.Pass;
- if (state.tokenize != tokenBase) return 0;
- var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
- // Kludge to prevent 'maybelse' from blocking lexical scope pops
- if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
- var c = state.cc[i];
- if (c == poplex) lexical = lexical.prev;
- else if (c != maybeelse) break;
- }
- while ((lexical.type == "stat" || lexical.type == "form") &&
- (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
- (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
- !/^[,\.=+\-*:?[\(]/.test(textAfter))))
- lexical = lexical.prev;
- if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
- lexical = lexical.prev;
- var type = lexical.type, closing = firstChar == type;
-
- if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
- else if (type == "form" && firstChar == "{") return lexical.indented;
- else if (type == "form") return lexical.indented + indentUnit;
- else if (type == "stat")
- return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
- else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
- return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
- else if (lexical.align) return lexical.column + (closing ? 0 : 1);
- else return lexical.indented + (closing ? 0 : indentUnit);
- },
-
- electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
- blockCommentStart: jsonMode ? null : "/*",
- blockCommentEnd: jsonMode ? null : "*/",
- lineComment: jsonMode ? null : "//",
- fold: "brace",
- closeBrackets: "()[]{}''\"\"``",
-
- helperType: jsonMode ? "json" : "javascript",
- jsonldMode: jsonldMode,
- jsonMode: jsonMode,
-
- expressionAllowed: expressionAllowed,
- skipExpression: function(state) {
- var top = state.cc[state.cc.length - 1]
- if (top == expression || top == expressionNoComma) state.cc.pop()
- }
- };
- });
-
- CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
-
- CodeMirror.defineMIME("text/javascript", "javascript");
- CodeMirror.defineMIME("text/ecmascript", "javascript");
- CodeMirror.defineMIME("application/javascript", "javascript");
- CodeMirror.defineMIME("application/x-javascript", "javascript");
- CodeMirror.defineMIME("application/ecmascript", "javascript");
- CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
- CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
- CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
- CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
- CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
-
- });
-
-
-/***/ }),
-/* 323 */
-/***/ (function(module, exports, __webpack_require__) {
-
- "use strict";
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
-
- var _react = __webpack_require__(298);
-
- var _react2 = _interopRequireDefault(_react);
-
- var _propTypes = __webpack_require__(299);
-
- var _propTypes2 = _interopRequireDefault(_propTypes);
-
- var _reactDom = __webpack_require__(310);
-
- var _server = __webpack_require__(324);
-
- var _server2 = _interopRequireDefault(_server);
-
- var _babelStandalone = __webpack_require__(489);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
- function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
-
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
-
- var Preview = function (_Component) {
- _inherits(Preview, _Component);
-
- function Preview() {
- var _ref;
-
- var _temp, _this, _ret;
-
- _classCallCheck(this, Preview);
-
- for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Preview.__proto__ || Object.getPrototypeOf(Preview)).call.apply(_ref, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret);
- }
-
- _createClass(Preview, [{
- key: "render",
- value: function render() {
- var error = this.state.error;
-
- return _react2.default.createElement(
- "div",
- null,
- error !== null ? _react2.default.createElement(
- "div",
- { className: "playgroundError" },
- error
- ) : null,
- _react2.default.createElement("div", { ref: "mount", className: "previewArea" })
- );
- }
- }]);
-
- return Preview;
- }(_react.Component);
-
- Preview.defaultProps = {
- previewComponent: "div"
- };
- Preview.propTypes = {
- code: _propTypes2.default.string.isRequired,
- scope: _propTypes2.default.object.isRequired,
- previewComponent: _propTypes2.default.node,
- noRender: _propTypes2.default.bool,
- context: _propTypes2.default.object
- };
-
- var _initialiseProps = function _initialiseProps() {
- var _this2 = this;
-
- this.state = {
- error: null
- };
-
- this._compileCode = function () {
- var _props = _this2.props,
- code = _props.code,
- context = _props.context,
- noRender = _props.noRender,
- scope = _props.scope;
-
- var generateContextTypes = function generateContextTypes(c) {
- return "{ " + Object.keys(c).map(function (val) {
- return val + ": React.PropTypes.any.isRequired";
- }).join(", ") + " }";
- };
-
- if (noRender) {
- return (0, _babelStandalone.transform)("\n ((" + Object.keys(scope).join(", ") + ", mountNode) => {\n class Comp extends React.Component {\n\n getChildContext() {\n return " + JSON.stringify(context) + ";\n }\n\n render() {\n return (\n " + code + "\n );\n }\n }\n\n Comp.childContextTypes = " + generateContextTypes(context) + ";\n\n return Comp;\n });\n ", { presets: ["es2015", "react", "stage-1"] }).code;
- } else {
- return (0, _babelStandalone.transform)("\n ((" + Object.keys(scope).join(",") + ", mountNode) => {\n " + code + "\n });\n ", { presets: ["es2015", "react", "stage-1"] }).code;
- }
- };
-
- this._setTimeout = function () {
- for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
-
- clearTimeout(_this2.timeoutID); //eslint-disable-line no-undef
- _this2.timeoutID = setTimeout.apply(null, args); //eslint-disable-line no-undef
- };
-
- this._executeCode = function () {
- var mountNode = _this2.refs.mount;
- var _props2 = _this2.props,
- scope = _props2.scope,
- noRender = _props2.noRender,
- previewComponent = _props2.previewComponent;
-
- var tempScope = [];
-
- try {
- Object.keys(scope).forEach(function (s) {
- return tempScope.push(scope[s]);
- });
- tempScope.push(mountNode);
- var compiledCode = _this2._compileCode();
- if (noRender) {
- /* eslint-disable no-eval, max-len */
- var Comp = _react2.default.createElement(eval(compiledCode).apply(null, tempScope));
- _server2.default.renderToString(_react2.default.createElement(previewComponent, {}, Comp));
- (0, _reactDom.render)(_react2.default.createElement(previewComponent, {}, Comp), mountNode);
- } else {
- eval(compiledCode).apply(null, tempScope);
- }
- /* eslint-enable no-eval, max-len */
-
- _this2.setState({ error: null });
- } catch (err) {
- _this2._setTimeout(function () {
- _this2.setState({ error: err.toString() });
- }, 500);
- }
- };
-
- this.componentDidMount = function () {
- _this2._executeCode();
- };
-
- this.componentDidUpdate = function (prevProps) {
- clearTimeout(_this2.timeoutID); //eslint-disable-line
- if (_this2.props.code !== prevProps.code) {
- _this2._executeCode();
- }
- };
- };
-
- exports.default = Preview;
-
-/***/ }),
-/* 324 */
-/***/ (function(module, exports, __webpack_require__) {
-
- 'use strict';
-
- module.exports = __webpack_require__(325);
-
-
-/***/ }),
-/* 325 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ReactDefaultInjection = __webpack_require__(326);
- var ReactServerRendering = __webpack_require__(483);
- var ReactVersion = __webpack_require__(488);
-
- ReactDefaultInjection.inject();
-
- var ReactDOMServer = {
- renderToString: ReactServerRendering.renderToString,
- renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
- version: ReactVersion
- };
-
- module.exports = ReactDOMServer;
-
-/***/ }),
-/* 326 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ARIADOMPropertyConfig = __webpack_require__(327);
- var BeforeInputEventPlugin = __webpack_require__(328);
- var ChangeEventPlugin = __webpack_require__(344);
- var DefaultEventPluginOrder = __webpack_require__(367);
- var EnterLeaveEventPlugin = __webpack_require__(368);
- var HTMLDOMPropertyConfig = __webpack_require__(373);
- var ReactComponentBrowserEnvironment = __webpack_require__(374);
- var ReactDOMComponent = __webpack_require__(387);
- var ReactDOMComponentTree = __webpack_require__(345);
- var ReactDOMEmptyComponent = __webpack_require__(454);
- var ReactDOMTreeTraversal = __webpack_require__(455);
- var ReactDOMTextComponent = __webpack_require__(456);
- var ReactDefaultBatchingStrategy = __webpack_require__(457);
- var ReactEventListener = __webpack_require__(458);
- var ReactInjection = __webpack_require__(461);
- var ReactReconcileTransaction = __webpack_require__(462);
- var SVGDOMPropertyConfig = __webpack_require__(470);
- var SelectEventPlugin = __webpack_require__(471);
- var SimpleEventPlugin = __webpack_require__(472);
-
- var alreadyInjected = false;
-
- function inject() {
- if (alreadyInjected) {
- // TODO: This is currently true because these injections are shared between
- // the client and the server package. They should be built independently
- // and not share any injection state. Then this problem will be solved.
- return;
- }
- alreadyInjected = true;
-
- ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
-
- /**
- * Inject modules for resolving DOM hierarchy and plugin ordering.
- */
- ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
- ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree);
- ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal);
-
- /**
- * Some important event plugins included by default (without having to require
- * them).
- */
- ReactInjection.EventPluginHub.injectEventPluginsByName({
- SimpleEventPlugin: SimpleEventPlugin,
- EnterLeaveEventPlugin: EnterLeaveEventPlugin,
- ChangeEventPlugin: ChangeEventPlugin,
- SelectEventPlugin: SelectEventPlugin,
- BeforeInputEventPlugin: BeforeInputEventPlugin
- });
-
- ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent);
-
- ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent);
-
- ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig);
- ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
- ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
-
- ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
- return new ReactDOMEmptyComponent(instantiate);
- });
-
- ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
- ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
-
- ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
- }
-
- module.exports = {
- inject: inject
- };
-
-/***/ }),
-/* 327 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ARIADOMPropertyConfig = {
- Properties: {
- // Global States and Properties
- 'aria-current': 0, // state
- 'aria-details': 0,
- 'aria-disabled': 0, // state
- 'aria-hidden': 0, // state
- 'aria-invalid': 0, // state
- 'aria-keyshortcuts': 0,
- 'aria-label': 0,
- 'aria-roledescription': 0,
- // Widget Attributes
- 'aria-autocomplete': 0,
- 'aria-checked': 0,
- 'aria-expanded': 0,
- 'aria-haspopup': 0,
- 'aria-level': 0,
- 'aria-modal': 0,
- 'aria-multiline': 0,
- 'aria-multiselectable': 0,
- 'aria-orientation': 0,
- 'aria-placeholder': 0,
- 'aria-pressed': 0,
- 'aria-readonly': 0,
- 'aria-required': 0,
- 'aria-selected': 0,
- 'aria-sort': 0,
- 'aria-valuemax': 0,
- 'aria-valuemin': 0,
- 'aria-valuenow': 0,
- 'aria-valuetext': 0,
- // Live Region Attributes
- 'aria-atomic': 0,
- 'aria-busy': 0,
- 'aria-live': 0,
- 'aria-relevant': 0,
- // Drag-and-Drop Attributes
- 'aria-dropeffect': 0,
- 'aria-grabbed': 0,
- // Relationship Attributes
- 'aria-activedescendant': 0,
- 'aria-colcount': 0,
- 'aria-colindex': 0,
- 'aria-colspan': 0,
- 'aria-controls': 0,
- 'aria-describedby': 0,
- 'aria-errormessage': 0,
- 'aria-flowto': 0,
- 'aria-labelledby': 0,
- 'aria-owns': 0,
- 'aria-posinset': 0,
- 'aria-rowcount': 0,
- 'aria-rowindex': 0,
- 'aria-rowspan': 0,
- 'aria-setsize': 0
- },
- DOMAttributeNames: {},
- DOMPropertyNames: {}
- };
-
- module.exports = ARIADOMPropertyConfig;
-
-/***/ }),
-/* 328 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var EventPropagators = __webpack_require__(329);
- var ExecutionEnvironment = __webpack_require__(337);
- var FallbackCompositionState = __webpack_require__(338);
- var SyntheticCompositionEvent = __webpack_require__(341);
- var SyntheticInputEvent = __webpack_require__(343);
-
- var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
- var START_KEYCODE = 229;
-
- var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
-
- var documentMode = null;
- if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
- documentMode = document.documentMode;
- }
-
- // Webkit offers a very useful `textInput` event that can be used to
- // directly represent `beforeInput`. The IE `textinput` event is not as
- // useful, so we don't use it.
- var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
-
- // In IE9+, we have access to composition events, but the data supplied
- // by the native compositionend event may be incorrect. Japanese ideographic
- // spaces, for instance (\u3000) are not recorded correctly.
- var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
-
- /**
- * Opera <= 12 includes TextEvent in window, but does not fire
- * text input events. Rely on keypress instead.
- */
- function isPresto() {
- var opera = window.opera;
- return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
- }
-
- var SPACEBAR_CODE = 32;
- var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
-
- // Events and their corresponding property names.
- var eventTypes = {
- beforeInput: {
- phasedRegistrationNames: {
- bubbled: 'onBeforeInput',
- captured: 'onBeforeInputCapture'
- },
- dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste']
- },
- compositionEnd: {
- phasedRegistrationNames: {
- bubbled: 'onCompositionEnd',
- captured: 'onCompositionEndCapture'
- },
- dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
- },
- compositionStart: {
- phasedRegistrationNames: {
- bubbled: 'onCompositionStart',
- captured: 'onCompositionStartCapture'
- },
- dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
- },
- compositionUpdate: {
- phasedRegistrationNames: {
- bubbled: 'onCompositionUpdate',
- captured: 'onCompositionUpdateCapture'
- },
- dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown']
- }
- };
-
- // Track whether we've ever handled a keypress on the space key.
- var hasSpaceKeypress = false;
-
- /**
- * Return whether a native keypress event is assumed to be a command.
- * This is required because Firefox fires `keypress` events for key commands
- * (cut, copy, select-all, etc.) even though no character is inserted.
- */
- function isKeypressCommand(nativeEvent) {
- return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
- // ctrlKey && altKey is equivalent to AltGr, and is not a command.
- !(nativeEvent.ctrlKey && nativeEvent.altKey);
- }
-
- /**
- * Translate native top level events into event types.
- *
- * @param {string} topLevelType
- * @return {object}
- */
- function getCompositionEventType(topLevelType) {
- switch (topLevelType) {
- case 'topCompositionStart':
- return eventTypes.compositionStart;
- case 'topCompositionEnd':
- return eventTypes.compositionEnd;
- case 'topCompositionUpdate':
- return eventTypes.compositionUpdate;
- }
- }
-
- /**
- * Does our fallback best-guess model think this event signifies that
- * composition has begun?
- *
- * @param {string} topLevelType
- * @param {object} nativeEvent
- * @return {boolean}
- */
- function isFallbackCompositionStart(topLevelType, nativeEvent) {
- return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE;
- }
-
- /**
- * Does our fallback mode think that this event is the end of composition?
- *
- * @param {string} topLevelType
- * @param {object} nativeEvent
- * @return {boolean}
- */
- function isFallbackCompositionEnd(topLevelType, nativeEvent) {
- switch (topLevelType) {
- case 'topKeyUp':
- // Command keys insert or clear IME input.
- return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
- case 'topKeyDown':
- // Expect IME keyCode on each keydown. If we get any other
- // code we must have exited earlier.
- return nativeEvent.keyCode !== START_KEYCODE;
- case 'topKeyPress':
- case 'topMouseDown':
- case 'topBlur':
- // Events are not possible without cancelling IME.
- return true;
- default:
- return false;
- }
- }
-
- /**
- * Google Input Tools provides composition data via a CustomEvent,
- * with the `data` property populated in the `detail` object. If this
- * is available on the event object, use it. If not, this is a plain
- * composition event and we have nothing special to extract.
- *
- * @param {object} nativeEvent
- * @return {?string}
- */
- function getDataFromCustomEvent(nativeEvent) {
- var detail = nativeEvent.detail;
- if (typeof detail === 'object' && 'data' in detail) {
- return detail.data;
- }
- return null;
- }
-
- // Track the current IME composition fallback object, if any.
- var currentComposition = null;
-
- /**
- * @return {?object} A SyntheticCompositionEvent.
- */
- function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
- var eventType;
- var fallbackData;
-
- if (canUseCompositionEvent) {
- eventType = getCompositionEventType(topLevelType);
- } else if (!currentComposition) {
- if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
- eventType = eventTypes.compositionStart;
- }
- } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
- eventType = eventTypes.compositionEnd;
- }
-
- if (!eventType) {
- return null;
- }
-
- if (useFallbackCompositionData) {
- // The current composition is stored statically and must not be
- // overwritten while composition continues.
- if (!currentComposition && eventType === eventTypes.compositionStart) {
- currentComposition = FallbackCompositionState.getPooled(nativeEventTarget);
- } else if (eventType === eventTypes.compositionEnd) {
- if (currentComposition) {
- fallbackData = currentComposition.getData();
- }
- }
- }
-
- var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
-
- if (fallbackData) {
- // Inject data generated from fallback path into the synthetic event.
- // This matches the property of native CompositionEventInterface.
- event.data = fallbackData;
- } else {
- var customData = getDataFromCustomEvent(nativeEvent);
- if (customData !== null) {
- event.data = customData;
- }
- }
-
- EventPropagators.accumulateTwoPhaseDispatches(event);
- return event;
- }
-
- /**
- * @param {string} topLevelType Record from `EventConstants`.
- * @param {object} nativeEvent Native browser event.
- * @return {?string} The string corresponding to this `beforeInput` event.
- */
- function getNativeBeforeInputChars(topLevelType, nativeEvent) {
- switch (topLevelType) {
- case 'topCompositionEnd':
- return getDataFromCustomEvent(nativeEvent);
- case 'topKeyPress':
- /**
- * If native `textInput` events are available, our goal is to make
- * use of them. However, there is a special case: the spacebar key.
- * In Webkit, preventing default on a spacebar `textInput` event
- * cancels character insertion, but it *also* causes the browser
- * to fall back to its default spacebar behavior of scrolling the
- * page.
- *
- * Tracking at:
- * https://code.google.com/p/chromium/issues/detail?id=355103
- *
- * To avoid this issue, use the keypress event as if no `textInput`
- * event is available.
- */
- var which = nativeEvent.which;
- if (which !== SPACEBAR_CODE) {
- return null;
- }
-
- hasSpaceKeypress = true;
- return SPACEBAR_CHAR;
-
- case 'topTextInput':
- // Record the characters to be added to the DOM.
- var chars = nativeEvent.data;
-
- // If it's a spacebar character, assume that we have already handled
- // it at the keypress level and bail immediately. Android Chrome
- // doesn't give us keycodes, so we need to blacklist it.
- if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
- return null;
- }
-
- return chars;
-
- default:
- // For other native event types, do nothing.
- return null;
- }
- }
-
- /**
- * For browsers that do not provide the `textInput` event, extract the
- * appropriate string to use for SyntheticInputEvent.
- *
- * @param {string} topLevelType Record from `EventConstants`.
- * @param {object} nativeEvent Native browser event.
- * @return {?string} The fallback string for this `beforeInput` event.
- */
- function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
- // If we are currently composing (IME) and using a fallback to do so,
- // try to extract the composed characters from the fallback object.
- // If composition event is available, we extract a string only at
- // compositionevent, otherwise extract it at fallback events.
- if (currentComposition) {
- if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
- var chars = currentComposition.getData();
- FallbackCompositionState.release(currentComposition);
- currentComposition = null;
- return chars;
- }
- return null;
- }
-
- switch (topLevelType) {
- case 'topPaste':
- // If a paste event occurs after a keypress, throw out the input
- // chars. Paste events should not lead to BeforeInput events.
- return null;
- case 'topKeyPress':
- /**
- * As of v27, Firefox may fire keypress events even when no character
- * will be inserted. A few possibilities:
- *
- * - `which` is `0`. Arrow keys, Esc key, etc.
- *
- * - `which` is the pressed key code, but no char is available.
- * Ex: 'AltGr + d` in Polish. There is no modified character for
- * this key combination and no character is inserted into the
- * document, but FF fires the keypress for char code `100` anyway.
- * No `input` event will occur.
- *
- * - `which` is the pressed key code, but a command combination is
- * being used. Ex: `Cmd+C`. No character is inserted, and no
- * `input` event will occur.
- */
- if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
- return String.fromCharCode(nativeEvent.which);
- }
- return null;
- case 'topCompositionEnd':
- return useFallbackCompositionData ? null : nativeEvent.data;
- default:
- return null;
- }
- }
-
- /**
- * Extract a SyntheticInputEvent for `beforeInput`, based on either native
- * `textInput` or fallback behavior.
- *
- * @return {?object} A SyntheticInputEvent.
- */
- function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
- var chars;
-
- if (canUseTextInputEvent) {
- chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
- } else {
- chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
- }
-
- // If no characters are being inserted, no BeforeInput event should
- // be fired.
- if (!chars) {
- return null;
- }
-
- var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
-
- event.data = chars;
- EventPropagators.accumulateTwoPhaseDispatches(event);
- return event;
- }
-
- /**
- * Create an `onBeforeInput` event to match
- * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
- *
- * This event plugin is based on the native `textInput` event
- * available in Chrome, Safari, Opera, and IE. This event fires after
- * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
- *
- * `beforeInput` is spec'd but not implemented in any browsers, and
- * the `input` event does not provide any useful information about what has
- * actually been added, contrary to the spec. Thus, `textInput` is the best
- * available event to identify the characters that have actually been inserted
- * into the target node.
- *
- * This plugin is also responsible for emitting `composition` events, thus
- * allowing us to share composition fallback code for both `beforeInput` and
- * `composition` event types.
- */
- var BeforeInputEventPlugin = {
-
- eventTypes: eventTypes,
-
- extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
- return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)];
- }
- };
-
- module.exports = BeforeInputEventPlugin;
-
-/***/ }),
-/* 329 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var EventPluginHub = __webpack_require__(330);
- var EventPluginUtils = __webpack_require__(333);
-
- var accumulateInto = __webpack_require__(335);
- var forEachAccumulated = __webpack_require__(336);
- var warning = __webpack_require__(304);
-
- var getListener = EventPluginHub.getListener;
-
- /**
- * Some event types have a notion of different registration names for different
- * "phases" of propagation. This finds listeners by a given phase.
- */
- function listenerAtPhase(inst, event, propagationPhase) {
- var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
- return getListener(inst, registrationName);
- }
-
- /**
- * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
- * here, allows us to not have to bind or create functions for each event.
- * Mutating the event's members allows us to not have to create a wrapping
- * "dispatch" object that pairs the event with the listener.
- */
- function accumulateDirectionalDispatches(inst, phase, event) {
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0;
- }
- var listener = listenerAtPhase(inst, event, phase);
- if (listener) {
- event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
- event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
- }
- }
-
- /**
- * Collect dispatches (must be entirely collected before dispatching - see unit
- * tests). Lazily allocate the array to conserve memory. We must loop through
- * each event and perform the traversal for each one. We cannot perform a
- * single traversal for the entire collection of events because each event may
- * have a different target.
- */
- function accumulateTwoPhaseDispatchesSingle(event) {
- if (event && event.dispatchConfig.phasedRegistrationNames) {
- EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
- }
- }
-
- /**
- * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
- */
- function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
- if (event && event.dispatchConfig.phasedRegistrationNames) {
- var targetInst = event._targetInst;
- var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
- EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
- }
- }
-
- /**
- * Accumulates without regard to direction, does not look for phased
- * registration names. Same as `accumulateDirectDispatchesSingle` but without
- * requiring that the `dispatchMarker` be the same as the dispatched ID.
- */
- function accumulateDispatches(inst, ignoredDirection, event) {
- if (event && event.dispatchConfig.registrationName) {
- var registrationName = event.dispatchConfig.registrationName;
- var listener = getListener(inst, registrationName);
- if (listener) {
- event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
- event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
- }
- }
- }
-
- /**
- * Accumulates dispatches on an `SyntheticEvent`, but only for the
- * `dispatchMarker`.
- * @param {SyntheticEvent} event
- */
- function accumulateDirectDispatchesSingle(event) {
- if (event && event.dispatchConfig.registrationName) {
- accumulateDispatches(event._targetInst, null, event);
- }
- }
-
- function accumulateTwoPhaseDispatches(events) {
- forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
- }
-
- function accumulateTwoPhaseDispatchesSkipTarget(events) {
- forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
- }
-
- function accumulateEnterLeaveDispatches(leave, enter, from, to) {
- EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
- }
-
- function accumulateDirectDispatches(events) {
- forEachAccumulated(events, accumulateDirectDispatchesSingle);
- }
-
- /**
- * A small set of propagation patterns, each of which will accept a small amount
- * of information, and generate a set of "dispatch ready event objects" - which
- * are sets of events that have already been annotated with a set of dispatched
- * listener functions/ids. The API is designed this way to discourage these
- * propagation strategies from actually executing the dispatches, since we
- * always want to collect the entire set of dispatches before executing event a
- * single one.
- *
- * @constructor EventPropagators
- */
- var EventPropagators = {
- accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
- accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
- accumulateDirectDispatches: accumulateDirectDispatches,
- accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
- };
-
- module.exports = EventPropagators;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 330 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var EventPluginRegistry = __webpack_require__(332);
- var EventPluginUtils = __webpack_require__(333);
- var ReactErrorUtils = __webpack_require__(334);
-
- var accumulateInto = __webpack_require__(335);
- var forEachAccumulated = __webpack_require__(336);
- var invariant = __webpack_require__(303);
-
- /**
- * Internal store for event listeners
- */
- var listenerBank = {};
-
- /**
- * Internal queue of events that have accumulated their dispatches and are
- * waiting to have their dispatches executed.
- */
- var eventQueue = null;
-
- /**
- * Dispatches an event and releases it back into the pool, unless persistent.
- *
- * @param {?object} event Synthetic event to be dispatched.
- * @param {boolean} simulated If the event is simulated (changes exn behavior)
- * @private
- */
- var executeDispatchesAndRelease = function (event, simulated) {
- if (event) {
- EventPluginUtils.executeDispatchesInOrder(event, simulated);
-
- if (!event.isPersistent()) {
- event.constructor.release(event);
- }
- }
- };
- var executeDispatchesAndReleaseSimulated = function (e) {
- return executeDispatchesAndRelease(e, true);
- };
- var executeDispatchesAndReleaseTopLevel = function (e) {
- return executeDispatchesAndRelease(e, false);
- };
-
- var getDictionaryKey = function (inst) {
- // Prevents V8 performance issue:
- // https://github.com/facebook/react/pull/7232
- return '.' + inst._rootNodeID;
- };
-
- function isInteractive(tag) {
- return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
- }
-
- function shouldPreventMouseEvent(name, type, props) {
- switch (name) {
- case 'onClick':
- case 'onClickCapture':
- case 'onDoubleClick':
- case 'onDoubleClickCapture':
- case 'onMouseDown':
- case 'onMouseDownCapture':
- case 'onMouseMove':
- case 'onMouseMoveCapture':
- case 'onMouseUp':
- case 'onMouseUpCapture':
- return !!(props.disabled && isInteractive(type));
- default:
- return false;
- }
- }
-
- /**
- * This is a unified interface for event plugins to be installed and configured.
- *
- * Event plugins can implement the following properties:
- *
- * `extractEvents` {function(string, DOMEventTarget, string, object): *}
- * Required. When a top-level event is fired, this method is expected to
- * extract synthetic events that will in turn be queued and dispatched.
- *
- * `eventTypes` {object}
- * Optional, plugins that fire events must publish a mapping of registration
- * names that are used to register listeners. Values of this mapping must
- * be objects that contain `registrationName` or `phasedRegistrationNames`.
- *
- * `executeDispatch` {function(object, function, string)}
- * Optional, allows plugins to override how an event gets dispatched. By
- * default, the listener is simply invoked.
- *
- * Each plugin that is injected into `EventsPluginHub` is immediately operable.
- *
- * @public
- */
- var EventPluginHub = {
-
- /**
- * Methods for injecting dependencies.
- */
- injection: {
-
- /**
- * @param {array} InjectedEventPluginOrder
- * @public
- */
- injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
-
- /**
- * @param {object} injectedNamesToPlugins Map from names to plugin modules.
- */
- injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
-
- },
-
- /**
- * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent.
- *
- * @param {object} inst The instance, which is the source of events.
- * @param {string} registrationName Name of listener (e.g. `onClick`).
- * @param {function} listener The callback to store.
- */
- putListener: function (inst, registrationName, listener) {
- !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0;
-
- var key = getDictionaryKey(inst);
- var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
- bankForRegistrationName[key] = listener;
-
- var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
- if (PluginModule && PluginModule.didPutListener) {
- PluginModule.didPutListener(inst, registrationName, listener);
- }
- },
-
- /**
- * @param {object} inst The instance, which is the source of events.
- * @param {string} registrationName Name of listener (e.g. `onClick`).
- * @return {?function} The stored callback.
- */
- getListener: function (inst, registrationName) {
- // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
- // live here; needs to be moved to a better place soon
- var bankForRegistrationName = listenerBank[registrationName];
- if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) {
- return null;
- }
- var key = getDictionaryKey(inst);
- return bankForRegistrationName && bankForRegistrationName[key];
- },
-
- /**
- * Deletes a listener from the registration bank.
- *
- * @param {object} inst The instance, which is the source of events.
- * @param {string} registrationName Name of listener (e.g. `onClick`).
- */
- deleteListener: function (inst, registrationName) {
- var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
- if (PluginModule && PluginModule.willDeleteListener) {
- PluginModule.willDeleteListener(inst, registrationName);
- }
-
- var bankForRegistrationName = listenerBank[registrationName];
- // TODO: This should never be null -- when is it?
- if (bankForRegistrationName) {
- var key = getDictionaryKey(inst);
- delete bankForRegistrationName[key];
- }
- },
-
- /**
- * Deletes all listeners for the DOM element with the supplied ID.
- *
- * @param {object} inst The instance, which is the source of events.
- */
- deleteAllListeners: function (inst) {
- var key = getDictionaryKey(inst);
- for (var registrationName in listenerBank) {
- if (!listenerBank.hasOwnProperty(registrationName)) {
- continue;
- }
-
- if (!listenerBank[registrationName][key]) {
- continue;
- }
-
- var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
- if (PluginModule && PluginModule.willDeleteListener) {
- PluginModule.willDeleteListener(inst, registrationName);
- }
-
- delete listenerBank[registrationName][key];
- }
- },
-
- /**
- * Allows registered plugins an opportunity to extract events from top-level
- * native browser events.
- *
- * @return {*} An accumulation of synthetic events.
- * @internal
- */
- extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
- var events;
- var plugins = EventPluginRegistry.plugins;
- for (var i = 0; i < plugins.length; i++) {
- // Not every plugin in the ordering may be loaded at runtime.
- var possiblePlugin = plugins[i];
- if (possiblePlugin) {
- var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
- if (extractedEvents) {
- events = accumulateInto(events, extractedEvents);
- }
- }
- }
- return events;
- },
-
- /**
- * Enqueues a synthetic event that should be dispatched when
- * `processEventQueue` is invoked.
- *
- * @param {*} events An accumulation of synthetic events.
- * @internal
- */
- enqueueEvents: function (events) {
- if (events) {
- eventQueue = accumulateInto(eventQueue, events);
- }
- },
-
- /**
- * Dispatches all synthetic events on the event queue.
- *
- * @internal
- */
- processEventQueue: function (simulated) {
- // Set `eventQueue` to null before processing it so that we can tell if more
- // events get enqueued while processing.
- var processingEventQueue = eventQueue;
- eventQueue = null;
- if (simulated) {
- forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
- } else {
- forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
- }
- !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0;
- // This would be a good time to rethrow if any of the event handlers threw.
- ReactErrorUtils.rethrowCaughtError();
- },
-
- /**
- * These are needed for tests only. Do not use!
- */
- __purge: function () {
- listenerBank = {};
- },
-
- __getListenerBank: function () {
- return listenerBank;
- }
-
- };
-
- module.exports = EventPluginHub;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 331 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
- 'use strict';
-
- /**
- * WARNING: DO NOT manually require this module.
- * This is a replacement for `invariant(...)` used by the error code system
- * and will _only_ be required by the corresponding babel pass.
- * It always throws.
- */
-
- function reactProdInvariant(code) {
- var argCount = arguments.length - 1;
-
- var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
-
- for (var argIdx = 0; argIdx < argCount; argIdx++) {
- message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
- }
-
- message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
-
- var error = new Error(message);
- error.name = 'Invariant Violation';
- error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
-
- throw error;
- }
-
- module.exports = reactProdInvariant;
-
-/***/ }),
-/* 332 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- /**
- * Injectable ordering of event plugins.
- */
- var eventPluginOrder = null;
-
- /**
- * Injectable mapping from names to event plugin modules.
- */
- var namesToPlugins = {};
-
- /**
- * Recomputes the plugin list using the injected plugins and plugin ordering.
- *
- * @private
- */
- function recomputePluginOrdering() {
- if (!eventPluginOrder) {
- // Wait until an `eventPluginOrder` is injected.
- return;
- }
- for (var pluginName in namesToPlugins) {
- var pluginModule = namesToPlugins[pluginName];
- var pluginIndex = eventPluginOrder.indexOf(pluginName);
- !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0;
- if (EventPluginRegistry.plugins[pluginIndex]) {
- continue;
- }
- !pluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0;
- EventPluginRegistry.plugins[pluginIndex] = pluginModule;
- var publishedEvents = pluginModule.eventTypes;
- for (var eventName in publishedEvents) {
- !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0;
- }
- }
- }
-
- /**
- * Publishes an event so that it can be dispatched by the supplied plugin.
- *
- * @param {object} dispatchConfig Dispatch configuration for the event.
- * @param {object} PluginModule Plugin publishing the event.
- * @return {boolean} True if the event was successfully published.
- * @private
- */
- function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
- !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0;
- EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
-
- var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
- if (phasedRegistrationNames) {
- for (var phaseName in phasedRegistrationNames) {
- if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
- var phasedRegistrationName = phasedRegistrationNames[phaseName];
- publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
- }
- }
- return true;
- } else if (dispatchConfig.registrationName) {
- publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
- return true;
- }
- return false;
- }
-
- /**
- * Publishes a registration name that is used to identify dispatched events and
- * can be used with `EventPluginHub.putListener` to register listeners.
- *
- * @param {string} registrationName Registration name to add.
- * @param {object} PluginModule Plugin publishing the event.
- * @private
- */
- function publishRegistrationName(registrationName, pluginModule, eventName) {
- !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0;
- EventPluginRegistry.registrationNameModules[registrationName] = pluginModule;
- EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
-
- if (process.env.NODE_ENV !== 'production') {
- var lowerCasedName = registrationName.toLowerCase();
- EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
-
- if (registrationName === 'onDoubleClick') {
- EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName;
- }
- }
- }
-
- /**
- * Registers plugins so that they can extract and dispatch events.
- *
- * @see {EventPluginHub}
- */
- var EventPluginRegistry = {
-
- /**
- * Ordered list of injected plugins.
- */
- plugins: [],
-
- /**
- * Mapping from event name to dispatch config
- */
- eventNameDispatchConfigs: {},
-
- /**
- * Mapping from registration name to plugin module
- */
- registrationNameModules: {},
-
- /**
- * Mapping from registration name to event name
- */
- registrationNameDependencies: {},
-
- /**
- * Mapping from lowercase registration names to the properly cased version,
- * used to warn in the case of missing event handlers. Available
- * only in __DEV__.
- * @type {Object}
- */
- possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null,
- // Trust the developer to only use possibleRegistrationNames in __DEV__
-
- /**
- * Injects an ordering of plugins (by plugin name). This allows the ordering
- * to be decoupled from injection of the actual plugins so that ordering is
- * always deterministic regardless of packaging, on-the-fly injection, etc.
- *
- * @param {array} InjectedEventPluginOrder
- * @internal
- * @see {EventPluginHub.injection.injectEventPluginOrder}
- */
- injectEventPluginOrder: function (injectedEventPluginOrder) {
- !!eventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0;
- // Clone the ordering so it cannot be dynamically mutated.
- eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
- recomputePluginOrdering();
- },
-
- /**
- * Injects plugins to be used by `EventPluginHub`. The plugin names must be
- * in the ordering injected by `injectEventPluginOrder`.
- *
- * Plugins can be injected as part of page initialization or on-the-fly.
- *
- * @param {object} injectedNamesToPlugins Map from names to plugin modules.
- * @internal
- * @see {EventPluginHub.injection.injectEventPluginsByName}
- */
- injectEventPluginsByName: function (injectedNamesToPlugins) {
- var isOrderingDirty = false;
- for (var pluginName in injectedNamesToPlugins) {
- if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
- continue;
- }
- var pluginModule = injectedNamesToPlugins[pluginName];
- if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
- !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0;
- namesToPlugins[pluginName] = pluginModule;
- isOrderingDirty = true;
- }
- }
- if (isOrderingDirty) {
- recomputePluginOrdering();
- }
- },
-
- /**
- * Looks up the plugin for the supplied event.
- *
- * @param {object} event A synthetic event.
- * @return {?object} The plugin that created the supplied event.
- * @internal
- */
- getPluginModuleForEvent: function (event) {
- var dispatchConfig = event.dispatchConfig;
- if (dispatchConfig.registrationName) {
- return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
- }
- if (dispatchConfig.phasedRegistrationNames !== undefined) {
- // pulling phasedRegistrationNames out of dispatchConfig helps Flow see
- // that it is not undefined.
- var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
-
- for (var phase in phasedRegistrationNames) {
- if (!phasedRegistrationNames.hasOwnProperty(phase)) {
- continue;
- }
- var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]];
- if (pluginModule) {
- return pluginModule;
- }
- }
- }
- return null;
- },
-
- /**
- * Exposed for unit testing.
- * @private
- */
- _resetEventPlugins: function () {
- eventPluginOrder = null;
- for (var pluginName in namesToPlugins) {
- if (namesToPlugins.hasOwnProperty(pluginName)) {
- delete namesToPlugins[pluginName];
- }
- }
- EventPluginRegistry.plugins.length = 0;
-
- var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
- for (var eventName in eventNameDispatchConfigs) {
- if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
- delete eventNameDispatchConfigs[eventName];
- }
- }
-
- var registrationNameModules = EventPluginRegistry.registrationNameModules;
- for (var registrationName in registrationNameModules) {
- if (registrationNameModules.hasOwnProperty(registrationName)) {
- delete registrationNameModules[registrationName];
- }
- }
-
- if (process.env.NODE_ENV !== 'production') {
- var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
- for (var lowerCasedName in possibleRegistrationNames) {
- if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) {
- delete possibleRegistrationNames[lowerCasedName];
- }
- }
- }
- }
-
- };
-
- module.exports = EventPluginRegistry;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 333 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var ReactErrorUtils = __webpack_require__(334);
-
- var invariant = __webpack_require__(303);
- var warning = __webpack_require__(304);
-
- /**
- * Injected dependencies:
- */
-
- /**
- * - `ComponentTree`: [required] Module that can convert between React instances
- * and actual node references.
- */
- var ComponentTree;
- var TreeTraversal;
- var injection = {
- injectComponentTree: function (Injected) {
- ComponentTree = Injected;
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
- }
- },
- injectTreeTraversal: function (Injected) {
- TreeTraversal = Injected;
- if (process.env.NODE_ENV !== 'production') {
- process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0;
- }
- }
- };
-
- function isEndish(topLevelType) {
- return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel';
- }
-
- function isMoveish(topLevelType) {
- return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove';
- }
- function isStartish(topLevelType) {
- return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart';
- }
-
- var validateEventDispatches;
- if (process.env.NODE_ENV !== 'production') {
- validateEventDispatches = function (event) {
- var dispatchListeners = event._dispatchListeners;
- var dispatchInstances = event._dispatchInstances;
-
- var listenersIsArr = Array.isArray(dispatchListeners);
- var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
-
- var instancesIsArr = Array.isArray(dispatchInstances);
- var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
-
- process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0;
- };
- }
-
- /**
- * Dispatch the event to the listener.
- * @param {SyntheticEvent} event SyntheticEvent to handle
- * @param {boolean} simulated If the event is simulated (changes exn behavior)
- * @param {function} listener Application-level callback
- * @param {*} inst Internal component instance
- */
- function executeDispatch(event, simulated, listener, inst) {
- var type = event.type || 'unknown-event';
- event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
- if (simulated) {
- ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event);
- } else {
- ReactErrorUtils.invokeGuardedCallback(type, listener, event);
- }
- event.currentTarget = null;
- }
-
- /**
- * Standard/simple iteration through an event's collected dispatches.
- */
- function executeDispatchesInOrder(event, simulated) {
- var dispatchListeners = event._dispatchListeners;
- var dispatchInstances = event._dispatchInstances;
- if (process.env.NODE_ENV !== 'production') {
- validateEventDispatches(event);
- }
- if (Array.isArray(dispatchListeners)) {
- for (var i = 0; i < dispatchListeners.length; i++) {
- if (event.isPropagationStopped()) {
- break;
- }
- // Listeners and Instances are two parallel arrays that are always in sync.
- executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
- }
- } else if (dispatchListeners) {
- executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
- }
- event._dispatchListeners = null;
- event._dispatchInstances = null;
- }
-
- /**
- * Standard/simple iteration through an event's collected dispatches, but stops
- * at the first dispatch execution returning true, and returns that id.
- *
- * @return {?string} id of the first dispatch execution who's listener returns
- * true, or null if no listener returned true.
- */
- function executeDispatchesInOrderStopAtTrueImpl(event) {
- var dispatchListeners = event._dispatchListeners;
- var dispatchInstances = event._dispatchInstances;
- if (process.env.NODE_ENV !== 'production') {
- validateEventDispatches(event);
- }
- if (Array.isArray(dispatchListeners)) {
- for (var i = 0; i < dispatchListeners.length; i++) {
- if (event.isPropagationStopped()) {
- break;
- }
- // Listeners and Instances are two parallel arrays that are always in sync.
- if (dispatchListeners[i](event, dispatchInstances[i])) {
- return dispatchInstances[i];
- }
- }
- } else if (dispatchListeners) {
- if (dispatchListeners(event, dispatchInstances)) {
- return dispatchInstances;
- }
- }
- return null;
- }
-
- /**
- * @see executeDispatchesInOrderStopAtTrueImpl
- */
- function executeDispatchesInOrderStopAtTrue(event) {
- var ret = executeDispatchesInOrderStopAtTrueImpl(event);
- event._dispatchInstances = null;
- event._dispatchListeners = null;
- return ret;
- }
-
- /**
- * Execution of a "direct" dispatch - there must be at most one dispatch
- * accumulated on the event or it is considered an error. It doesn't really make
- * sense for an event with multiple dispatches (bubbled) to keep track of the
- * return values at each dispatch execution, but it does tend to make sense when
- * dealing with "direct" dispatches.
- *
- * @return {*} The return value of executing the single dispatch.
- */
- function executeDirectDispatch(event) {
- if (process.env.NODE_ENV !== 'production') {
- validateEventDispatches(event);
- }
- var dispatchListener = event._dispatchListeners;
- var dispatchInstance = event._dispatchInstances;
- !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0;
- event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
- var res = dispatchListener ? dispatchListener(event) : null;
- event.currentTarget = null;
- event._dispatchListeners = null;
- event._dispatchInstances = null;
- return res;
- }
-
- /**
- * @param {SyntheticEvent} event
- * @return {boolean} True iff number of dispatches accumulated is greater than 0.
- */
- function hasDispatches(event) {
- return !!event._dispatchListeners;
- }
-
- /**
- * General utilities that are useful in creating custom Event Plugins.
- */
- var EventPluginUtils = {
- isEndish: isEndish,
- isMoveish: isMoveish,
- isStartish: isStartish,
-
- executeDirectDispatch: executeDirectDispatch,
- executeDispatchesInOrder: executeDispatchesInOrder,
- executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
- hasDispatches: hasDispatches,
-
- getInstanceFromNode: function (node) {
- return ComponentTree.getInstanceFromNode(node);
- },
- getNodeFromInstance: function (node) {
- return ComponentTree.getNodeFromInstance(node);
- },
- isAncestor: function (a, b) {
- return TreeTraversal.isAncestor(a, b);
- },
- getLowestCommonAncestor: function (a, b) {
- return TreeTraversal.getLowestCommonAncestor(a, b);
- },
- getParentInstance: function (inst) {
- return TreeTraversal.getParentInstance(inst);
- },
- traverseTwoPhase: function (target, fn, arg) {
- return TreeTraversal.traverseTwoPhase(target, fn, arg);
- },
- traverseEnterLeave: function (from, to, fn, argFrom, argTo) {
- return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
- },
-
- injection: injection
- };
-
- module.exports = EventPluginUtils;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 334 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var caughtError = null;
-
- /**
- * Call a function while guarding against errors that happens within it.
- *
- * @param {String} name of the guard to use for logging or debugging
- * @param {Function} func The function to invoke
- * @param {*} a First argument
- * @param {*} b Second argument
- */
- function invokeGuardedCallback(name, func, a) {
- try {
- func(a);
- } catch (x) {
- if (caughtError === null) {
- caughtError = x;
- }
- }
- }
-
- var ReactErrorUtils = {
- invokeGuardedCallback: invokeGuardedCallback,
-
- /**
- * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
- * handler are sure to be rethrown by rethrowCaughtError.
- */
- invokeGuardedCallbackWithCatch: invokeGuardedCallback,
-
- /**
- * During execution of guarded functions we will capture the first error which
- * we will rethrow to be handled by the top level error handler.
- */
- rethrowCaughtError: function () {
- if (caughtError) {
- var error = caughtError;
- caughtError = null;
- throw error;
- }
- }
- };
-
- if (process.env.NODE_ENV !== 'production') {
- /**
- * To help development we can get better devtools integration by simulating a
- * real browser event.
- */
- if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
- var fakeNode = document.createElement('react');
- ReactErrorUtils.invokeGuardedCallback = function (name, func, a) {
- var boundFunc = func.bind(null, a);
- var evtType = 'react-' + name;
- fakeNode.addEventListener(evtType, boundFunc, false);
- var evt = document.createEvent('Event');
- evt.initEvent(evtType, false, false);
- fakeNode.dispatchEvent(evt);
- fakeNode.removeEventListener(evtType, boundFunc, false);
- };
- }
- }
-
- module.exports = ReactErrorUtils;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 335 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2014-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- /**
- * Accumulates items that must not be null or undefined into the first one. This
- * is used to conserve memory by avoiding array allocations, and thus sacrifices
- * API cleanness. Since `current` can be null before being passed in and not
- * null after this function, make sure to assign it back to `current`:
- *
- * `a = accumulateInto(a, b);`
- *
- * This API should be sparingly used. Try `accumulate` for something cleaner.
- *
- * @return {*|array<*>} An accumulation of items.
- */
-
- function accumulateInto(current, next) {
- !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0;
-
- if (current == null) {
- return next;
- }
-
- // Both are not empty. Warning: Never call x.concat(y) when you are not
- // certain that x is an Array (x could be a string with concat method).
- if (Array.isArray(current)) {
- if (Array.isArray(next)) {
- current.push.apply(current, next);
- return current;
- }
- current.push(next);
- return current;
- }
-
- if (Array.isArray(next)) {
- // A bit too dangerous to mutate `next`.
- return [current].concat(next);
- }
-
- return [current, next];
- }
-
- module.exports = accumulateInto;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 336 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- /**
- * @param {array} arr an "accumulation" of items which is either an Array or
- * a single item. Useful when paired with the `accumulate` module. This is a
- * simple utility that allows us to reason about a collection of items, but
- * handling the case when there is exactly one item (and we do not need to
- * allocate an array).
- */
-
- function forEachAccumulated(arr, cb, scope) {
- if (Array.isArray(arr)) {
- arr.forEach(cb, scope);
- } else if (arr) {
- cb.call(scope, arr);
- }
- }
-
- module.exports = forEachAccumulated;
-
-/***/ }),
-/* 337 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
-
- /**
- * Simple, lightweight module assisting with the detection and context of
- * Worker. Helps avoid circular dependencies and allows code to reason about
- * whether or not they are in a Worker, even if they never include the main
- * `ReactWorker` dependency.
- */
- var ExecutionEnvironment = {
-
- canUseDOM: canUseDOM,
-
- canUseWorkers: typeof Worker !== 'undefined',
-
- canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
-
- canUseViewport: canUseDOM && !!window.screen,
-
- isInWorker: !canUseDOM // For now, this is true - might change in the future.
-
- };
-
- module.exports = ExecutionEnvironment;
-
-/***/ }),
-/* 338 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _assign = __webpack_require__(317);
-
- var PooledClass = __webpack_require__(339);
-
- var getTextContentAccessor = __webpack_require__(340);
-
- /**
- * This helper class stores information about text content of a target node,
- * allowing comparison of content before and after a given event.
- *
- * Identify the node where selection currently begins, then observe
- * both its text content and its current position in the DOM. Since the
- * browser may natively replace the target node during composition, we can
- * use its position to find its replacement.
- *
- * @param {DOMEventTarget} root
- */
- function FallbackCompositionState(root) {
- this._root = root;
- this._startText = this.getText();
- this._fallbackText = null;
- }
-
- _assign(FallbackCompositionState.prototype, {
- destructor: function () {
- this._root = null;
- this._startText = null;
- this._fallbackText = null;
- },
-
- /**
- * Get current text of input.
- *
- * @return {string}
- */
- getText: function () {
- if ('value' in this._root) {
- return this._root.value;
- }
- return this._root[getTextContentAccessor()];
- },
-
- /**
- * Determine the differing substring between the initially stored
- * text content and the current content.
- *
- * @return {string}
- */
- getData: function () {
- if (this._fallbackText) {
- return this._fallbackText;
- }
-
- var start;
- var startValue = this._startText;
- var startLength = startValue.length;
- var end;
- var endValue = this.getText();
- var endLength = endValue.length;
-
- for (start = 0; start < startLength; start++) {
- if (startValue[start] !== endValue[start]) {
- break;
- }
- }
-
- var minEnd = startLength - start;
- for (end = 1; end <= minEnd; end++) {
- if (startValue[startLength - end] !== endValue[endLength - end]) {
- break;
- }
- }
-
- var sliceTail = end > 1 ? 1 - end : undefined;
- this._fallbackText = endValue.slice(start, sliceTail);
- return this._fallbackText;
- }
- });
-
- PooledClass.addPoolingTo(FallbackCompositionState);
-
- module.exports = FallbackCompositionState;
-
-/***/ }),
-/* 339 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- /**
- * Static poolers. Several custom versions for each potential number of
- * arguments. A completely generic pooler is easy to implement, but would
- * require accessing the `arguments` object. In each of these, `this` refers to
- * the Class itself, not an instance. If any others are needed, simply add them
- * here, or in their own files.
- */
- var oneArgumentPooler = function (copyFieldsFrom) {
- var Klass = this;
- if (Klass.instancePool.length) {
- var instance = Klass.instancePool.pop();
- Klass.call(instance, copyFieldsFrom);
- return instance;
- } else {
- return new Klass(copyFieldsFrom);
- }
- };
-
- var twoArgumentPooler = function (a1, a2) {
- var Klass = this;
- if (Klass.instancePool.length) {
- var instance = Klass.instancePool.pop();
- Klass.call(instance, a1, a2);
- return instance;
- } else {
- return new Klass(a1, a2);
- }
- };
-
- var threeArgumentPooler = function (a1, a2, a3) {
- var Klass = this;
- if (Klass.instancePool.length) {
- var instance = Klass.instancePool.pop();
- Klass.call(instance, a1, a2, a3);
- return instance;
- } else {
- return new Klass(a1, a2, a3);
- }
- };
-
- var fourArgumentPooler = function (a1, a2, a3, a4) {
- var Klass = this;
- if (Klass.instancePool.length) {
- var instance = Klass.instancePool.pop();
- Klass.call(instance, a1, a2, a3, a4);
- return instance;
- } else {
- return new Klass(a1, a2, a3, a4);
- }
- };
-
- var standardReleaser = function (instance) {
- var Klass = this;
- !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
- instance.destructor();
- if (Klass.instancePool.length < Klass.poolSize) {
- Klass.instancePool.push(instance);
- }
- };
-
- var DEFAULT_POOL_SIZE = 10;
- var DEFAULT_POOLER = oneArgumentPooler;
-
- /**
- * Augments `CopyConstructor` to be a poolable class, augmenting only the class
- * itself (statically) not adding any prototypical fields. Any CopyConstructor
- * you give this may have a `poolSize` property, and will look for a
- * prototypical `destructor` on instances.
- *
- * @param {Function} CopyConstructor Constructor that can be used to reset.
- * @param {Function} pooler Customizable pooler.
- */
- var addPoolingTo = function (CopyConstructor, pooler) {
- // Casting as any so that flow ignores the actual implementation and trusts
- // it to match the type we declared
- var NewKlass = CopyConstructor;
- NewKlass.instancePool = [];
- NewKlass.getPooled = pooler || DEFAULT_POOLER;
- if (!NewKlass.poolSize) {
- NewKlass.poolSize = DEFAULT_POOL_SIZE;
- }
- NewKlass.release = standardReleaser;
- return NewKlass;
- };
-
- var PooledClass = {
- addPoolingTo: addPoolingTo,
- oneArgumentPooler: oneArgumentPooler,
- twoArgumentPooler: twoArgumentPooler,
- threeArgumentPooler: threeArgumentPooler,
- fourArgumentPooler: fourArgumentPooler
- };
-
- module.exports = PooledClass;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 340 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ExecutionEnvironment = __webpack_require__(337);
-
- var contentKey = null;
-
- /**
- * Gets the key used to access text content on a DOM node.
- *
- * @return {?string} Key used to access text content.
- * @internal
- */
- function getTextContentAccessor() {
- if (!contentKey && ExecutionEnvironment.canUseDOM) {
- // Prefer textContent to innerText because many browsers support both but
- // SVG elements don't support innerText even when
does.
- contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
- }
- return contentKey;
- }
-
- module.exports = getTextContentAccessor;
-
-/***/ }),
-/* 341 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var SyntheticEvent = __webpack_require__(342);
-
- /**
- * @interface Event
- * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
- */
- var CompositionEventInterface = {
- data: null
- };
-
- /**
- * @param {object} dispatchConfig Configuration used to dispatch this event.
- * @param {string} dispatchMarker Marker identifying the event target.
- * @param {object} nativeEvent Native browser event.
- * @extends {SyntheticUIEvent}
- */
- function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
- }
-
- SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
-
- module.exports = SyntheticCompositionEvent;
-
-/***/ }),
-/* 342 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _assign = __webpack_require__(317);
-
- var PooledClass = __webpack_require__(339);
-
- var emptyFunction = __webpack_require__(302);
- var warning = __webpack_require__(304);
-
- var didWarnForAddedNewProperty = false;
- var isProxySupported = typeof Proxy === 'function';
-
- var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
-
- /**
- * @interface Event
- * @see http://www.w3.org/TR/DOM-Level-3-Events/
- */
- var EventInterface = {
- type: null,
- target: null,
- // currentTarget is set when dispatching; no use in copying it here
- currentTarget: emptyFunction.thatReturnsNull,
- eventPhase: null,
- bubbles: null,
- cancelable: null,
- timeStamp: function (event) {
- return event.timeStamp || Date.now();
- },
- defaultPrevented: null,
- isTrusted: null
- };
-
- /**
- * Synthetic events are dispatched by event plugins, typically in response to a
- * top-level event delegation handler.
- *
- * These systems should generally use pooling to reduce the frequency of garbage
- * collection. The system should check `isPersistent` to determine whether the
- * event should be released into the pool after being dispatched. Users that
- * need a persisted event should invoke `persist`.
- *
- * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
- * normalizing browser quirks. Subclasses do not necessarily have to implement a
- * DOM interface; custom application-specific events can also subclass this.
- *
- * @param {object} dispatchConfig Configuration used to dispatch this event.
- * @param {*} targetInst Marker identifying the event target.
- * @param {object} nativeEvent Native browser event.
- * @param {DOMEventTarget} nativeEventTarget Target node.
- */
- function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
- if (process.env.NODE_ENV !== 'production') {
- // these have a getter/setter for warnings
- delete this.nativeEvent;
- delete this.preventDefault;
- delete this.stopPropagation;
- }
-
- this.dispatchConfig = dispatchConfig;
- this._targetInst = targetInst;
- this.nativeEvent = nativeEvent;
-
- var Interface = this.constructor.Interface;
- for (var propName in Interface) {
- if (!Interface.hasOwnProperty(propName)) {
- continue;
- }
- if (process.env.NODE_ENV !== 'production') {
- delete this[propName]; // this has a getter/setter for warnings
- }
- var normalize = Interface[propName];
- if (normalize) {
- this[propName] = normalize(nativeEvent);
- } else {
- if (propName === 'target') {
- this.target = nativeEventTarget;
- } else {
- this[propName] = nativeEvent[propName];
- }
- }
- }
-
- var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
- if (defaultPrevented) {
- this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
- } else {
- this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
- }
- this.isPropagationStopped = emptyFunction.thatReturnsFalse;
- return this;
- }
-
- _assign(SyntheticEvent.prototype, {
-
- preventDefault: function () {
- this.defaultPrevented = true;
- var event = this.nativeEvent;
- if (!event) {
- return;
- }
-
- if (event.preventDefault) {
- event.preventDefault();
- } else if (typeof event.returnValue !== 'unknown') {
- // eslint-disable-line valid-typeof
- event.returnValue = false;
- }
- this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
- },
-
- stopPropagation: function () {
- var event = this.nativeEvent;
- if (!event) {
- return;
- }
-
- if (event.stopPropagation) {
- event.stopPropagation();
- } else if (typeof event.cancelBubble !== 'unknown') {
- // eslint-disable-line valid-typeof
- // The ChangeEventPlugin registers a "propertychange" event for
- // IE. This event does not support bubbling or cancelling, and
- // any references to cancelBubble throw "Member not found". A
- // typeof check of "unknown" circumvents this issue (and is also
- // IE specific).
- event.cancelBubble = true;
- }
-
- this.isPropagationStopped = emptyFunction.thatReturnsTrue;
- },
-
- /**
- * We release all dispatched `SyntheticEvent`s after each event loop, adding
- * them back into the pool. This allows a way to hold onto a reference that
- * won't be added back into the pool.
- */
- persist: function () {
- this.isPersistent = emptyFunction.thatReturnsTrue;
- },
-
- /**
- * Checks if this event should be released back into the pool.
- *
- * @return {boolean} True if this should not be released, false otherwise.
- */
- isPersistent: emptyFunction.thatReturnsFalse,
-
- /**
- * `PooledClass` looks for `destructor` on each instance it releases.
- */
- destructor: function () {
- var Interface = this.constructor.Interface;
- for (var propName in Interface) {
- if (process.env.NODE_ENV !== 'production') {
- Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
- } else {
- this[propName] = null;
- }
- }
- for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
- this[shouldBeReleasedProperties[i]] = null;
- }
- if (process.env.NODE_ENV !== 'production') {
- Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
- Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
- Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
- }
- }
-
- });
-
- SyntheticEvent.Interface = EventInterface;
-
- if (process.env.NODE_ENV !== 'production') {
- if (isProxySupported) {
- /*eslint-disable no-func-assign */
- SyntheticEvent = new Proxy(SyntheticEvent, {
- construct: function (target, args) {
- return this.apply(target, Object.create(target.prototype), args);
- },
- apply: function (constructor, that, args) {
- return new Proxy(constructor.apply(that, args), {
- set: function (target, prop, value) {
- if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
- process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;
- didWarnForAddedNewProperty = true;
- }
- target[prop] = value;
- return true;
- }
- });
- }
- });
- /*eslint-enable no-func-assign */
- }
- }
- /**
- * Helper to reduce boilerplate when creating subclasses.
- *
- * @param {function} Class
- * @param {?object} Interface
- */
- SyntheticEvent.augmentClass = function (Class, Interface) {
- var Super = this;
-
- var E = function () {};
- E.prototype = Super.prototype;
- var prototype = new E();
-
- _assign(prototype, Class.prototype);
- Class.prototype = prototype;
- Class.prototype.constructor = Class;
-
- Class.Interface = _assign({}, Super.Interface, Interface);
- Class.augmentClass = Super.augmentClass;
-
- PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
- };
-
- PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
-
- module.exports = SyntheticEvent;
-
- /**
- * Helper to nullify syntheticEvent instance properties when destructing
- *
- * @param {object} SyntheticEvent
- * @param {String} propName
- * @return {object} defineProperty object
- */
- function getPooledWarningPropertyDefinition(propName, getVal) {
- var isFunction = typeof getVal === 'function';
- return {
- configurable: true,
- set: set,
- get: get
- };
-
- function set(val) {
- var action = isFunction ? 'setting the method' : 'setting the property';
- warn(action, 'This is effectively a no-op');
- return val;
- }
-
- function get() {
- var action = isFunction ? 'accessing the method' : 'accessing the property';
- var result = isFunction ? 'This is a no-op function' : 'This is set to null';
- warn(action, result);
- return getVal;
- }
-
- function warn(action, result) {
- var warningCondition = false;
- process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
- }
- }
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 343 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var SyntheticEvent = __webpack_require__(342);
-
- /**
- * @interface Event
- * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
- * /#events-inputevents
- */
- var InputEventInterface = {
- data: null
- };
-
- /**
- * @param {object} dispatchConfig Configuration used to dispatch this event.
- * @param {string} dispatchMarker Marker identifying the event target.
- * @param {object} nativeEvent Native browser event.
- * @extends {SyntheticUIEvent}
- */
- function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
- }
-
- SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
-
- module.exports = SyntheticInputEvent;
-
-/***/ }),
-/* 344 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var EventPluginHub = __webpack_require__(330);
- var EventPropagators = __webpack_require__(329);
- var ExecutionEnvironment = __webpack_require__(337);
- var ReactDOMComponentTree = __webpack_require__(345);
- var ReactUpdates = __webpack_require__(348);
- var SyntheticEvent = __webpack_require__(342);
-
- var getEventTarget = __webpack_require__(364);
- var isEventSupported = __webpack_require__(365);
- var isTextInputElement = __webpack_require__(366);
-
- var eventTypes = {
- change: {
- phasedRegistrationNames: {
- bubbled: 'onChange',
- captured: 'onChangeCapture'
- },
- dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange']
- }
- };
-
- /**
- * For IE shims
- */
- var activeElement = null;
- var activeElementInst = null;
- var activeElementValue = null;
- var activeElementValueProp = null;
-
- /**
- * SECTION: handle `change` event
- */
- function shouldUseChangeEvent(elem) {
- var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
- return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
- }
-
- var doesChangeEventBubble = false;
- if (ExecutionEnvironment.canUseDOM) {
- // See `handleChange` comment below
- doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8);
- }
-
- function manualDispatchChangeEvent(nativeEvent) {
- var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
- EventPropagators.accumulateTwoPhaseDispatches(event);
-
- // If change and propertychange bubbled, we'd just bind to it like all the
- // other events and have it go through ReactBrowserEventEmitter. Since it
- // doesn't, we manually listen for the events and so we have to enqueue and
- // process the abstract event manually.
- //
- // Batching is necessary here in order to ensure that all event handlers run
- // before the next rerender (including event handlers attached to ancestor
- // elements instead of directly on the input). Without this, controlled
- // components don't work properly in conjunction with event bubbling because
- // the component is rerendered and the value reverted before all the event
- // handlers can run. See https://github.com/facebook/react/issues/708.
- ReactUpdates.batchedUpdates(runEventInBatch, event);
- }
-
- function runEventInBatch(event) {
- EventPluginHub.enqueueEvents(event);
- EventPluginHub.processEventQueue(false);
- }
-
- function startWatchingForChangeEventIE8(target, targetInst) {
- activeElement = target;
- activeElementInst = targetInst;
- activeElement.attachEvent('onchange', manualDispatchChangeEvent);
- }
-
- function stopWatchingForChangeEventIE8() {
- if (!activeElement) {
- return;
- }
- activeElement.detachEvent('onchange', manualDispatchChangeEvent);
- activeElement = null;
- activeElementInst = null;
- }
-
- function getTargetInstForChangeEvent(topLevelType, targetInst) {
- if (topLevelType === 'topChange') {
- return targetInst;
- }
- }
- function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
- if (topLevelType === 'topFocus') {
- // stopWatching() should be a noop here but we call it just in case we
- // missed a blur event somehow.
- stopWatchingForChangeEventIE8();
- startWatchingForChangeEventIE8(target, targetInst);
- } else if (topLevelType === 'topBlur') {
- stopWatchingForChangeEventIE8();
- }
- }
-
- /**
- * SECTION: handle `input` event
- */
- var isInputEventSupported = false;
- if (ExecutionEnvironment.canUseDOM) {
- // IE9 claims to support the input event but fails to trigger it when
- // deleting text, so we ignore its input events.
- // IE10+ fire input events to often, such when a placeholder
- // changes or when an input with a placeholder is focused.
- isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 11);
- }
-
- /**
- * (For IE <=11) Replacement getter/setter for the `value` property that gets
- * set on the active element.
- */
- var newValueProp = {
- get: function () {
- return activeElementValueProp.get.call(this);
- },
- set: function (val) {
- // Cast to a string so we can do equality checks.
- activeElementValue = '' + val;
- activeElementValueProp.set.call(this, val);
- }
- };
-
- /**
- * (For IE <=11) Starts tracking propertychange events on the passed-in element
- * and override the value property so that we can distinguish user events from
- * value changes in JS.
- */
- function startWatchingForValueChange(target, targetInst) {
- activeElement = target;
- activeElementInst = targetInst;
- activeElementValue = target.value;
- activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
-
- // Not guarded in a canDefineProperty check: IE8 supports defineProperty only
- // on DOM elements
- Object.defineProperty(activeElement, 'value', newValueProp);
- if (activeElement.attachEvent) {
- activeElement.attachEvent('onpropertychange', handlePropertyChange);
- } else {
- activeElement.addEventListener('propertychange', handlePropertyChange, false);
- }
- }
-
- /**
- * (For IE <=11) Removes the event listeners from the currently-tracked element,
- * if any exists.
- */
- function stopWatchingForValueChange() {
- if (!activeElement) {
- return;
- }
-
- // delete restores the original property definition
- delete activeElement.value;
-
- if (activeElement.detachEvent) {
- activeElement.detachEvent('onpropertychange', handlePropertyChange);
- } else {
- activeElement.removeEventListener('propertychange', handlePropertyChange, false);
- }
-
- activeElement = null;
- activeElementInst = null;
- activeElementValue = null;
- activeElementValueProp = null;
- }
-
- /**
- * (For IE <=11) Handles a propertychange event, sending a `change` event if
- * the value of the active element has changed.
- */
- function handlePropertyChange(nativeEvent) {
- if (nativeEvent.propertyName !== 'value') {
- return;
- }
- var value = nativeEvent.srcElement.value;
- if (value === activeElementValue) {
- return;
- }
- activeElementValue = value;
-
- manualDispatchChangeEvent(nativeEvent);
- }
-
- /**
- * If a `change` event should be fired, returns the target's ID.
- */
- function getTargetInstForInputEvent(topLevelType, targetInst) {
- if (topLevelType === 'topInput') {
- // In modern browsers (i.e., not IE8 or IE9), the input event is exactly
- // what we want so fall through here and trigger an abstract event
- return targetInst;
- }
- }
-
- function handleEventsForInputEventIE(topLevelType, target, targetInst) {
- if (topLevelType === 'topFocus') {
- // In IE8, we can capture almost all .value changes by adding a
- // propertychange handler and looking for events with propertyName
- // equal to 'value'
- // In IE9-11, propertychange fires for most input events but is buggy and
- // doesn't fire when text is deleted, but conveniently, selectionchange
- // appears to fire in all of the remaining cases so we catch those and
- // forward the event if the value has changed
- // In either case, we don't want to call the event handler if the value
- // is changed from JS so we redefine a setter for `.value` that updates
- // our activeElementValue variable, allowing us to ignore those changes
- //
- // stopWatching() should be a noop here but we call it just in case we
- // missed a blur event somehow.
- stopWatchingForValueChange();
- startWatchingForValueChange(target, targetInst);
- } else if (topLevelType === 'topBlur') {
- stopWatchingForValueChange();
- }
- }
-
- // For IE8 and IE9.
- function getTargetInstForInputEventIE(topLevelType, targetInst) {
- if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') {
- // On the selectionchange event, the target is just document which isn't
- // helpful for us so just check activeElement instead.
- //
- // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
- // propertychange on the first input event after setting `value` from a
- // script and fires only keydown, keypress, keyup. Catching keyup usually
- // gets it and catching keydown lets us fire an event for the first
- // keystroke if user does a key repeat (it'll be a little delayed: right
- // before the second keystroke). Other input methods (e.g., paste) seem to
- // fire selectionchange normally.
- if (activeElement && activeElement.value !== activeElementValue) {
- activeElementValue = activeElement.value;
- return activeElementInst;
- }
- }
- }
-
- /**
- * SECTION: handle `click` event
- */
- function shouldUseClickEvent(elem) {
- // Use the `click` event to detect changes to checkbox and radio inputs.
- // This approach works across all browsers, whereas `change` does not fire
- // until `blur` in IE8.
- return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
- }
-
- function getTargetInstForClickEvent(topLevelType, targetInst) {
- if (topLevelType === 'topClick') {
- return targetInst;
- }
- }
-
- function handleControlledInputBlur(inst, node) {
- // TODO: In IE, inst is occasionally null. Why?
- if (inst == null) {
- return;
- }
-
- // Fiber and ReactDOM keep wrapper state in separate places
- var state = inst._wrapperState || node._wrapperState;
-
- if (!state || !state.controlled || node.type !== 'number') {
- return;
- }
-
- // If controlled, assign the value attribute to the current value on blur
- var value = '' + node.value;
- if (node.getAttribute('value') !== value) {
- node.setAttribute('value', value);
- }
- }
-
- /**
- * This plugin creates an `onChange` event that normalizes change events
- * across form elements. This event fires at a time when it's possible to
- * change the element's value without seeing a flicker.
- *
- * Supported elements are:
- * - input (see `isTextInputElement`)
- * - textarea
- * - select
- */
- var ChangeEventPlugin = {
-
- eventTypes: eventTypes,
-
- extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
- var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
-
- var getTargetInstFunc, handleEventFunc;
- if (shouldUseChangeEvent(targetNode)) {
- if (doesChangeEventBubble) {
- getTargetInstFunc = getTargetInstForChangeEvent;
- } else {
- handleEventFunc = handleEventsForChangeEventIE8;
- }
- } else if (isTextInputElement(targetNode)) {
- if (isInputEventSupported) {
- getTargetInstFunc = getTargetInstForInputEvent;
- } else {
- getTargetInstFunc = getTargetInstForInputEventIE;
- handleEventFunc = handleEventsForInputEventIE;
- }
- } else if (shouldUseClickEvent(targetNode)) {
- getTargetInstFunc = getTargetInstForClickEvent;
- }
-
- if (getTargetInstFunc) {
- var inst = getTargetInstFunc(topLevelType, targetInst);
- if (inst) {
- var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
- event.type = 'change';
- EventPropagators.accumulateTwoPhaseDispatches(event);
- return event;
- }
- }
-
- if (handleEventFunc) {
- handleEventFunc(topLevelType, targetNode, targetInst);
- }
-
- // When blurring, set the value attribute for number inputs
- if (topLevelType === 'topBlur') {
- handleControlledInputBlur(targetInst, targetNode);
- }
- }
-
- };
-
- module.exports = ChangeEventPlugin;
-
-/***/ }),
-/* 345 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var DOMProperty = __webpack_require__(346);
- var ReactDOMComponentFlags = __webpack_require__(347);
-
- var invariant = __webpack_require__(303);
-
- var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
- var Flags = ReactDOMComponentFlags;
-
- var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2);
-
- /**
- * Check if a given node should be cached.
- */
- function shouldPrecacheNode(node, nodeID) {
- return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' ';
- }
-
- /**
- * Drill down (through composites and empty components) until we get a host or
- * host text component.
- *
- * This is pretty polymorphic but unavoidable with the current structure we have
- * for `_renderedChildren`.
- */
- function getRenderedHostOrTextFromComponent(component) {
- var rendered;
- while (rendered = component._renderedComponent) {
- component = rendered;
- }
- return component;
- }
-
- /**
- * Populate `_hostNode` on the rendered host/text component with the given
- * DOM node. The passed `inst` can be a composite.
- */
- function precacheNode(inst, node) {
- var hostInst = getRenderedHostOrTextFromComponent(inst);
- hostInst._hostNode = node;
- node[internalInstanceKey] = hostInst;
- }
-
- function uncacheNode(inst) {
- var node = inst._hostNode;
- if (node) {
- delete node[internalInstanceKey];
- inst._hostNode = null;
- }
- }
-
- /**
- * Populate `_hostNode` on each child of `inst`, assuming that the children
- * match up with the DOM (element) children of `node`.
- *
- * We cache entire levels at once to avoid an n^2 problem where we access the
- * children of a node sequentially and have to walk from the start to our target
- * node every time.
- *
- * Since we update `_renderedChildren` and the actual DOM at (slightly)
- * different times, we could race here and see a newer `_renderedChildren` than
- * the DOM nodes we see. To avoid this, ReactMultiChild calls
- * `prepareToManageChildren` before we change `_renderedChildren`, at which
- * time the container's child nodes are always cached (until it unmounts).
- */
- function precacheChildNodes(inst, node) {
- if (inst._flags & Flags.hasCachedChildNodes) {
- return;
- }
- var children = inst._renderedChildren;
- var childNode = node.firstChild;
- outer: for (var name in children) {
- if (!children.hasOwnProperty(name)) {
- continue;
- }
- var childInst = children[name];
- var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
- if (childID === 0) {
- // We're currently unmounting this child in ReactMultiChild; skip it.
- continue;
- }
- // We assume the child nodes are in the same order as the child instances.
- for (; childNode !== null; childNode = childNode.nextSibling) {
- if (shouldPrecacheNode(childNode, childID)) {
- precacheNode(childInst, childNode);
- continue outer;
- }
- }
- // We reached the end of the DOM children without finding an ID match.
- true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0;
- }
- inst._flags |= Flags.hasCachedChildNodes;
- }
-
- /**
- * Given a DOM node, return the closest ReactDOMComponent or
- * ReactDOMTextComponent instance ancestor.
- */
- function getClosestInstanceFromNode(node) {
- if (node[internalInstanceKey]) {
- return node[internalInstanceKey];
- }
-
- // Walk up the tree until we find an ancestor whose instance we have cached.
- var parents = [];
- while (!node[internalInstanceKey]) {
- parents.push(node);
- if (node.parentNode) {
- node = node.parentNode;
- } else {
- // Top of the tree. This node must not be part of a React tree (or is
- // unmounted, potentially).
- return null;
- }
- }
-
- var closest;
- var inst;
- for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
- closest = inst;
- if (parents.length) {
- precacheChildNodes(inst, node);
- }
- }
-
- return closest;
- }
-
- /**
- * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
- * instance, or null if the node was not rendered by this React.
- */
- function getInstanceFromNode(node) {
- var inst = getClosestInstanceFromNode(node);
- if (inst != null && inst._hostNode === node) {
- return inst;
- } else {
- return null;
- }
- }
-
- /**
- * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
- * DOM node.
- */
- function getNodeFromInstance(inst) {
- // Without this first invariant, passing a non-DOM-component triggers the next
- // invariant for a missing parent, which is super confusing.
- !(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
-
- if (inst._hostNode) {
- return inst._hostNode;
- }
-
- // Walk up the tree until we find an ancestor whose DOM node we have cached.
- var parents = [];
- while (!inst._hostNode) {
- parents.push(inst);
- !inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0;
- inst = inst._hostParent;
- }
-
- // Now parents contains each ancestor that does *not* have a cached native
- // node, and `inst` is the deepest ancestor that does.
- for (; parents.length; inst = parents.pop()) {
- precacheChildNodes(inst, inst._hostNode);
- }
-
- return inst._hostNode;
- }
-
- var ReactDOMComponentTree = {
- getClosestInstanceFromNode: getClosestInstanceFromNode,
- getInstanceFromNode: getInstanceFromNode,
- getNodeFromInstance: getNodeFromInstance,
- precacheChildNodes: precacheChildNodes,
- precacheNode: precacheNode,
- uncacheNode: uncacheNode
- };
-
- module.exports = ReactDOMComponentTree;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 346 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- function checkMask(value, bitmask) {
- return (value & bitmask) === bitmask;
- }
-
- var DOMPropertyInjection = {
- /**
- * Mapping from normalized, camelcased property names to a configuration that
- * specifies how the associated DOM property should be accessed or rendered.
- */
- MUST_USE_PROPERTY: 0x1,
- HAS_BOOLEAN_VALUE: 0x4,
- HAS_NUMERIC_VALUE: 0x8,
- HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
- HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
-
- /**
- * Inject some specialized knowledge about the DOM. This takes a config object
- * with the following properties:
- *
- * isCustomAttribute: function that given an attribute name will return true
- * if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
- * attributes where it's impossible to enumerate all of the possible
- * attribute names,
- *
- * Properties: object mapping DOM property name to one of the
- * DOMPropertyInjection constants or null. If your attribute isn't in here,
- * it won't get written to the DOM.
- *
- * DOMAttributeNames: object mapping React attribute name to the DOM
- * attribute name. Attribute names not specified use the **lowercase**
- * normalized name.
- *
- * DOMAttributeNamespaces: object mapping React attribute name to the DOM
- * attribute namespace URL. (Attribute names not specified use no namespace.)
- *
- * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
- * Property names not specified use the normalized name.
- *
- * DOMMutationMethods: Properties that require special mutation methods. If
- * `value` is undefined, the mutation method should unset the property.
- *
- * @param {object} domPropertyConfig the config as described above.
- */
- injectDOMPropertyConfig: function (domPropertyConfig) {
- var Injection = DOMPropertyInjection;
- var Properties = domPropertyConfig.Properties || {};
- var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
- var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
- var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
- var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
-
- if (domPropertyConfig.isCustomAttribute) {
- DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
- }
-
- for (var propName in Properties) {
- !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0;
-
- var lowerCased = propName.toLowerCase();
- var propConfig = Properties[propName];
-
- var propertyInfo = {
- attributeName: lowerCased,
- attributeNamespace: null,
- propertyName: propName,
- mutationMethod: null,
-
- mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
- hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
- hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
- hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
- hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
- };
- !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0;
-
- if (process.env.NODE_ENV !== 'production') {
- DOMProperty.getPossibleStandardName[lowerCased] = propName;
- }
-
- if (DOMAttributeNames.hasOwnProperty(propName)) {
- var attributeName = DOMAttributeNames[propName];
- propertyInfo.attributeName = attributeName;
- if (process.env.NODE_ENV !== 'production') {
- DOMProperty.getPossibleStandardName[attributeName] = propName;
- }
- }
-
- if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
- propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
- }
-
- if (DOMPropertyNames.hasOwnProperty(propName)) {
- propertyInfo.propertyName = DOMPropertyNames[propName];
- }
-
- if (DOMMutationMethods.hasOwnProperty(propName)) {
- propertyInfo.mutationMethod = DOMMutationMethods[propName];
- }
-
- DOMProperty.properties[propName] = propertyInfo;
- }
- }
- };
-
- /* eslint-disable max-len */
- var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
- /* eslint-enable max-len */
-
- /**
- * DOMProperty exports lookup objects that can be used like functions:
- *
- * > DOMProperty.isValid['id']
- * true
- * > DOMProperty.isValid['foobar']
- * undefined
- *
- * Although this may be confusing, it performs better in general.
- *
- * @see http://jsperf.com/key-exists
- * @see http://jsperf.com/key-missing
- */
- var DOMProperty = {
-
- ID_ATTRIBUTE_NAME: 'data-reactid',
- ROOT_ATTRIBUTE_NAME: 'data-reactroot',
-
- ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
- ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
-
- /**
- * Map from property "standard name" to an object with info about how to set
- * the property in the DOM. Each object contains:
- *
- * attributeName:
- * Used when rendering markup or with `*Attribute()`.
- * attributeNamespace
- * propertyName:
- * Used on DOM node instances. (This includes properties that mutate due to
- * external factors.)
- * mutationMethod:
- * If non-null, used instead of the property or `setAttribute()` after
- * initial render.
- * mustUseProperty:
- * Whether the property must be accessed and mutated as an object property.
- * hasBooleanValue:
- * Whether the property should be removed when set to a falsey value.
- * hasNumericValue:
- * Whether the property must be numeric or parse as a numeric and should be
- * removed when set to a falsey value.
- * hasPositiveNumericValue:
- * Whether the property must be positive numeric or parse as a positive
- * numeric and should be removed when set to a falsey value.
- * hasOverloadedBooleanValue:
- * Whether the property can be used as a flag as well as with a value.
- * Removed when strictly equal to false; present without a value when
- * strictly equal to true; present with a value otherwise.
- */
- properties: {},
-
- /**
- * Mapping from lowercase property names to the properly cased version, used
- * to warn in the case of missing properties. Available only in __DEV__.
- *
- * autofocus is predefined, because adding it to the property whitelist
- * causes unintended side effects.
- *
- * @type {Object}
- */
- getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null,
-
- /**
- * All of the isCustomAttribute() functions that have been injected.
- */
- _isCustomAttributeFunctions: [],
-
- /**
- * Checks whether a property name is a custom attribute.
- * @method
- */
- isCustomAttribute: function (attributeName) {
- for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
- var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
- if (isCustomAttributeFn(attributeName)) {
- return true;
- }
- }
- return false;
- },
-
- injection: DOMPropertyInjection
- };
-
- module.exports = DOMProperty;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 347 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2015-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ReactDOMComponentFlags = {
- hasCachedChildNodes: 1 << 0
- };
-
- module.exports = ReactDOMComponentFlags;
-
-/***/ }),
-/* 348 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331),
- _assign = __webpack_require__(317);
-
- var CallbackQueue = __webpack_require__(349);
- var PooledClass = __webpack_require__(339);
- var ReactFeatureFlags = __webpack_require__(350);
- var ReactReconciler = __webpack_require__(351);
- var Transaction = __webpack_require__(363);
-
- var invariant = __webpack_require__(303);
-
- var dirtyComponents = [];
- var updateBatchNumber = 0;
- var asapCallbackQueue = CallbackQueue.getPooled();
- var asapEnqueued = false;
-
- var batchingStrategy = null;
-
- function ensureInjected() {
- !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0;
- }
-
- var NESTED_UPDATES = {
- initialize: function () {
- this.dirtyComponentsLength = dirtyComponents.length;
- },
- close: function () {
- if (this.dirtyComponentsLength !== dirtyComponents.length) {
- // Additional updates were enqueued by componentDidUpdate handlers or
- // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
- // these new updates so that if A's componentDidUpdate calls setState on
- // B, B will update before the callback A's updater provided when calling
- // setState.
- dirtyComponents.splice(0, this.dirtyComponentsLength);
- flushBatchedUpdates();
- } else {
- dirtyComponents.length = 0;
- }
- }
- };
-
- var UPDATE_QUEUEING = {
- initialize: function () {
- this.callbackQueue.reset();
- },
- close: function () {
- this.callbackQueue.notifyAll();
- }
- };
-
- var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
-
- function ReactUpdatesFlushTransaction() {
- this.reinitializeTransaction();
- this.dirtyComponentsLength = null;
- this.callbackQueue = CallbackQueue.getPooled();
- this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(
- /* useCreateElement */true);
- }
-
- _assign(ReactUpdatesFlushTransaction.prototype, Transaction, {
- getTransactionWrappers: function () {
- return TRANSACTION_WRAPPERS;
- },
-
- destructor: function () {
- this.dirtyComponentsLength = null;
- CallbackQueue.release(this.callbackQueue);
- this.callbackQueue = null;
- ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
- this.reconcileTransaction = null;
- },
-
- perform: function (method, scope, a) {
- // Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
- // with this transaction's wrappers around it.
- return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
- }
- });
-
- PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
-
- function batchedUpdates(callback, a, b, c, d, e) {
- ensureInjected();
- return batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
- }
-
- /**
- * Array comparator for ReactComponents by mount ordering.
- *
- * @param {ReactComponent} c1 first component you're comparing
- * @param {ReactComponent} c2 second component you're comparing
- * @return {number} Return value usable by Array.prototype.sort().
- */
- function mountOrderComparator(c1, c2) {
- return c1._mountOrder - c2._mountOrder;
- }
-
- function runBatchedUpdates(transaction) {
- var len = transaction.dirtyComponentsLength;
- !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0;
-
- // Since reconciling a component higher in the owner hierarchy usually (not
- // always -- see shouldComponentUpdate()) will reconcile children, reconcile
- // them before their children by sorting the array.
- dirtyComponents.sort(mountOrderComparator);
-
- // Any updates enqueued while reconciling must be performed after this entire
- // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
- // C, B could update twice in a single batch if C's render enqueues an update
- // to B (since B would have already updated, we should skip it, and the only
- // way we can know to do so is by checking the batch counter).
- updateBatchNumber++;
-
- for (var i = 0; i < len; i++) {
- // If a component is unmounted before pending changes apply, it will still
- // be here, but we assume that it has cleared its _pendingCallbacks and
- // that performUpdateIfNecessary is a noop.
- var component = dirtyComponents[i];
-
- // If performUpdateIfNecessary happens to enqueue any new updates, we
- // shouldn't execute the callbacks until the next render happens, so
- // stash the callbacks first
- var callbacks = component._pendingCallbacks;
- component._pendingCallbacks = null;
-
- var markerName;
- if (ReactFeatureFlags.logTopLevelRenders) {
- var namedComponent = component;
- // Duck type TopLevelWrapper. This is probably always true.
- if (component._currentElement.type.isReactTopLevelWrapper) {
- namedComponent = component._renderedComponent;
- }
- markerName = 'React update: ' + namedComponent.getName();
- console.time(markerName);
- }
-
- ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);
-
- if (markerName) {
- console.timeEnd(markerName);
- }
-
- if (callbacks) {
- for (var j = 0; j < callbacks.length; j++) {
- transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
- }
- }
- }
- }
-
- var flushBatchedUpdates = function () {
- // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
- // array and perform any updates enqueued by mount-ready handlers (i.e.,
- // componentDidUpdate) but we need to check here too in order to catch
- // updates enqueued by setState callbacks and asap calls.
- while (dirtyComponents.length || asapEnqueued) {
- if (dirtyComponents.length) {
- var transaction = ReactUpdatesFlushTransaction.getPooled();
- transaction.perform(runBatchedUpdates, null, transaction);
- ReactUpdatesFlushTransaction.release(transaction);
- }
-
- if (asapEnqueued) {
- asapEnqueued = false;
- var queue = asapCallbackQueue;
- asapCallbackQueue = CallbackQueue.getPooled();
- queue.notifyAll();
- CallbackQueue.release(queue);
- }
- }
- };
-
- /**
- * Mark a component as needing a rerender, adding an optional callback to a
- * list of functions which will be executed once the rerender occurs.
- */
- function enqueueUpdate(component) {
- ensureInjected();
-
- // Various parts of our code (such as ReactCompositeComponent's
- // _renderValidatedComponent) assume that calls to render aren't nested;
- // verify that that's the case. (This is called by each top-level update
- // function, like setState, forceUpdate, etc.; creation and
- // destruction of top-level components is guarded in ReactMount.)
-
- if (!batchingStrategy.isBatchingUpdates) {
- batchingStrategy.batchedUpdates(enqueueUpdate, component);
- return;
- }
-
- dirtyComponents.push(component);
- if (component._updateBatchNumber == null) {
- component._updateBatchNumber = updateBatchNumber + 1;
- }
- }
-
- /**
- * Enqueue a callback to be run at the end of the current batching cycle. Throws
- * if no updates are currently being performed.
- */
- function asap(callback, context) {
- !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0;
- asapCallbackQueue.enqueue(callback, context);
- asapEnqueued = true;
- }
-
- var ReactUpdatesInjection = {
- injectReconcileTransaction: function (ReconcileTransaction) {
- !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0;
- ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
- },
-
- injectBatchingStrategy: function (_batchingStrategy) {
- !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0;
- !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0;
- !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0;
- batchingStrategy = _batchingStrategy;
- }
- };
-
- var ReactUpdates = {
- /**
- * React references `ReactReconcileTransaction` using this property in order
- * to allow dependency injection.
- *
- * @internal
- */
- ReactReconcileTransaction: null,
-
- batchedUpdates: batchedUpdates,
- enqueueUpdate: enqueueUpdate,
- flushBatchedUpdates: flushBatchedUpdates,
- injection: ReactUpdatesInjection,
- asap: asap
- };
-
- module.exports = ReactUpdates;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 349 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
- var PooledClass = __webpack_require__(339);
-
- var invariant = __webpack_require__(303);
-
- /**
- * A specialized pseudo-event module to help keep track of components waiting to
- * be notified when their DOM representations are available for use.
- *
- * This implements `PooledClass`, so you should never need to instantiate this.
- * Instead, use `CallbackQueue.getPooled()`.
- *
- * @class ReactMountReady
- * @implements PooledClass
- * @internal
- */
-
- var CallbackQueue = function () {
- function CallbackQueue(arg) {
- _classCallCheck(this, CallbackQueue);
-
- this._callbacks = null;
- this._contexts = null;
- this._arg = arg;
- }
-
- /**
- * Enqueues a callback to be invoked when `notifyAll` is invoked.
- *
- * @param {function} callback Invoked when `notifyAll` is invoked.
- * @param {?object} context Context to call `callback` with.
- * @internal
- */
-
-
- CallbackQueue.prototype.enqueue = function enqueue(callback, context) {
- this._callbacks = this._callbacks || [];
- this._callbacks.push(callback);
- this._contexts = this._contexts || [];
- this._contexts.push(context);
- };
-
- /**
- * Invokes all enqueued callbacks and clears the queue. This is invoked after
- * the DOM representation of a component has been created or updated.
- *
- * @internal
- */
-
-
- CallbackQueue.prototype.notifyAll = function notifyAll() {
- var callbacks = this._callbacks;
- var contexts = this._contexts;
- var arg = this._arg;
- if (callbacks && contexts) {
- !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0;
- this._callbacks = null;
- this._contexts = null;
- for (var i = 0; i < callbacks.length; i++) {
- callbacks[i].call(contexts[i], arg);
- }
- callbacks.length = 0;
- contexts.length = 0;
- }
- };
-
- CallbackQueue.prototype.checkpoint = function checkpoint() {
- return this._callbacks ? this._callbacks.length : 0;
- };
-
- CallbackQueue.prototype.rollback = function rollback(len) {
- if (this._callbacks && this._contexts) {
- this._callbacks.length = len;
- this._contexts.length = len;
- }
- };
-
- /**
- * Resets the internal queue.
- *
- * @internal
- */
-
-
- CallbackQueue.prototype.reset = function reset() {
- this._callbacks = null;
- this._contexts = null;
- };
-
- /**
- * `PooledClass` looks for this.
- */
-
-
- CallbackQueue.prototype.destructor = function destructor() {
- this.reset();
- };
-
- return CallbackQueue;
- }();
-
- module.exports = PooledClass.addPoolingTo(CallbackQueue);
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 350 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var ReactFeatureFlags = {
- // When true, call console.time() before and .timeEnd() after each top-level
- // render (both initial renders and updates). Useful when looking at prod-mode
- // timeline profiles in Chrome, for example.
- logTopLevelRenders: false
- };
-
- module.exports = ReactFeatureFlags;
-
-/***/ }),
-/* 351 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- var ReactRef = __webpack_require__(352);
- var ReactInstrumentation = __webpack_require__(354);
-
- var warning = __webpack_require__(304);
-
- /**
- * Helper to call ReactRef.attachRefs with this composite component, split out
- * to avoid allocations in the transaction mount-ready queue.
- */
- function attachRefs() {
- ReactRef.attachRefs(this, this._currentElement);
- }
-
- var ReactReconciler = {
-
- /**
- * Initializes the component, renders markup, and registers event listeners.
- *
- * @param {ReactComponent} internalInstance
- * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
- * @param {?object} the containing host component instance
- * @param {?object} info about the host container
- * @return {?string} Rendered markup to be inserted into the DOM.
- * @final
- * @internal
- */
- mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots
- ) {
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID);
- }
- }
- var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID);
- if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
- transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
- }
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
- }
- }
- return markup;
- },
-
- /**
- * Returns a value that can be passed to
- * ReactComponentEnvironment.replaceNodeWithMarkup.
- */
- getHostNode: function (internalInstance) {
- return internalInstance.getHostNode();
- },
-
- /**
- * Releases any resources allocated by `mountComponent`.
- *
- * @final
- * @internal
- */
- unmountComponent: function (internalInstance, safely) {
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID);
- }
- }
- ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
- internalInstance.unmountComponent(safely);
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
- }
- }
- },
-
- /**
- * Update a component using a new element.
- *
- * @param {ReactComponent} internalInstance
- * @param {ReactElement} nextElement
- * @param {ReactReconcileTransaction} transaction
- * @param {object} context
- * @internal
- */
- receiveComponent: function (internalInstance, nextElement, transaction, context) {
- var prevElement = internalInstance._currentElement;
-
- if (nextElement === prevElement && context === internalInstance._context) {
- // Since elements are immutable after the owner is rendered,
- // we can do a cheap identity compare here to determine if this is a
- // superfluous reconcile. It's possible for state to be mutable but such
- // change should trigger an update of the owner which would recreate
- // the element. We explicitly check for the existence of an owner since
- // it's possible for an element created outside a composite to be
- // deeply mutated and reused.
-
- // TODO: Bailing out early is just a perf optimization right?
- // TODO: Removing the return statement should affect correctness?
- return;
- }
-
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
- }
- }
-
- var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
-
- if (refsChanged) {
- ReactRef.detachRefs(internalInstance, prevElement);
- }
-
- internalInstance.receiveComponent(nextElement, transaction, context);
-
- if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
- transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
- }
-
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
- }
- }
- },
-
- /**
- * Flush any dirty changes in a component.
- *
- * @param {ReactComponent} internalInstance
- * @param {ReactReconcileTransaction} transaction
- * @internal
- */
- performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) {
- if (internalInstance._updateBatchNumber !== updateBatchNumber) {
- // The component's enqueued batch number should always be the current
- // batch or the following one.
- process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;
- return;
- }
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);
- }
- }
- internalInstance.performUpdateIfNecessary(transaction);
- if (process.env.NODE_ENV !== 'production') {
- if (internalInstance._debugID !== 0) {
- ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
- }
- }
- }
-
- };
-
- module.exports = ReactReconciler;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 352 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var ReactOwner = __webpack_require__(353);
-
- var ReactRef = {};
-
- function attachRef(ref, component, owner) {
- if (typeof ref === 'function') {
- ref(component.getPublicInstance());
- } else {
- // Legacy ref
- ReactOwner.addComponentAsRefTo(component, ref, owner);
- }
- }
-
- function detachRef(ref, component, owner) {
- if (typeof ref === 'function') {
- ref(null);
- } else {
- // Legacy ref
- ReactOwner.removeComponentAsRefFrom(component, ref, owner);
- }
- }
-
- ReactRef.attachRefs = function (instance, element) {
- if (element === null || typeof element !== 'object') {
- return;
- }
- var ref = element.ref;
- if (ref != null) {
- attachRef(ref, instance, element._owner);
- }
- };
-
- ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
- // If either the owner or a `ref` has changed, make sure the newest owner
- // has stored a reference to `this`, and the previous owner (if different)
- // has forgotten the reference to `this`. We use the element instead
- // of the public this.props because the post processing cannot determine
- // a ref. The ref conceptually lives on the element.
-
- // TODO: Should this even be possible? The owner cannot change because
- // it's forbidden by shouldUpdateReactComponent. The ref can change
- // if you swap the keys of but not the refs. Reconsider where this check
- // is made. It probably belongs where the key checking and
- // instantiateReactComponent is done.
-
- var prevRef = null;
- var prevOwner = null;
- if (prevElement !== null && typeof prevElement === 'object') {
- prevRef = prevElement.ref;
- prevOwner = prevElement._owner;
- }
-
- var nextRef = null;
- var nextOwner = null;
- if (nextElement !== null && typeof nextElement === 'object') {
- nextRef = nextElement.ref;
- nextOwner = nextElement._owner;
- }
-
- return prevRef !== nextRef ||
- // If owner changes but we have an unchanged function ref, don't update refs
- typeof nextRef === 'string' && nextOwner !== prevOwner;
- };
-
- ReactRef.detachRefs = function (instance, element) {
- if (element === null || typeof element !== 'object') {
- return;
- }
- var ref = element.ref;
- if (ref != null) {
- detachRef(ref, instance, element._owner);
- }
- };
-
- module.exports = ReactRef;
-
-/***/ }),
-/* 353 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- /**
- * @param {?object} object
- * @return {boolean} True if `object` is a valid owner.
- * @final
- */
- function isValidOwner(object) {
- return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
- }
-
- /**
- * ReactOwners are capable of storing references to owned components.
- *
- * All components are capable of //being// referenced by owner components, but
- * only ReactOwner components are capable of //referencing// owned components.
- * The named reference is known as a "ref".
- *
- * Refs are available when mounted and updated during reconciliation.
- *
- * var MyComponent = React.createClass({
- * render: function() {
- * return (
- *
- *
- *
- * );
- * },
- * handleClick: function() {
- * this.refs.custom.handleClick();
- * },
- * componentDidMount: function() {
- * this.refs.custom.initialize();
- * }
- * });
- *
- * Refs should rarely be used. When refs are used, they should only be done to
- * control data that is not handled by React's data flow.
- *
- * @class ReactOwner
- */
- var ReactOwner = {
- /**
- * Adds a component by ref to an owner component.
- *
- * @param {ReactComponent} component Component to reference.
- * @param {string} ref Name by which to refer to the component.
- * @param {ReactOwner} owner Component on which to record the ref.
- * @final
- * @internal
- */
- addComponentAsRefTo: function (component, ref, owner) {
- !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0;
- owner.attachRef(ref, component);
- },
-
- /**
- * Removes a component by ref from an owner component.
- *
- * @param {ReactComponent} component Component to dereference.
- * @param {string} ref Name of the ref to remove.
- * @param {ReactOwner} owner Component on which the ref is recorded.
- * @final
- * @internal
- */
- removeComponentAsRefFrom: function (component, ref, owner) {
- !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0;
- var ownerPublicInstance = owner.getPublicInstance();
- // Check that `component`'s owner is still alive and that `component` is still the current ref
- // because we do not want to detach the ref if another component stole it.
- if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
- owner.detachRef(ref);
- }
- }
-
- };
-
- module.exports = ReactOwner;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 354 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2016-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- // Trust the developer to only use ReactInstrumentation with a __DEV__ check
-
- var debugTool = null;
-
- if (process.env.NODE_ENV !== 'production') {
- var ReactDebugTool = __webpack_require__(355);
- debugTool = ReactDebugTool;
- }
-
- module.exports = { debugTool: debugTool };
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 355 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2016-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var ReactInvalidSetStateWarningHook = __webpack_require__(356);
- var ReactHostOperationHistoryHook = __webpack_require__(357);
- var ReactComponentTreeHook = __webpack_require__(358);
- var ExecutionEnvironment = __webpack_require__(337);
-
- var performanceNow = __webpack_require__(361);
- var warning = __webpack_require__(304);
-
- var hooks = [];
- var didHookThrowForEvent = {};
-
- function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) {
- try {
- fn.call(context, arg1, arg2, arg3, arg4, arg5);
- } catch (e) {
- process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0;
- didHookThrowForEvent[event] = true;
- }
- }
-
- function emitEvent(event, arg1, arg2, arg3, arg4, arg5) {
- for (var i = 0; i < hooks.length; i++) {
- var hook = hooks[i];
- var fn = hook[event];
- if (fn) {
- callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5);
- }
- }
- }
-
- var isProfiling = false;
- var flushHistory = [];
- var lifeCycleTimerStack = [];
- var currentFlushNesting = 0;
- var currentFlushMeasurements = [];
- var currentFlushStartTime = 0;
- var currentTimerDebugID = null;
- var currentTimerStartTime = 0;
- var currentTimerNestedFlushDuration = 0;
- var currentTimerType = null;
-
- var lifeCycleTimerHasWarned = false;
-
- function clearHistory() {
- ReactComponentTreeHook.purgeUnmountedComponents();
- ReactHostOperationHistoryHook.clearHistory();
- }
-
- function getTreeSnapshot(registeredIDs) {
- return registeredIDs.reduce(function (tree, id) {
- var ownerID = ReactComponentTreeHook.getOwnerID(id);
- var parentID = ReactComponentTreeHook.getParentID(id);
- tree[id] = {
- displayName: ReactComponentTreeHook.getDisplayName(id),
- text: ReactComponentTreeHook.getText(id),
- updateCount: ReactComponentTreeHook.getUpdateCount(id),
- childIDs: ReactComponentTreeHook.getChildIDs(id),
- // Text nodes don't have owners but this is close enough.
- ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0,
- parentID: parentID
- };
- return tree;
- }, {});
- }
-
- function resetMeasurements() {
- var previousStartTime = currentFlushStartTime;
- var previousMeasurements = currentFlushMeasurements;
- var previousOperations = ReactHostOperationHistoryHook.getHistory();
-
- if (currentFlushNesting === 0) {
- currentFlushStartTime = 0;
- currentFlushMeasurements = [];
- clearHistory();
- return;
- }
-
- if (previousMeasurements.length || previousOperations.length) {
- var registeredIDs = ReactComponentTreeHook.getRegisteredIDs();
- flushHistory.push({
- duration: performanceNow() - previousStartTime,
- measurements: previousMeasurements || [],
- operations: previousOperations || [],
- treeSnapshot: getTreeSnapshot(registeredIDs)
- });
- }
-
- clearHistory();
- currentFlushStartTime = performanceNow();
- currentFlushMeasurements = [];
- }
-
- function checkDebugID(debugID) {
- var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-
- if (allowRoot && debugID === 0) {
- return;
- }
- if (!debugID) {
- process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0;
- }
- }
-
- function beginLifeCycleTimer(debugID, timerType) {
- if (currentFlushNesting === 0) {
- return;
- }
- if (currentTimerType && !lifeCycleTimerHasWarned) {
- process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
- lifeCycleTimerHasWarned = true;
- }
- currentTimerStartTime = performanceNow();
- currentTimerNestedFlushDuration = 0;
- currentTimerDebugID = debugID;
- currentTimerType = timerType;
- }
-
- function endLifeCycleTimer(debugID, timerType) {
- if (currentFlushNesting === 0) {
- return;
- }
- if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) {
- process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
- lifeCycleTimerHasWarned = true;
- }
- if (isProfiling) {
- currentFlushMeasurements.push({
- timerType: timerType,
- instanceID: debugID,
- duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration
- });
- }
- currentTimerStartTime = 0;
- currentTimerNestedFlushDuration = 0;
- currentTimerDebugID = null;
- currentTimerType = null;
- }
-
- function pauseCurrentLifeCycleTimer() {
- var currentTimer = {
- startTime: currentTimerStartTime,
- nestedFlushStartTime: performanceNow(),
- debugID: currentTimerDebugID,
- timerType: currentTimerType
- };
- lifeCycleTimerStack.push(currentTimer);
- currentTimerStartTime = 0;
- currentTimerNestedFlushDuration = 0;
- currentTimerDebugID = null;
- currentTimerType = null;
- }
-
- function resumeCurrentLifeCycleTimer() {
- var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(),
- startTime = _lifeCycleTimerStack$.startTime,
- nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime,
- debugID = _lifeCycleTimerStack$.debugID,
- timerType = _lifeCycleTimerStack$.timerType;
-
- var nestedFlushDuration = performanceNow() - nestedFlushStartTime;
- currentTimerStartTime = startTime;
- currentTimerNestedFlushDuration += nestedFlushDuration;
- currentTimerDebugID = debugID;
- currentTimerType = timerType;
- }
-
- var lastMarkTimeStamp = 0;
- var canUsePerformanceMeasure = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
-
- function shouldMark(debugID) {
- if (!isProfiling || !canUsePerformanceMeasure) {
- return false;
- }
- var element = ReactComponentTreeHook.getElement(debugID);
- if (element == null || typeof element !== 'object') {
- return false;
- }
- var isHostElement = typeof element.type === 'string';
- if (isHostElement) {
- return false;
- }
- return true;
- }
-
- function markBegin(debugID, markType) {
- if (!shouldMark(debugID)) {
- return;
- }
-
- var markName = debugID + '::' + markType;
- lastMarkTimeStamp = performanceNow();
- performance.mark(markName);
- }
-
- function markEnd(debugID, markType) {
- if (!shouldMark(debugID)) {
- return;
- }
-
- var markName = debugID + '::' + markType;
- var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown';
-
- // Chrome has an issue of dropping markers recorded too fast:
- // https://bugs.chromium.org/p/chromium/issues/detail?id=640652
- // To work around this, we will not report very small measurements.
- // I determined the magic number by tweaking it back and forth.
- // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe.
- // When the bug is fixed, we can `measure()` unconditionally if we want to.
- var timeStamp = performanceNow();
- if (timeStamp - lastMarkTimeStamp > 0.1) {
- var measurementName = displayName + ' [' + markType + ']';
- performance.measure(measurementName, markName);
- }
-
- performance.clearMarks(markName);
- performance.clearMeasures(measurementName);
- }
-
- var ReactDebugTool = {
- addHook: function (hook) {
- hooks.push(hook);
- },
- removeHook: function (hook) {
- for (var i = 0; i < hooks.length; i++) {
- if (hooks[i] === hook) {
- hooks.splice(i, 1);
- i--;
- }
- }
- },
- isProfiling: function () {
- return isProfiling;
- },
- beginProfiling: function () {
- if (isProfiling) {
- return;
- }
-
- isProfiling = true;
- flushHistory.length = 0;
- resetMeasurements();
- ReactDebugTool.addHook(ReactHostOperationHistoryHook);
- },
- endProfiling: function () {
- if (!isProfiling) {
- return;
- }
-
- isProfiling = false;
- resetMeasurements();
- ReactDebugTool.removeHook(ReactHostOperationHistoryHook);
- },
- getFlushHistory: function () {
- return flushHistory;
- },
- onBeginFlush: function () {
- currentFlushNesting++;
- resetMeasurements();
- pauseCurrentLifeCycleTimer();
- emitEvent('onBeginFlush');
- },
- onEndFlush: function () {
- resetMeasurements();
- currentFlushNesting--;
- resumeCurrentLifeCycleTimer();
- emitEvent('onEndFlush');
- },
- onBeginLifeCycleTimer: function (debugID, timerType) {
- checkDebugID(debugID);
- emitEvent('onBeginLifeCycleTimer', debugID, timerType);
- markBegin(debugID, timerType);
- beginLifeCycleTimer(debugID, timerType);
- },
- onEndLifeCycleTimer: function (debugID, timerType) {
- checkDebugID(debugID);
- endLifeCycleTimer(debugID, timerType);
- markEnd(debugID, timerType);
- emitEvent('onEndLifeCycleTimer', debugID, timerType);
- },
- onBeginProcessingChildContext: function () {
- emitEvent('onBeginProcessingChildContext');
- },
- onEndProcessingChildContext: function () {
- emitEvent('onEndProcessingChildContext');
- },
- onHostOperation: function (operation) {
- checkDebugID(operation.instanceID);
- emitEvent('onHostOperation', operation);
- },
- onSetState: function () {
- emitEvent('onSetState');
- },
- onSetChildren: function (debugID, childDebugIDs) {
- checkDebugID(debugID);
- childDebugIDs.forEach(checkDebugID);
- emitEvent('onSetChildren', debugID, childDebugIDs);
- },
- onBeforeMountComponent: function (debugID, element, parentDebugID) {
- checkDebugID(debugID);
- checkDebugID(parentDebugID, true);
- emitEvent('onBeforeMountComponent', debugID, element, parentDebugID);
- markBegin(debugID, 'mount');
- },
- onMountComponent: function (debugID) {
- checkDebugID(debugID);
- markEnd(debugID, 'mount');
- emitEvent('onMountComponent', debugID);
- },
- onBeforeUpdateComponent: function (debugID, element) {
- checkDebugID(debugID);
- emitEvent('onBeforeUpdateComponent', debugID, element);
- markBegin(debugID, 'update');
- },
- onUpdateComponent: function (debugID) {
- checkDebugID(debugID);
- markEnd(debugID, 'update');
- emitEvent('onUpdateComponent', debugID);
- },
- onBeforeUnmountComponent: function (debugID) {
- checkDebugID(debugID);
- emitEvent('onBeforeUnmountComponent', debugID);
- markBegin(debugID, 'unmount');
- },
- onUnmountComponent: function (debugID) {
- checkDebugID(debugID);
- markEnd(debugID, 'unmount');
- emitEvent('onUnmountComponent', debugID);
- },
- onTestEvent: function () {
- emitEvent('onTestEvent');
- }
- };
-
- // TODO remove these when RN/www gets updated
- ReactDebugTool.addDevtool = ReactDebugTool.addHook;
- ReactDebugTool.removeDevtool = ReactDebugTool.removeHook;
-
- ReactDebugTool.addHook(ReactInvalidSetStateWarningHook);
- ReactDebugTool.addHook(ReactComponentTreeHook);
- var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
- if (/[?&]react_perf\b/.test(url)) {
- ReactDebugTool.beginProfiling();
- }
-
- module.exports = ReactDebugTool;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 356 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2016-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var warning = __webpack_require__(304);
-
- if (process.env.NODE_ENV !== 'production') {
- var processingChildContext = false;
-
- var warnInvalidSetState = function () {
- process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0;
- };
- }
-
- var ReactInvalidSetStateWarningHook = {
- onBeginProcessingChildContext: function () {
- processingChildContext = true;
- },
- onEndProcessingChildContext: function () {
- processingChildContext = false;
- },
- onSetState: function () {
- warnInvalidSetState();
- }
- };
-
- module.exports = ReactInvalidSetStateWarningHook;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 357 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2016-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var history = [];
-
- var ReactHostOperationHistoryHook = {
- onHostOperation: function (operation) {
- history.push(operation);
- },
- clearHistory: function () {
- if (ReactHostOperationHistoryHook._preventClearing) {
- // Should only be used for tests.
- return;
- }
-
- history = [];
- },
- getHistory: function () {
- return history;
- }
- };
-
- module.exports = ReactHostOperationHistoryHook;
-
-/***/ }),
-/* 358 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2016-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(359);
-
- var ReactCurrentOwner = __webpack_require__(360);
-
- var invariant = __webpack_require__(303);
- var warning = __webpack_require__(304);
-
- function isNative(fn) {
- // Based on isNative() from Lodash
- var funcToString = Function.prototype.toString;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var reIsNative = RegExp('^' + funcToString
- // Take an example native function source for comparison
- .call(hasOwnProperty)
- // Strip regex characters so we can use it for regex
- .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
- // Remove hasOwnProperty from the template to make it generic
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
- try {
- var source = funcToString.call(fn);
- return reIsNative.test(source);
- } catch (err) {
- return false;
- }
- }
-
- var canUseCollections =
- // Array.from
- typeof Array.from === 'function' &&
- // Map
- typeof Map === 'function' && isNative(Map) &&
- // Map.prototype.keys
- Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) &&
- // Set
- typeof Set === 'function' && isNative(Set) &&
- // Set.prototype.keys
- Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys);
-
- var setItem;
- var getItem;
- var removeItem;
- var getItemIDs;
- var addRoot;
- var removeRoot;
- var getRootIDs;
-
- if (canUseCollections) {
- var itemMap = new Map();
- var rootIDSet = new Set();
-
- setItem = function (id, item) {
- itemMap.set(id, item);
- };
- getItem = function (id) {
- return itemMap.get(id);
- };
- removeItem = function (id) {
- itemMap['delete'](id);
- };
- getItemIDs = function () {
- return Array.from(itemMap.keys());
- };
-
- addRoot = function (id) {
- rootIDSet.add(id);
- };
- removeRoot = function (id) {
- rootIDSet['delete'](id);
- };
- getRootIDs = function () {
- return Array.from(rootIDSet.keys());
- };
- } else {
- var itemByKey = {};
- var rootByKey = {};
-
- // Use non-numeric keys to prevent V8 performance issues:
- // https://github.com/facebook/react/pull/7232
- var getKeyFromID = function (id) {
- return '.' + id;
- };
- var getIDFromKey = function (key) {
- return parseInt(key.substr(1), 10);
- };
-
- setItem = function (id, item) {
- var key = getKeyFromID(id);
- itemByKey[key] = item;
- };
- getItem = function (id) {
- var key = getKeyFromID(id);
- return itemByKey[key];
- };
- removeItem = function (id) {
- var key = getKeyFromID(id);
- delete itemByKey[key];
- };
- getItemIDs = function () {
- return Object.keys(itemByKey).map(getIDFromKey);
- };
-
- addRoot = function (id) {
- var key = getKeyFromID(id);
- rootByKey[key] = true;
- };
- removeRoot = function (id) {
- var key = getKeyFromID(id);
- delete rootByKey[key];
- };
- getRootIDs = function () {
- return Object.keys(rootByKey).map(getIDFromKey);
- };
- }
-
- var unmountedIDs = [];
-
- function purgeDeep(id) {
- var item = getItem(id);
- if (item) {
- var childIDs = item.childIDs;
-
- removeItem(id);
- childIDs.forEach(purgeDeep);
- }
- }
-
- function describeComponentFrame(name, source, ownerName) {
- return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
- }
-
- function getDisplayName(element) {
- if (element == null) {
- return '#empty';
- } else if (typeof element === 'string' || typeof element === 'number') {
- return '#text';
- } else if (typeof element.type === 'string') {
- return element.type;
- } else {
- return element.type.displayName || element.type.name || 'Unknown';
- }
- }
-
- function describeID(id) {
- var name = ReactComponentTreeHook.getDisplayName(id);
- var element = ReactComponentTreeHook.getElement(id);
- var ownerID = ReactComponentTreeHook.getOwnerID(id);
- var ownerName;
- if (ownerID) {
- ownerName = ReactComponentTreeHook.getDisplayName(ownerID);
- }
- process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
- return describeComponentFrame(name, element && element._source, ownerName);
- }
-
- var ReactComponentTreeHook = {
- onSetChildren: function (id, nextChildIDs) {
- var item = getItem(id);
- !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
- item.childIDs = nextChildIDs;
-
- for (var i = 0; i < nextChildIDs.length; i++) {
- var nextChildID = nextChildIDs[i];
- var nextChild = getItem(nextChildID);
- !nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0;
- !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0;
- !nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
- if (nextChild.parentID == null) {
- nextChild.parentID = id;
- // TODO: This shouldn't be necessary but mounting a new root during in
- // componentWillMount currently causes not-yet-mounted components to
- // be purged from our tree data so their parent id is missing.
- }
- !(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0;
- }
- },
- onBeforeMountComponent: function (id, element, parentID) {
- var item = {
- element: element,
- parentID: parentID,
- text: null,
- childIDs: [],
- isMounted: false,
- updateCount: 0
- };
- setItem(id, item);
- },
- onBeforeUpdateComponent: function (id, element) {
- var item = getItem(id);
- if (!item || !item.isMounted) {
- // We may end up here as a result of setState() in componentWillUnmount().
- // In this case, ignore the element.
- return;
- }
- item.element = element;
- },
- onMountComponent: function (id) {
- var item = getItem(id);
- !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
- item.isMounted = true;
- var isRoot = item.parentID === 0;
- if (isRoot) {
- addRoot(id);
- }
- },
- onUpdateComponent: function (id) {
- var item = getItem(id);
- if (!item || !item.isMounted) {
- // We may end up here as a result of setState() in componentWillUnmount().
- // In this case, ignore the element.
- return;
- }
- item.updateCount++;
- },
- onUnmountComponent: function (id) {
- var item = getItem(id);
- if (item) {
- // We need to check if it exists.
- // `item` might not exist if it is inside an error boundary, and a sibling
- // error boundary child threw while mounting. Then this instance never
- // got a chance to mount, but it still gets an unmounting event during
- // the error boundary cleanup.
- item.isMounted = false;
- var isRoot = item.parentID === 0;
- if (isRoot) {
- removeRoot(id);
- }
- }
- unmountedIDs.push(id);
- },
- purgeUnmountedComponents: function () {
- if (ReactComponentTreeHook._preventPurging) {
- // Should only be used for testing.
- return;
- }
-
- for (var i = 0; i < unmountedIDs.length; i++) {
- var id = unmountedIDs[i];
- purgeDeep(id);
- }
- unmountedIDs.length = 0;
- },
- isMounted: function (id) {
- var item = getItem(id);
- return item ? item.isMounted : false;
- },
- getCurrentStackAddendum: function (topElement) {
- var info = '';
- if (topElement) {
- var name = getDisplayName(topElement);
- var owner = topElement._owner;
- info += describeComponentFrame(name, topElement._source, owner && owner.getName());
- }
-
- var currentOwner = ReactCurrentOwner.current;
- var id = currentOwner && currentOwner._debugID;
-
- info += ReactComponentTreeHook.getStackAddendumByID(id);
- return info;
- },
- getStackAddendumByID: function (id) {
- var info = '';
- while (id) {
- info += describeID(id);
- id = ReactComponentTreeHook.getParentID(id);
- }
- return info;
- },
- getChildIDs: function (id) {
- var item = getItem(id);
- return item ? item.childIDs : [];
- },
- getDisplayName: function (id) {
- var element = ReactComponentTreeHook.getElement(id);
- if (!element) {
- return null;
- }
- return getDisplayName(element);
- },
- getElement: function (id) {
- var item = getItem(id);
- return item ? item.element : null;
- },
- getOwnerID: function (id) {
- var element = ReactComponentTreeHook.getElement(id);
- if (!element || !element._owner) {
- return null;
- }
- return element._owner._debugID;
- },
- getParentID: function (id) {
- var item = getItem(id);
- return item ? item.parentID : null;
- },
- getSource: function (id) {
- var item = getItem(id);
- var element = item ? item.element : null;
- var source = element != null ? element._source : null;
- return source;
- },
- getText: function (id) {
- var element = ReactComponentTreeHook.getElement(id);
- if (typeof element === 'string') {
- return element;
- } else if (typeof element === 'number') {
- return '' + element;
- } else {
- return null;
- }
- },
- getUpdateCount: function (id) {
- var item = getItem(id);
- return item ? item.updateCount : 0;
- },
-
-
- getRootIDs: getRootIDs,
- getRegisteredIDs: getItemIDs
- };
-
- module.exports = ReactComponentTreeHook;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 359 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
- 'use strict';
-
- /**
- * WARNING: DO NOT manually require this module.
- * This is a replacement for `invariant(...)` used by the error code system
- * and will _only_ be required by the corresponding babel pass.
- * It always throws.
- */
-
- function reactProdInvariant(code) {
- var argCount = arguments.length - 1;
-
- var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
-
- for (var argIdx = 0; argIdx < argCount; argIdx++) {
- message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
- }
-
- message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
-
- var error = new Error(message);
- error.name = 'Invariant Violation';
- error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
-
- throw error;
- }
-
- module.exports = reactProdInvariant;
-
-/***/ }),
-/* 360 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- /**
- * Keeps track of the current owner.
- *
- * The current owner is the component who should own any components that are
- * currently being constructed.
- */
- var ReactCurrentOwner = {
-
- /**
- * @internal
- * @type {ReactComponent}
- */
- current: null
-
- };
-
- module.exports = ReactCurrentOwner;
-
-/***/ }),
-/* 361 */
-/***/ (function(module, exports, __webpack_require__) {
-
- 'use strict';
-
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @typechecks
- */
-
- var performance = __webpack_require__(362);
-
- var performanceNow;
-
- /**
- * Detect if we can use `window.performance.now()` and gracefully fallback to
- * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
- * because of Facebook's testing infrastructure.
- */
- if (performance.now) {
- performanceNow = function performanceNow() {
- return performance.now();
- };
- } else {
- performanceNow = function performanceNow() {
- return Date.now();
- };
- }
-
- module.exports = performanceNow;
-
-/***/ }),
-/* 362 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @typechecks
- */
-
- 'use strict';
-
- var ExecutionEnvironment = __webpack_require__(337);
-
- var performance;
-
- if (ExecutionEnvironment.canUseDOM) {
- performance = window.performance || window.msPerformance || window.webkitPerformance;
- }
-
- module.exports = performance || {};
-
-/***/ }),
-/* 363 */
-/***/ (function(module, exports, __webpack_require__) {
-
- /* WEBPACK VAR INJECTION */(function(process) {/**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- *
- */
-
- 'use strict';
-
- var _prodInvariant = __webpack_require__(331);
-
- var invariant = __webpack_require__(303);
-
- var OBSERVED_ERROR = {};
-
- /**
- * `Transaction` creates a black box that is able to wrap any method such that
- * certain invariants are maintained before and after the method is invoked
- * (Even if an exception is thrown while invoking the wrapped method). Whoever
- * instantiates a transaction can provide enforcers of the invariants at
- * creation time. The `Transaction` class itself will supply one additional
- * automatic invariant for you - the invariant that any transaction instance
- * should not be run while it is already being run. You would typically create a
- * single instance of a `Transaction` for reuse multiple times, that potentially
- * is used to wrap several different methods. Wrappers are extremely simple -
- * they only require implementing two methods.
- *
- *
- *
- * Use cases:
- * - Preserving the input selection ranges before/after reconciliation.
- * Restoring selection even in the event of an unexpected error.
- * - Deactivating events while rearranging the DOM, preventing blurs/focuses,
- * while guaranteeing that afterwards, the event system is reactivated.
- * - Flushing a queue of collected DOM mutations to the main UI thread after a
- * reconciliation takes place in a worker thread.
- * - Invoking any collected `componentDidUpdate` callbacks after rendering new
- * content.
- * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
- * to preserve the `scrollTop` (an automatic scroll aware DOM).
- * - (Future use case): Layout calculations before and after DOM updates.
- *
- * Transactional plugin API:
- * - A module that has an `initialize` method that returns any precomputation.
- * - and a `close` method that accepts the precomputation. `close` is invoked
- * when the wrapped process is completed, or has failed.
- *
- * @param {Array} transactionWrapper Wrapper modules
- * that implement `initialize` and `close`.
- * @return {Transaction} Single transaction for reuse in thread.
- *
- * @class Transaction
- */
- var TransactionImpl = {
- /**
- * Sets up this instance so that it is prepared for collecting metrics. Does
- * so such that this setup method may be used on an instance that is already
- * initialized, in a way that does not consume additional memory upon reuse.
- * That can be useful if you decide to make your subclass of this mixin a
- * "PooledClass".
- */
- reinitializeTransaction: function () {
- this.transactionWrappers = this.getTransactionWrappers();
- if (this.wrapperInitData) {
- this.wrapperInitData.length = 0;
- } else {
- this.wrapperInitData = [];
- }
- this._isInTransaction = false;
- },
-
- _isInTransaction: false,
-
- /**
- * @abstract
- * @return {Array} Array of transaction wrappers.
- */
- getTransactionWrappers: null,
-
- isInTransaction: function () {
- return !!this._isInTransaction;
- },
-
- /**
- * Executes the function within a safety window. Use this for the top level
- * methods that result in large amounts of computation/mutations that would
- * need to be safety checked. The optional arguments helps prevent the need
- * to bind in many cases.
- *
- * @param {function} method Member of scope to call.
- * @param {Object} scope Scope to invoke from.
- * @param {Object?=} a Argument to pass to the method.
- * @param {Object?=} b Argument to pass to the method.
- * @param {Object?=} c Argument to pass to the method.
- * @param {Object?=} d Argument to pass to the method.
- * @param {Object?=} e Argument to pass to the method.
- * @param {Object?=} f Argument to pass to the method.
- *
- * @return {*} Return value from `method`.
- */
- perform: function (method, scope, a, b, c, d, e, f) {
- !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0;
- var errorThrown;
- var ret;
- try {
- this._isInTransaction = true;
- // Catching errors makes debugging more difficult, so we start with
- // errorThrown set to true before setting it to false after calling
- // close -- if it's still set to true in the finally block, it means
- // one of these calls threw.
- errorThrown = true;
- this.initializeAll(0);
- ret = method.call(scope, a, b, c, d, e, f);
- errorThrown = false;
- } finally {
- try {
- if (errorThrown) {
- // If `method` throws, prefer to show that stack trace over any thrown
- // by invoking `closeAll`.
- try {
- this.closeAll(0);
- } catch (err) {}
- } else {
- // Since `method` didn't throw, we don't want to silence the exception
- // here.
- this.closeAll(0);
- }
- } finally {
- this._isInTransaction = false;
- }
- }
- return ret;
- },
-
- initializeAll: function (startIndex) {
- var transactionWrappers = this.transactionWrappers;
- for (var i = startIndex; i < transactionWrappers.length; i++) {
- var wrapper = transactionWrappers[i];
- try {
- // Catching errors makes debugging more difficult, so we start with the
- // OBSERVED_ERROR state before overwriting it with the real return value
- // of initialize -- if it's still set to OBSERVED_ERROR in the finally
- // block, it means wrapper.initialize threw.
- this.wrapperInitData[i] = OBSERVED_ERROR;
- this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
- } finally {
- if (this.wrapperInitData[i] === OBSERVED_ERROR) {
- // The initializer for wrapper i threw an error; initialize the
- // remaining wrappers but silence any exceptions from them to ensure
- // that the first error is the one to bubble up.
- try {
- this.initializeAll(i + 1);
- } catch (err) {}
- }
- }
- }
- },
-
- /**
- * Invokes each of `this.transactionWrappers.close[i]` functions, passing into
- * them the respective return values of `this.transactionWrappers.init[i]`
- * (`close`rs that correspond to initializers that failed will not be
- * invoked).
- */
- closeAll: function (startIndex) {
- !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0;
- var transactionWrappers = this.transactionWrappers;
- for (var i = startIndex; i < transactionWrappers.length; i++) {
- var wrapper = transactionWrappers[i];
- var initData = this.wrapperInitData[i];
- var errorThrown;
- try {
- // Catching errors makes debugging more difficult, so we start with
- // errorThrown set to true before setting it to false after calling
- // close -- if it's still set to true in the finally block, it means
- // wrapper.close threw.
- errorThrown = true;
- if (initData !== OBSERVED_ERROR && wrapper.close) {
- wrapper.close.call(this, initData);
- }
- errorThrown = false;
- } finally {
- if (errorThrown) {
- // The closer for wrapper i threw an error; close the remaining
- // wrappers but silence any exceptions from them to ensure that the
- // first error is the one to bubble up.
- try {
- this.closeAll(i + 1);
- } catch (e) {}
- }
- }
- }
- this.wrapperInitData.length = 0;
- }
- };
-
- module.exports = TransactionImpl;
- /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300)))
-
-/***/ }),
-/* 364 */
-/***/ (function(module, exports) {
-
- /**
- * Copyright 2013-present, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- */
-
- 'use strict';
-
- /**
- * Gets the target node from a native browser event by accounting for
- * inconsistencies in browser DOM APIs.
- *
- * @param {object} nativeEvent Native browser event.
- * @return {DOMEventTarget} Target node.
- */
-
- function getEventTarget(nativeEvent) {
- var target = nativeEvent.target || nativeEvent.srcElement || window;
-
- // Normalize SVG