From e5d845d07bef3e9b1508f88c397db065fbe86b8c Mon Sep 17 00:00:00 2001 From: Ricky Vetter Date: Sun, 3 Jun 2018 13:04:34 -0700 Subject: [PATCH] prod build/remove logs --- bsconfig.json | 2 +- docs/Popup.bundle.js | 41851 +---------------------------- src/extension/common/protocol.re | 7 +- src/refmt/refmt2.re | 2 - yarn.lock | 8 +- 5 files changed, 13 insertions(+), 41857 deletions(-) diff --git a/bsconfig.json b/bsconfig.json index b5e0454..06dad29 100644 --- a/bsconfig.json +++ b/bsconfig.json @@ -3,7 +3,7 @@ "name" : "reason-tools", "version": "0.0.0", "reason" : {"react-jsx" : 2}, - "bs-dependencies": ["reason-react"], + "bs-dependencies": ["reason-react", "bs-result"], "sources": { "dir": "src", "subdirs": [ diff --git a/docs/Popup.bundle.js b/docs/Popup.bundle.js index 8c572ed..16f81ef 100644 --- a/docs/Popup.bundle.js +++ b/docs/Popup.bundle.js @@ -1,39055 +1,9 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 37); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export out_of_memory */ -/* unused harmony export sys_error */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return failure; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return invalid_argument; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return end_of_file; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return division_by_zero; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return not_found; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return match_failure; }); -/* unused harmony export stack_overflow */ -/* unused harmony export sys_blocked_io */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return assert_failure; }); -/* unused harmony export undefined_recursive_module */ - - - -var out_of_memory = /* tuple */[ - "Out_of_memory", - 0 -]; - -var sys_error = /* tuple */[ - "Sys_error", - -1 -]; - -var failure = /* tuple */[ - "Failure", - -2 -]; - -var invalid_argument = /* tuple */[ - "Invalid_argument", - -3 -]; - -var end_of_file = /* tuple */[ - "End_of_file", - -4 -]; - -var division_by_zero = /* tuple */[ - "Division_by_zero", - -5 -]; - -var not_found = /* tuple */[ - "Not_found", - -6 -]; - -var match_failure = /* tuple */[ - "Match_failure", - -7 -]; - -var stack_overflow = /* tuple */[ - "Stack_overflow", - -8 -]; - -var sys_blocked_io = /* tuple */[ - "Sys_blocked_io", - -9 -]; - -var assert_failure = /* tuple */[ - "Assert_failure", - -10 -]; - -var undefined_recursive_module = /* tuple */[ - "Undefined_recursive_module", - -11 -]; - -out_of_memory.tag = 248; - -sys_error.tag = 248; - -failure.tag = 248; - -invalid_argument.tag = 248; - -end_of_file.tag = 248; - -division_by_zero.tag = 248; - -not_found.tag = 248; - -match_failure.tag = 248; - -stack_overflow.tag = 248; - -sys_blocked_io.tag = 248; - -assert_failure.tag = 248; - -undefined_recursive_module.tag = 248; - - -/* Not a pure module */ - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export app */ -/* unused harmony export curry_1 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _1; }); -/* unused harmony export __1 */ -/* unused harmony export curry_2 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return _2; }); -/* unused harmony export __2 */ -/* unused harmony export curry_3 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _3; }); -/* unused harmony export __3 */ -/* unused harmony export curry_4 */ -/* unused harmony export _4 */ -/* unused harmony export __4 */ -/* unused harmony export curry_5 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return _5; }); -/* unused harmony export __5 */ -/* unused harmony export curry_6 */ -/* unused harmony export _6 */ -/* unused harmony export __6 */ -/* unused harmony export curry_7 */ -/* unused harmony export _7 */ -/* unused harmony export __7 */ -/* unused harmony export curry_8 */ -/* unused harmony export _8 */ -/* unused harmony export __8 */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_array_js__ = __webpack_require__(19); - - - - -function app(_f, _args) { - while(true) { - var args = _args; - var f = _f; - var arity = f.length; - var arity$1 = arity === 0 ? 1 : arity; - var len = args.length; - var d = arity$1 - len | 0; - if (d === 0) { - return f.apply(null, args); - } else if (d < 0) { - _args = __WEBPACK_IMPORTED_MODULE_0__caml_array_js__["a" /* caml_array_sub */](args, arity$1, -d | 0); - _f = f.apply(null, __WEBPACK_IMPORTED_MODULE_0__caml_array_js__["a" /* caml_array_sub */](args, 0, arity$1)); - continue ; - - } else { - return (function(f,args){ - return function (x) { - return app(f, args.concat(/* array */[x])); - } - }(f,args)); - } - }; -} - -function curry_1(o, a0, arity) { - if (arity > 7 || arity < 0) { - return app(o, /* array */[a0]); - } else { - switch (arity) { - case 0 : - case 1 : - return o(a0); - case 2 : - return (function (param) { - return o(a0, param); - }); - case 3 : - return (function (param, param$1) { - return o(a0, param, param$1); - }); - case 4 : - return (function (param, param$1, param$2) { - return o(a0, param, param$1, param$2); - }); - case 5 : - return (function (param, param$1, param$2, param$3) { - return o(a0, param, param$1, param$2, param$3); - }); - case 6 : - return (function (param, param$1, param$2, param$3, param$4) { - return o(a0, param, param$1, param$2, param$3, param$4); - }); - case 7 : - return (function (param, param$1, param$2, param$3, param$4, param$5) { - return o(a0, param, param$1, param$2, param$3, param$4, param$5); - }); - - } - } -} - -function _1(o, a0) { - var arity = o.length; - if (arity === 1) { - return o(a0); - } else { - return curry_1(o, a0, arity); - } -} - -function __1(o) { - var arity = o.length; - if (arity === 1) { - return o; - } else { - return (function (a0) { - return _1(o, a0); - }); - } -} - -function curry_2(o, a0, a1, arity) { - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - return app(o(a0), /* array */[a1]); - case 2 : - return o(a0, a1); - case 3 : - return (function (param) { - return o(a0, a1, param); - }); - case 4 : - return (function (param, param$1) { - return o(a0, a1, param, param$1); - }); - case 5 : - return (function (param, param$1, param$2) { - return o(a0, a1, param, param$1, param$2); - }); - case 6 : - return (function (param, param$1, param$2, param$3) { - return o(a0, a1, param, param$1, param$2, param$3); - }); - case 7 : - return (function (param, param$1, param$2, param$3, param$4) { - return o(a0, a1, param, param$1, param$2, param$3, param$4); - }); - - } - } -} - -function _2(o, a0, a1) { - var arity = o.length; - if (arity === 2) { - return o(a0, a1); - } else { - return curry_2(o, a0, a1, arity); - } -} - -function __2(o) { - var arity = o.length; - if (arity === 2) { - return o; - } else { - return (function (a0, a1) { - return _2(o, a0, a1); - }); - } -} - -function curry_3(o, a0, a1, a2, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[a2]); - case 3 : - return o(a0, a1, a2); - case 4 : - return (function (param) { - return o(a0, a1, a2, param); - }); - case 5 : - return (function (param, param$1) { - return o(a0, a1, a2, param, param$1); - }); - case 6 : - return (function (param, param$1, param$2) { - return o(a0, a1, a2, param, param$1, param$2); - }); - case 7 : - return (function (param, param$1, param$2, param$3) { - return o(a0, a1, a2, param, param$1, param$2, param$3); - }); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2 - ]); - } - -} - -function _3(o, a0, a1, a2) { - var arity = o.length; - if (arity === 3) { - return o(a0, a1, a2); - } else { - return curry_3(o, a0, a1, a2, arity); - } -} - -function __3(o) { - var arity = o.length; - if (arity === 3) { - return o; - } else { - return (function (a0, a1, a2) { - return _3(o, a0, a1, a2); - }); - } -} - -function curry_4(o, a0, a1, a2, a3, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2, - a3 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[ - a2, - a3 - ]); - case 3 : - return app(o(a0, a1, a2), /* array */[a3]); - case 4 : - return o(a0, a1, a2, a3); - case 5 : - return (function (param) { - return o(a0, a1, a2, a3, param); - }); - case 6 : - return (function (param, param$1) { - return o(a0, a1, a2, a3, param, param$1); - }); - case 7 : - return (function (param, param$1, param$2) { - return o(a0, a1, a2, a3, param, param$1, param$2); - }); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2, - a3 - ]); - } - -} - -function _4(o, a0, a1, a2, a3) { - var arity = o.length; - if (arity === 4) { - return o(a0, a1, a2, a3); - } else { - return curry_4(o, a0, a1, a2, a3, arity); - } -} - -function __4(o) { - var arity = o.length; - if (arity === 4) { - return o; - } else { - return (function (a0, a1, a2, a3) { - return _4(o, a0, a1, a2, a3); - }); - } -} - -function curry_5(o, a0, a1, a2, a3, a4, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2, - a3, - a4 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[ - a2, - a3, - a4 - ]); - case 3 : - return app(o(a0, a1, a2), /* array */[ - a3, - a4 - ]); - case 4 : - return app(o(a0, a1, a2, a3), /* array */[a4]); - case 5 : - return o(a0, a1, a2, a3, a4); - case 6 : - return (function (param) { - return o(a0, a1, a2, a3, a4, param); - }); - case 7 : - return (function (param, param$1) { - return o(a0, a1, a2, a3, a4, param, param$1); - }); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2, - a3, - a4 - ]); - } - -} - -function _5(o, a0, a1, a2, a3, a4) { - var arity = o.length; - if (arity === 5) { - return o(a0, a1, a2, a3, a4); - } else { - return curry_5(o, a0, a1, a2, a3, a4, arity); - } -} - -function __5(o) { - var arity = o.length; - if (arity === 5) { - return o; - } else { - return (function (a0, a1, a2, a3, a4) { - return _5(o, a0, a1, a2, a3, a4); - }); - } -} - -function curry_6(o, a0, a1, a2, a3, a4, a5, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2, - a3, - a4, - a5 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[ - a2, - a3, - a4, - a5 - ]); - case 3 : - return app(o(a0, a1, a2), /* array */[ - a3, - a4, - a5 - ]); - case 4 : - return app(o(a0, a1, a2, a3), /* array */[ - a4, - a5 - ]); - case 5 : - return app(o(a0, a1, a2, a3, a4), /* array */[a5]); - case 6 : - return o(a0, a1, a2, a3, a4, a5); - case 7 : - return (function (param) { - return o(a0, a1, a2, a3, a4, a5, param); - }); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2, - a3, - a4, - a5 - ]); - } - -} - -function _6(o, a0, a1, a2, a3, a4, a5) { - var arity = o.length; - if (arity === 6) { - return o(a0, a1, a2, a3, a4, a5); - } else { - return curry_6(o, a0, a1, a2, a3, a4, a5, arity); - } -} - -function __6(o) { - var arity = o.length; - if (arity === 6) { - return o; - } else { - return (function (a0, a1, a2, a3, a4, a5) { - return _6(o, a0, a1, a2, a3, a4, a5); - }); - } -} - -function curry_7(o, a0, a1, a2, a3, a4, a5, a6, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2, - a3, - a4, - a5, - a6 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[ - a2, - a3, - a4, - a5, - a6 - ]); - case 3 : - return app(o(a0, a1, a2), /* array */[ - a3, - a4, - a5, - a6 - ]); - case 4 : - return app(o(a0, a1, a2, a3), /* array */[ - a4, - a5, - a6 - ]); - case 5 : - return app(o(a0, a1, a2, a3, a4), /* array */[ - a5, - a6 - ]); - case 6 : - return app(o(a0, a1, a2, a3, a4, a5), /* array */[a6]); - case 7 : - return o(a0, a1, a2, a3, a4, a5, a6); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2, - a3, - a4, - a5, - a6 - ]); - } - -} - -function _7(o, a0, a1, a2, a3, a4, a5, a6) { - var arity = o.length; - if (arity === 7) { - return o(a0, a1, a2, a3, a4, a5, a6); - } else { - return curry_7(o, a0, a1, a2, a3, a4, a5, a6, arity); - } -} - -function __7(o) { - var arity = o.length; - if (arity === 7) { - return o; - } else { - return (function (a0, a1, a2, a3, a4, a5, a6) { - return _7(o, a0, a1, a2, a3, a4, a5, a6); - }); - } -} - -function curry_8(o, a0, a1, a2, a3, a4, a5, a6, a7, arity) { - var exit = 0; - if (arity > 7 || arity < 0) { - return app(o, /* array */[ - a0, - a1, - a2, - a3, - a4, - a5, - a6, - a7 - ]); - } else { - switch (arity) { - case 0 : - case 1 : - exit = 1; - break; - case 2 : - return app(o(a0, a1), /* array */[ - a2, - a3, - a4, - a5, - a6, - a7 - ]); - case 3 : - return app(o(a0, a1, a2), /* array */[ - a3, - a4, - a5, - a6, - a7 - ]); - case 4 : - return app(o(a0, a1, a2, a3), /* array */[ - a4, - a5, - a6, - a7 - ]); - case 5 : - return app(o(a0, a1, a2, a3, a4), /* array */[ - a5, - a6, - a7 - ]); - case 6 : - return app(o(a0, a1, a2, a3, a4, a5), /* array */[ - a6, - a7 - ]); - case 7 : - return app(o(a0, a1, a2, a3, a4, a5, a6), /* array */[a7]); - - } - } - if (exit === 1) { - return app(o(a0), /* array */[ - a1, - a2, - a3, - a4, - a5, - a6, - a7 - ]); - } - -} - -function _8(o, a0, a1, a2, a3, a4, a5, a6, a7) { - var arity = o.length; - if (arity === 8) { - return o(a0, a1, a2, a3, a4, a5, a6, a7); - } else { - return curry_8(o, a0, a1, a2, a3, a4, a5, a6, a7, arity); - } -} - -function __8(o) { - var arity = o.length; - if (arity === 8) { - return o; - } else { - return (function (a0, a1, a2, a3, a4, a5, a6, a7) { - return _8(o, a0, a1, a2, a3, a4, a5, a6, a7); - }); - } -} - - -/* No side effect */ - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { - -if (process.env.NODE_ENV === 'production') { - module.exports = __webpack_require__(83); -} else { - module.exports = __webpack_require__(82); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export Callback */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return statelessComponent; }); -/* unused harmony export statelessComponentWithRetainedProps */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return reducerComponent; }); -/* unused harmony export reducerComponentWithRetainedProps */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return element; }); -/* unused harmony export wrapReasonForJs */ -/* unused harmony export createDomElement */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return wrapJsForReason; }); -/* unused harmony export Router */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_bs_platform_lib_es6_caml_builtin_exceptions_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__ReasonReactOptimizedCreateClass_js__ = __webpack_require__(85); - - - - - - - - -function createDomElement(s, props, children) { - var vararg = /* array */[ - s, - props - ].concat(children); - return __WEBPACK_IMPORTED_MODULE_2_react__["createElement"].apply(null, vararg); -} - -var magicNull = null; - -function $$default() { - return /* () */0; -} - -function chain(handlerOne, handlerTwo, payload) { - __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](handlerOne, payload); - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](handlerTwo, payload); -} - -var Callback = /* module */[ - /* default */$$default, - /* chain */chain -]; - -function lifecycleNoUpdate() { - return /* NoUpdate */0; -} - -function lifecyclePreviousNextUnit() { - return /* () */0; -} - -function lifecyclePreviousCurrentReturnUnit() { - return /* () */0; -} - -function lifecycleReturnUnit() { - return /* () */0; -} - -function lifecycleReturnTrue() { - return /* true */1; -} - -function willReceivePropsDefault(param) { - return param[/* state */2]; -} - -function renderDefault() { - return "RenderNotImplemented"; -} - -function initialStateDefault() { - return /* () */0; -} - -function reducerDefault(_, _$1) { - return /* NoUpdate */0; -} - -function subscriptionsDefault() { - return /* [] */0; -} - -function convertPropsIfTheyreFromJs(props, jsPropsToReason, debugName) { - var match = props.reasonProps; - if (match == null) { - if (jsPropsToReason) { - return /* Element */[__WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](jsPropsToReason[0], props)]; - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3_bs_platform_lib_es6_caml_builtin_exceptions_js__["a" /* invalid_argument */], - "A JS component called the Reason component " + (debugName + " which didn't implement the JS->Reason React props conversion.") - ]; - } - } else { - return match; - } -} - -function createClass(debugName) { - return __WEBPACK_IMPORTED_MODULE_4__ReasonReactOptimizedCreateClass_js__["a" /* createClass */]({ - displayName: debugName, - subscriptions: null, - self: (function (state, retainedProps) { - var $$this = this ; - return /* record */[ - /* handle */$$this.handleMethod, - /* reduce */$$this.reduceMethod, - /* state */state, - /* retainedProps */retainedProps, - /* send */$$this.sendMethod - ]; - }), - transitionNextTotalState: (function (curTotalState, reasonStateUpdate) { - if (typeof reasonStateUpdate === "number") { - return curTotalState; - } else { - switch (reasonStateUpdate.tag | 0) { - case 0 : - return { - reasonState: reasonStateUpdate[0], - reasonStateVersion: curTotalState.reasonStateVersion + 1 | 0, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements, - sideEffects: curTotalState.sideEffects - }; - case 1 : - return { - reasonState: reasonStateUpdate[0], - reasonStateVersion: curTotalState.reasonStateVersion + 1 | 0, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements + 1 | 0, - sideEffects: curTotalState.sideEffects - }; - case 2 : - return { - reasonState: curTotalState.reasonState, - reasonStateVersion: curTotalState.reasonStateVersion + 1 | 0, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements + 1 | 0, - sideEffects: /* :: */[ - reasonStateUpdate[0], - curTotalState.sideEffects - ] - }; - case 3 : - return { - reasonState: reasonStateUpdate[0], - reasonStateVersion: curTotalState.reasonStateVersion + 1 | 0, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements, - sideEffects: /* :: */[ - reasonStateUpdate[1], - curTotalState.sideEffects - ] - }; - case 4 : - return { - reasonState: reasonStateUpdate[0], - reasonStateVersion: curTotalState.reasonStateVersion + 1 | 0, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements + 1 | 0, - sideEffects: /* :: */[ - reasonStateUpdate[1], - curTotalState.sideEffects - ] - }; - - } - } - }), - getInitialState: (function () { - var thisJs = (this); - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var initialReasonState = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](convertedReasonProps[0][/* initialState */10], /* () */0); - return { - reasonState: initialReasonState, - reasonStateVersion: 1, - reasonStateVersionUsedToComputeSubelements: 1, - sideEffects: /* [] */0 - }; - }), - componentDidMount: (function () { - var $$this = this ; - var thisJs = (this); - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var component = convertedReasonProps[0]; - var curTotalState = thisJs.state; - var curReasonState = curTotalState.reasonState; - var self = $$this.self(curReasonState, component[/* retainedProps */11]); - if (component[/* subscriptions */13] !== subscriptionsDefault) { - var subscriptions = __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["a" /* map */]((function (param) { - var unsubscribe = param[1]; - var token = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](param[0], /* () */0); - return (function () { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](unsubscribe, token); - }); - }), __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](component[/* subscriptions */13], self)); - $$this.subscriptions = subscriptions; - } - if (component[/* didMount */4] !== lifecycleNoUpdate) { - var reasonStateUpdate = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](component[/* didMount */4], self); - var nextTotalState = $$this.transitionNextTotalState(curTotalState, reasonStateUpdate); - if (nextTotalState.reasonStateVersion !== curTotalState.reasonStateVersion) { - return thisJs.setState(nextTotalState); - } else { - return 0; - } - } else { - return 0; - } - }), - componentDidUpdate: (function (prevProps, prevState) { - var $$this = this ; - var thisJs = (this); - var curState = thisJs.state; - var curReasonState = curState.reasonState; - var newJsProps = thisJs.props; - var newConvertedReasonProps = convertPropsIfTheyreFromJs(newJsProps, thisJs.jsPropsToReason, debugName); - var newComponent = newConvertedReasonProps[0]; - if (newComponent[/* didUpdate */5] !== lifecyclePreviousCurrentReturnUnit) { - var match = +(prevProps === newJsProps); - var oldConvertedReasonProps = match !== 0 ? newConvertedReasonProps : convertPropsIfTheyreFromJs(prevProps, thisJs.jsPropsToReason, debugName); - var prevReasonState = prevState.reasonState; - var newSelf = $$this.self(curReasonState, newComponent[/* retainedProps */11]); - var oldSelf_000 = /* handle */newSelf[/* handle */0]; - var oldSelf_001 = /* reduce */newSelf[/* reduce */1]; - var oldSelf_003 = /* retainedProps */oldConvertedReasonProps[0][/* retainedProps */11]; - var oldSelf_004 = /* send */newSelf[/* send */4]; - var oldSelf = /* record */[ - oldSelf_000, - oldSelf_001, - /* state */prevReasonState, - oldSelf_003, - oldSelf_004 - ]; - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](newComponent[/* didUpdate */5], /* record */[ - /* oldSelf */oldSelf, - /* newSelf */newSelf - ]); - } else { - return 0; - } - }), - componentWillUnmount: (function () { - var $$this = this ; - var thisJs = (this); - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var component = convertedReasonProps[0]; - var curState = thisJs.state; - var curReasonState = curState.reasonState; - if (component[/* willUnmount */6] !== lifecycleReturnUnit) { - __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](component[/* willUnmount */6], $$this.self(curReasonState, component[/* retainedProps */11])); - } - var match = $$this.subscriptions; - if (match == null) { - return /* () */0; - } else { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["b" /* iter */]((function (unsubscribe) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](unsubscribe, /* () */0); - }), __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["c" /* rev */](match)); - } - }), - componentWillUpdate: (function (nextProps, nextState) { - var $$this = this ; - var thisJs = (this); - var newConvertedReasonProps = convertPropsIfTheyreFromJs(nextProps, thisJs.jsPropsToReason, debugName); - var newComponent = newConvertedReasonProps[0]; - if (newComponent[/* willUpdate */7] !== lifecyclePreviousNextUnit) { - var oldJsProps = thisJs.props; - var match = +(nextProps === oldJsProps); - var oldConvertedReasonProps = match !== 0 ? newConvertedReasonProps : convertPropsIfTheyreFromJs(oldJsProps, thisJs.jsPropsToReason, debugName); - var curState = thisJs.state; - var curReasonState = curState.reasonState; - var nextReasonState = nextState.reasonState; - var newSelf = $$this.self(nextReasonState, newComponent[/* retainedProps */11]); - var oldSelf_000 = /* handle */newSelf[/* handle */0]; - var oldSelf_001 = /* reduce */newSelf[/* reduce */1]; - var oldSelf_003 = /* retainedProps */oldConvertedReasonProps[0][/* retainedProps */11]; - var oldSelf_004 = /* send */newSelf[/* send */4]; - var oldSelf = /* record */[ - oldSelf_000, - oldSelf_001, - /* state */curReasonState, - oldSelf_003, - oldSelf_004 - ]; - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](newComponent[/* willUpdate */7], /* record */[ - /* oldSelf */oldSelf, - /* newSelf */newSelf - ]); - } else { - return 0; - } - }), - componentWillReceiveProps: (function (nextProps) { - var $$this = this ; - var thisJs = (this); - var newConvertedReasonProps = convertPropsIfTheyreFromJs(nextProps, thisJs.jsPropsToReason, debugName); - var newComponent = newConvertedReasonProps[0]; - if (newComponent[/* willReceiveProps */3] !== willReceivePropsDefault) { - var oldJsProps = thisJs.props; - var match = +(nextProps === oldJsProps); - var oldConvertedReasonProps = match !== 0 ? newConvertedReasonProps : convertPropsIfTheyreFromJs(oldJsProps, thisJs.jsPropsToReason, debugName); - var oldComponent = oldConvertedReasonProps[0]; - return thisJs.setState((function (curTotalState, _) { - var curReasonState = curTotalState.reasonState; - var curReasonStateVersion = curTotalState.reasonStateVersion; - var oldSelf = $$this.self(curReasonState, oldComponent[/* retainedProps */11]); - var nextReasonState = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](newComponent[/* willReceiveProps */3], oldSelf); - var match = +(nextReasonState !== curReasonState); - var nextReasonStateVersion = match !== 0 ? curReasonStateVersion + 1 | 0 : curReasonStateVersion; - if (nextReasonStateVersion !== curReasonStateVersion) { - return { - reasonState: nextReasonState, - reasonStateVersion: nextReasonStateVersion, - reasonStateVersionUsedToComputeSubelements: curTotalState.reasonStateVersionUsedToComputeSubelements, - sideEffects: nextReasonState.sideEffects - }; - } else { - return curTotalState; - } - })); - } else { - return 0; - } - }), - shouldComponentUpdate: (function (nextJsProps, nextState, _) { - var $$this = this ; - var thisJs = (this); - var curJsProps = thisJs.props; - var propsWarrantRerender = +(nextJsProps !== curJsProps); - var oldConvertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var match = +(nextJsProps === curJsProps); - var newConvertedReasonProps = match !== 0 ? oldConvertedReasonProps : convertPropsIfTheyreFromJs(nextJsProps, thisJs.jsPropsToReason, debugName); - var newComponent = newConvertedReasonProps[0]; - var nextReasonStateVersion = nextState.reasonStateVersion; - var nextReasonStateVersionUsedToComputeSubelements = nextState.reasonStateVersionUsedToComputeSubelements; - var stateChangeWarrantsComputingSubelements = +(nextReasonStateVersionUsedToComputeSubelements !== nextReasonStateVersion); - var warrantsUpdate = propsWarrantRerender || stateChangeWarrantsComputingSubelements; - var nextReasonState = nextState.reasonState; - var newSelf = $$this.self(nextReasonState, newComponent[/* retainedProps */11]); - var ret; - if (warrantsUpdate && newComponent[/* shouldUpdate */8] !== lifecycleReturnTrue) { - var curState = thisJs.state; - var curReasonState = curState.reasonState; - var oldSelf_000 = /* handle */newSelf[/* handle */0]; - var oldSelf_001 = /* reduce */newSelf[/* reduce */1]; - var oldSelf_003 = /* retainedProps */oldConvertedReasonProps[0][/* retainedProps */11]; - var oldSelf_004 = /* send */newSelf[/* send */4]; - var oldSelf = /* record */[ - oldSelf_000, - oldSelf_001, - /* state */curReasonState, - oldSelf_003, - oldSelf_004 - ]; - ret = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](newComponent[/* shouldUpdate */8], /* record */[ - /* oldSelf */oldSelf, - /* newSelf */newSelf - ]); - } else { - ret = warrantsUpdate; - } - nextState.reasonStateVersionUsedToComputeSubelements = nextReasonStateVersion; - var nextSideEffects = __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["c" /* rev */](nextState.sideEffects); - if (nextSideEffects !== /* [] */0) { - __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["b" /* iter */]((function (performSideEffects) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](performSideEffects, newSelf); - }), nextSideEffects); - thisJs.setState((function (futureTotalState, _) { - var initialSegment = function (_acc, _n, _l) { - while(true) { - var l = _l; - var n = _n; - var acc = _acc; - if (l && n > 0) { - _l = l[1]; - _n = n - 1 | 0; - _acc = /* :: */[ - l[0], - acc - ]; - continue ; - - } else { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["c" /* rev */](acc); - } - }; - }; - var n = __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["d" /* length */](futureTotalState.sideEffects) - __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["d" /* length */](nextState.sideEffects) | 0; - var newSideEffects = initialSegment(/* [] */0, n, futureTotalState.sideEffects); - return { - reasonState: futureTotalState.reasonState, - reasonStateVersion: futureTotalState.reasonStateVersion, - reasonStateVersionUsedToComputeSubelements: futureTotalState.reasonStateVersionUsedToComputeSubelements, - sideEffects: newSideEffects - }; - })); - } - return ret; - }), - handleMethod: (function (callback) { - var $$this = this ; - var thisJs = (this); - return (function (callbackPayload) { - var curState = thisJs.state; - var curReasonState = curState.reasonState; - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["d" /* _2 */](callback, callbackPayload, $$this.self(curReasonState, convertedReasonProps[0][/* retainedProps */11])); - }); - }), - updateMethod: (function (callback) { - var $$this = this ; - var thisJs = (this); - return (function ($$event) { - var curTotalState = thisJs.state; - var curReasonState = curTotalState.reasonState; - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var reasonStateUpdate = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["d" /* _2 */](callback, $$event, $$this.self(curReasonState, convertedReasonProps[0][/* retainedProps */11])); - if (reasonStateUpdate === /* NoUpdate */0) { - return magicNull; - } else { - var nextTotalState = $$this.transitionNextTotalState(curTotalState, reasonStateUpdate); - if (nextTotalState.reasonStateVersion !== curTotalState.reasonStateVersion) { - return thisJs.setState(nextTotalState); - } else { - return 0; - } - } - }); - }), - sendMethod: (function (action) { - var $$this = this ; - var thisJs = (this); - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var component = convertedReasonProps[0]; - if (component[/* reducer */12] !== reducerDefault) { - var partialStateApplication = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](component[/* reducer */12], action); - return thisJs.setState((function (curTotalState, _) { - var curReasonState = curTotalState.reasonState; - var reasonStateUpdate = __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](partialStateApplication, curReasonState); - if (reasonStateUpdate === /* NoUpdate */0) { - return magicNull; - } else { - var nextTotalState = $$this.transitionNextTotalState(curTotalState, reasonStateUpdate); - if (nextTotalState.reasonStateVersion !== curTotalState.reasonStateVersion) { - return nextTotalState; - } else { - return magicNull; - } - } - })); - } else { - return 0; - } - }), - reduceMethod: (function (callback, payload) { - var $$this = this ; - return $$this.sendMethod(__WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, payload)); - }), - render: (function () { - var $$this = this ; - var thisJs = (this); - var convertedReasonProps = convertPropsIfTheyreFromJs(thisJs.props, thisJs.jsPropsToReason, debugName); - var created = convertedReasonProps[0]; - var curState = thisJs.state; - var curReasonState = curState.reasonState; - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](created[/* render */9], $$this.self(curReasonState, created[/* retainedProps */11])); - }) - }); -} - -function basicComponent(debugName) { - return /* record */[ - /* debugName */debugName, - /* reactClassInternal */createClass(debugName), - /* handedOffState : record */[/* contents : None */0], - /* willReceiveProps */willReceivePropsDefault, - /* didMount */lifecycleNoUpdate, - /* didUpdate */lifecyclePreviousCurrentReturnUnit, - /* willUnmount */lifecycleReturnUnit, - /* willUpdate */lifecyclePreviousNextUnit, - /* shouldUpdate */lifecycleReturnTrue, - /* render */renderDefault, - /* initialState */initialStateDefault, - /* retainedProps : () */0, - /* reducer */reducerDefault, - /* subscriptions */subscriptionsDefault, - /* jsElementWrapped : None */0 - ]; -} - -var statelessComponent = basicComponent; - -var statelessComponentWithRetainedProps = basicComponent; - -var reducerComponent = basicComponent; - -var reducerComponentWithRetainedProps = basicComponent; - -function element($staropt$star, $staropt$star$1, component) { - var key = $staropt$star ? $staropt$star[0] : undefined; - var ref = $staropt$star$1 ? $staropt$star$1[0] : undefined; - var element$1 = /* Element */[component]; - var match = component[/* jsElementWrapped */14]; - if (match) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["d" /* _2 */](match[0], key, ref); - } else { - return __WEBPACK_IMPORTED_MODULE_2_react__["createElement"](component[/* reactClassInternal */1], { - key: key, - ref: ref, - reasonProps: element$1 - }); - } -} - -function wrapReasonForJs(component, jsPropsToReason) { - var tmp = component[/* reactClassInternal */1].prototype; - tmp.jsPropsToReason = /* Some */[jsPropsToReason]; - return component[/* reactClassInternal */1]; -} - -var dummyInteropComponent = basicComponent("interop"); - -function wrapJsForReason(reactClass, props, children) { - var jsElementWrapped = /* Some */[(function (param, param$1) { - var reactClass$1 = reactClass; - var props$1 = props; - var children$1 = children; - var key = param; - var ref = param$1; - var props$2 = Object.assign(Object.assign({ }, props$1), { - ref: ref, - key: key - }); - var varargs = /* array */[ - reactClass$1, - props$2 - ].concat(children$1); - return __WEBPACK_IMPORTED_MODULE_2_react__["createElement"].apply(null, varargs); - })]; - var newrecord = dummyInteropComponent.slice(); - newrecord[/* jsElementWrapped */14] = jsElementWrapped; - return newrecord; -} - -function path() { - var match = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined) { - var raw = match.location.pathname; - switch (raw) { - case "" : - case "/" : - return /* [] */0; - default: - var raw$1 = raw.slice(1); - var match$1 = raw$1[raw$1.length - 1 | 0]; - var raw$2 = match$1 === "/" ? raw$1.slice(0, -1) : raw$1; - var a = raw$2.split("/"); - var _i = a.length - 1 | 0; - var _res = /* [] */0; - while(true) { - var res = _res; - var i = _i; - if (i < 0) { - return res; - } else { - _res = /* :: */[ - a[i], - res - ]; - _i = i - 1 | 0; - continue ; - - } - }; - } - } else { - return /* [] */0; - } -} - -function hash() { - var match = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined) { - var raw = match.location.hash; - switch (raw) { - case "" : - case "#" : - return ""; - default: - return raw.slice(1); - } - } else { - return ""; - } -} - -function search() { - var match = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined) { - var raw = match.location.search; - switch (raw) { - case "" : - case "?" : - return ""; - default: - return raw.slice(1); - } - } else { - return ""; - } -} - -function push(path) { - var match = typeof (history) === "undefined" ? undefined : (history); - var match$1 = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined && match$1 !== undefined) { - match.pushState((null), "", path); - match$1.dispatchEvent(new Event("popstate")); - return /* () */0; - } else { - return /* () */0; - } -} - -function url() { - return /* record */[ - /* path */path(/* () */0), - /* hash */hash(/* () */0), - /* search */search(/* () */0) - ]; -} - -function watchUrl(callback) { - var match = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined) { - var watcherID = function () { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, url(/* () */0)); - }; - match.addEventListener("popstate", watcherID); - return watcherID; - } else { - return (function () { - return /* () */0; - }); - } -} - -function unwatchUrl(watcherID) { - var match = typeof (window) === "undefined" ? undefined : (window); - if (match !== undefined) { - match.removeEventListener("popstate", watcherID); - return /* () */0; - } else { - return /* () */0; - } -} - -var Router = [ - push, - watchUrl, - unwatchUrl, - url -]; - - -/* magicNull Not a pure module */ - - -/***/ }), -/* 5 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export caml_set_oo_id */ -/* unused harmony export get_id */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return create; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isCamlExceptionOrOpenVariant; }); - - - -var id = [0]; - -function caml_set_oo_id(b) { - b[1] = id[0]; - id[0] += 1; - return b; -} - -function get_id() { - id[0] += 1; - return id[0]; -} - -function create(str) { - var v_001 = get_id(/* () */0); - var v = /* tuple */[ - str, - v_001 - ]; - v.tag = 248; - return v; -} - -function isCamlExceptionOrOpenVariant(e) { - if (e === undefined) { - return /* false */0; - } else if (e.tag === 248) { - return /* true */1; - } else { - var slot = e[0]; - if (slot !== undefined) { - return +(slot.tag === 248); - } else { - return /* false */0; - } - } -} - - -/* No side effect */ - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"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. - * - * - */ - -function makeEmptyFunction(arg) { - return function () { - return arg; - }; -} - -/** - * This function accepts and discards inputs; it has no side effects. This is - * primarily useful idiomatically for overridable function endpoints which - * always need to be callable, since JS lacks a null-call idiom ala Cocoa. - */ -var emptyFunction = function emptyFunction() {}; - -emptyFunction.thatReturns = makeEmptyFunction; -emptyFunction.thatReturnsFalse = makeEmptyFunction(false); -emptyFunction.thatReturnsTrue = makeEmptyFunction(true); -emptyFunction.thatReturnsNull = makeEmptyFunction(null); -emptyFunction.thatReturnsThis = function () { - return this; -}; -emptyFunction.thatReturnsArgument = function (arg) { - return arg; -}; - -module.exports = emptyFunction; - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/** - * 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 invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - -var validateFormat = function validateFormat(format) {}; - -if (process.env.NODE_ENV !== 'production') { - validateFormat = function validateFormat(format) { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - }; -} - -function invariant(condition, format, a, b, c, d, e, f) { - validateFormat(format); - - if (!condition) { - var error; - if (format === undefined) { - error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error(format.replace(/%s/g, function () { - return args[argIndex++]; - })); - error.name = 'Invariant Violation'; - } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } -} - -module.exports = invariant; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __; }); - - - -function __(tag, block) { - block.tag = tag; - return block; -} - - -/* No side effect */ - - -/***/ }), -/* 9 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export div */ -/* unused harmony export mod_ */ -/* unused harmony export caml_bswap16 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_int32_bswap; }); -/* unused harmony export caml_nativeint_bswap */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return imul; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - -function div(x, y) { - if (y === 0) { - throw __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["f" /* division_by_zero */]; - } else { - return x / y | 0; - } -} - -function mod_(x, y) { - if (y === 0) { - throw __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["f" /* division_by_zero */]; - } else { - return x % y; - } -} - -function caml_bswap16(x) { - return ((x & 255) << 8) | ((x & 65280) >>> 8); -} - -function caml_int32_bswap(x) { - return ((x & 255) << 24) | ((x & 65280) << 8) | ((x & 16711680) >>> 8) | ((x & 4278190080) >>> 24); -} - -var imul = ( Math.imul || function (x,y) { - y |= 0; return ((((x >> 16) * y) << 16) + (x & 0xffff) * y)|0; -} -); - -var caml_nativeint_bswap = caml_int32_bswap; - - -/* imul Not a pure module */ - - -/***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_int_compare; }); -/* unused harmony export caml_float_compare */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return caml_nativeint_compare; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return caml_string_compare; }); -/* unused harmony export caml_int32_compare */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return caml_int_min; }); -/* unused harmony export caml_float_min */ -/* unused harmony export caml_string_min */ -/* unused harmony export caml_nativeint_min */ -/* unused harmony export caml_int32_min */ -/* unused harmony export caml_int_max */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return caml_float_max; }); -/* unused harmony export caml_string_max */ -/* unused harmony export caml_nativeint_max */ -/* unused harmony export caml_int32_max */ - - - -function caml_int_compare(x, y) { - if (x < y) { - return -1; - } else if (x === y) { - return 0; - } else { - return 1; - } -} - -function caml_float_compare(x, y) { - if (x === y) { - return 0; - } else if (x < y) { - return -1; - } else if (x > y || x === x) { - return 1; - } else if (y === y) { - return -1; - } else { - return 0; - } -} - -function caml_string_compare(s1, s2) { - if (s1 === s2) { - return 0; - } else if (s1 < s2) { - return -1; - } else { - return 1; - } -} - -function caml_int_min(x, y) { - if (x < y) { - return x; - } else { - return y; - } -} - -function caml_float_min(x, y) { - if (x < y) { - return x; - } else { - return y; - } -} - -function caml_string_min(x, y) { - if (x < y) { - return x; - } else { - return y; - } -} - -function caml_nativeint_min(x, y) { - if (x < y) { - return x; - } else { - return y; - } -} - -function caml_int32_min(x, y) { - if (x < y) { - return x; - } else { - return y; - } -} - -function caml_int_max(x, y) { - if (x > y) { - return x; - } else { - return y; - } -} - -function caml_float_max(x, y) { - if (x > y) { - return x; - } else { - return y; - } -} - -function caml_string_max(x, y) { - if (x > y) { - return x; - } else { - return y; - } -} - -function caml_nativeint_max(x, y) { - if (x > y) { - return x; - } else { - return y; - } -} - -function caml_int32_max(x, y) { - if (x > y) { - return x; - } else { - return y; - } -} - -var caml_nativeint_compare = caml_int_compare; - -var caml_int32_compare = caml_int_compare; - - -/* No side effect */ - - -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return bytes_of_string; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bytes_to_string; }); -/* unused harmony export caml_is_printable */ -/* unused harmony export caml_string_of_char_array */ -/* unused harmony export caml_string_get */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_create_string; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return caml_fill_string; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return caml_blit_string; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return caml_blit_bytes; }); -/* unused harmony export caml_string_get16 */ -/* unused harmony export caml_string_get32 */ -/* unused harmony export string_of_char */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return get; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - -function string_of_char(prim) { - return String.fromCharCode(prim); -} - -function caml_string_get(s, i) { - if (i >= s.length || i < 0) { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "index out of bounds" - ]; - } else { - return s.charCodeAt(i); - } -} - -function caml_create_string(len) { - if (len < 0) { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.create" - ]; - } else { - var result = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - result[i] = /* "\000" */0; - } - return result; - } -} - -function caml_fill_string(s, i, l, c) { - if (l > 0) { - for(var k = i ,k_finish = (l + i | 0) - 1 | 0; k <= k_finish; ++k){ - s[k] = c; - } - return /* () */0; - } else { - return 0; - } -} - -function caml_blit_string(s1, i1, s2, i2, len) { - if (len > 0) { - var off1 = s1.length - i1 | 0; - if (len <= off1) { - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - s2[i2 + i | 0] = s1.charCodeAt(i1 + i | 0); - } - return /* () */0; - } else { - for(var i$1 = 0 ,i_finish$1 = off1 - 1 | 0; i$1 <= i_finish$1; ++i$1){ - s2[i2 + i$1 | 0] = s1.charCodeAt(i1 + i$1 | 0); - } - for(var i$2 = off1 ,i_finish$2 = len - 1 | 0; i$2 <= i_finish$2; ++i$2){ - s2[i2 + i$2 | 0] = /* "\000" */0; - } - return /* () */0; - } - } else { - return 0; - } -} - -function caml_blit_bytes(s1, i1, s2, i2, len) { - if (len > 0) { - if (s1 === s2) { - var s1$1 = s1; - var i1$1 = i1; - var i2$1 = i2; - var len$1 = len; - if (i1$1 < i2$1) { - var range_a = (s1$1.length - i2$1 | 0) - 1 | 0; - var range_b = len$1 - 1 | 0; - var range = range_a > range_b ? range_b : range_a; - for(var j = range; j >= 0; --j){ - s1$1[i2$1 + j | 0] = s1$1[i1$1 + j | 0]; - } - return /* () */0; - } else if (i1$1 > i2$1) { - var range_a$1 = (s1$1.length - i1$1 | 0) - 1 | 0; - var range_b$1 = len$1 - 1 | 0; - var range$1 = range_a$1 > range_b$1 ? range_b$1 : range_a$1; - for(var k = 0; k <= range$1; ++k){ - s1$1[i2$1 + k | 0] = s1$1[i1$1 + k | 0]; - } - return /* () */0; - } else { - return 0; - } - } else { - var off1 = s1.length - i1 | 0; - if (len <= off1) { - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - s2[i2 + i | 0] = s1[i1 + i | 0]; - } - return /* () */0; - } else { - for(var i$1 = 0 ,i_finish$1 = off1 - 1 | 0; i$1 <= i_finish$1; ++i$1){ - s2[i2 + i$1 | 0] = s1[i1 + i$1 | 0]; - } - for(var i$2 = off1 ,i_finish$2 = len - 1 | 0; i$2 <= i_finish$2; ++i$2){ - s2[i2 + i$2 | 0] = /* "\000" */0; - } - return /* () */0; - } - } - } else { - return 0; - } -} - -function bytes_of_string(s) { - var len = s.length; - var res = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - res[i] = s.charCodeAt(i); - } - return res; -} - -function bytes_to_string(a) { - var bytes = a; - var i = 0; - var len = a.length; - var s = ""; - var s_len = len; - if (i === 0 && len <= 4096 && len === bytes.length) { - return String.fromCharCode.apply(null,bytes); - } else { - var offset = 0; - while(s_len > 0) { - var next = s_len < 1024 ? s_len : 1024; - var tmp_bytes = new Array(next); - caml_blit_bytes(bytes, offset, tmp_bytes, 0, next); - s = s + String.fromCharCode.apply(null,tmp_bytes); - s_len = s_len - next | 0; - offset = offset + next | 0; - }; - return s; - } -} - -function caml_string_of_char_array(chars) { - var len = chars.length; - var bytes = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - bytes[i] = chars[i]; - } - return bytes_to_string(bytes); -} - -function caml_is_printable(c) { - if (c > 31) { - return +(c < 127); - } else { - return /* false */0; - } -} - -function caml_string_get16(s, i) { - return s.charCodeAt(i) + (s.charCodeAt(i + 1 | 0) << 8) | 0; -} - -function caml_string_get32(s, i) { - return ((s.charCodeAt(i) + (s.charCodeAt(i + 1 | 0) << 8) | 0) + (s.charCodeAt(i + 2 | 0) << 16) | 0) + (s.charCodeAt(i + 3 | 0) << 24) | 0; -} - -function get(s, i) { - if (i < 0 || i >= s.length) { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "index out of bounds" - ]; - } else { - return s.charCodeAt(i); - } -} - - -/* No side effect */ - - -/***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return length; }); -/* unused harmony export hd */ -/* unused harmony export tl */ -/* unused harmony export nth */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return rev; }); -/* unused harmony export append */ -/* unused harmony export rev_append */ -/* unused harmony export concat */ -/* unused harmony export flatten */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iter; }); -/* unused harmony export iteri */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return map; }); -/* unused harmony export mapi */ -/* unused harmony export rev_map */ -/* unused harmony export fold_left */ -/* unused harmony export fold_right */ -/* unused harmony export iter2 */ -/* unused harmony export map2 */ -/* unused harmony export rev_map2 */ -/* unused harmony export fold_left2 */ -/* unused harmony export fold_right2 */ -/* unused harmony export for_all */ -/* unused harmony export exists */ -/* unused harmony export for_all2 */ -/* unused harmony export exists2 */ -/* unused harmony export mem */ -/* unused harmony export memq */ -/* unused harmony export find */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return filter; }); -/* unused harmony export find_all */ -/* unused harmony export partition */ -/* unused harmony export assoc */ -/* unused harmony export assq */ -/* unused harmony export mem_assoc */ -/* unused harmony export mem_assq */ -/* unused harmony export remove_assoc */ -/* unused harmony export remove_assq */ -/* unused harmony export split */ -/* unused harmony export combine */ -/* unused harmony export sort */ -/* unused harmony export stable_sort */ -/* unused harmony export fast_sort */ -/* unused harmony export sort_uniq */ -/* unused harmony export merge */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_obj_js__ = __webpack_require__(20); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pervasives_js__ = __webpack_require__(55); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - - -function length(l) { - var _len = 0; - var _param = l; - while(true) { - var param = _param; - var len = _len; - if (param) { - _param = param[1]; - _len = len + 1 | 0; - continue ; - - } else { - return len; - } - }; -} - -function hd(param) { - if (param) { - return param[0]; - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["b" /* failure */], - "hd" - ]; - } -} - -function tl(param) { - if (param) { - return param[1]; - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["b" /* failure */], - "tl" - ]; - } -} - -function nth(l, n) { - if (n < 0) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.nth" - ]; - } else { - var _l = l; - var _n = n; - while(true) { - var n$1 = _n; - var l$1 = _l; - if (l$1) { - if (n$1 === 0) { - return l$1[0]; - } else { - _n = n$1 - 1 | 0; - _l = l$1[1]; - continue ; - - } - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["b" /* failure */], - "nth" - ]; - } - }; - } -} - -function rev_append(_l1, _l2) { - while(true) { - var l2 = _l2; - var l1 = _l1; - if (l1) { - _l2 = /* :: */[ - l1[0], - l2 - ]; - _l1 = l1[1]; - continue ; - - } else { - return l2; - } - }; -} - -function rev(l) { - return rev_append(l, /* [] */0); -} - -function flatten(param) { - if (param) { - return __WEBPACK_IMPORTED_MODULE_2__pervasives_js__["a" /* $at */](param[0], flatten(param[1])); - } else { - return /* [] */0; - } -} - -function map(f, param) { - if (param) { - var r = __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, param[0]); - return /* :: */[ - r, - map(f, param[1]) - ]; - } else { - return /* [] */0; - } -} - -function mapi(i, f, param) { - if (param) { - var r = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, i, param[0]); - return /* :: */[ - r, - mapi(i + 1 | 0, f, param[1]) - ]; - } else { - return /* [] */0; - } -} - -function mapi$1(f, l) { - return mapi(0, f, l); -} - -function rev_map(f, l) { - var _accu = /* [] */0; - var _param = l; - while(true) { - var param = _param; - var accu = _accu; - if (param) { - _param = param[1]; - _accu = /* :: */[ - __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, param[0]), - accu - ]; - continue ; - - } else { - return accu; - } - }; -} - -function iter(f, _param) { - while(true) { - var param = _param; - if (param) { - __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, param[0]); - _param = param[1]; - continue ; - - } else { - return /* () */0; - } - }; -} - -function iteri(f, l) { - var _i = 0; - var f$1 = f; - var _param = l; - while(true) { - var param = _param; - var i = _i; - if (param) { - __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f$1, i, param[0]); - _param = param[1]; - _i = i + 1 | 0; - continue ; - - } else { - return /* () */0; - } - }; -} - -function fold_left(f, _accu, _l) { - while(true) { - var l = _l; - var accu = _accu; - if (l) { - _l = l[1]; - _accu = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, accu, l[0]); - continue ; - - } else { - return accu; - } - }; -} - -function fold_right(f, l, accu) { - if (l) { - return __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, l[0], fold_right(f, l[1], accu)); - } else { - return accu; - } -} - -function map2(f, l1, l2) { - if (l1) { - if (l2) { - var r = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, l1[0], l2[0]); - return /* :: */[ - r, - map2(f, l1[1], l2[1]) - ]; - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.map2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.map2" - ]; - } else { - return /* [] */0; - } -} - -function rev_map2(f, l1, l2) { - var _accu = /* [] */0; - var _l1 = l1; - var _l2 = l2; - while(true) { - var l2$1 = _l2; - var l1$1 = _l1; - var accu = _accu; - if (l1$1) { - if (l2$1) { - _l2 = l2$1[1]; - _l1 = l1$1[1]; - _accu = /* :: */[ - __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, l1$1[0], l2$1[0]), - accu - ]; - continue ; - - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.rev_map2" - ]; - } - } else if (l2$1) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.rev_map2" - ]; - } else { - return accu; - } - }; -} - -function iter2(f, _l1, _l2) { - while(true) { - var l2 = _l2; - var l1 = _l1; - if (l1) { - if (l2) { - __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, l1[0], l2[0]); - _l2 = l2[1]; - _l1 = l1[1]; - continue ; - - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.iter2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.iter2" - ]; - } else { - return /* () */0; - } - }; -} - -function fold_left2(f, _accu, _l1, _l2) { - while(true) { - var l2 = _l2; - var l1 = _l1; - var accu = _accu; - if (l1) { - if (l2) { - _l2 = l2[1]; - _l1 = l1[1]; - _accu = __WEBPACK_IMPORTED_MODULE_0__curry_js__["a" /* _3 */](f, accu, l1[0], l2[0]); - continue ; - - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.fold_left2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.fold_left2" - ]; - } else { - return accu; - } - }; -} - -function fold_right2(f, l1, l2, accu) { - if (l1) { - if (l2) { - return __WEBPACK_IMPORTED_MODULE_0__curry_js__["a" /* _3 */](f, l1[0], l2[0], fold_right2(f, l1[1], l2[1], accu)); - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.fold_right2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.fold_right2" - ]; - } else { - return accu; - } -} - -function for_all(p, _param) { - while(true) { - var param = _param; - if (param) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](p, param[0])) { - _param = param[1]; - continue ; - - } else { - return /* false */0; - } - } else { - return /* true */1; - } - }; -} - -function exists(p, _param) { - while(true) { - var param = _param; - if (param) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](p, param[0])) { - return /* true */1; - } else { - _param = param[1]; - continue ; - - } - } else { - return /* false */0; - } - }; -} - -function for_all2(p, _l1, _l2) { - while(true) { - var l2 = _l2; - var l1 = _l1; - if (l1) { - if (l2) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](p, l1[0], l2[0])) { - _l2 = l2[1]; - _l1 = l1[1]; - continue ; - - } else { - return /* false */0; - } - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.for_all2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.for_all2" - ]; - } else { - return /* true */1; - } - }; -} - -function exists2(p, _l1, _l2) { - while(true) { - var l2 = _l2; - var l1 = _l1; - if (l1) { - if (l2) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](p, l1[0], l2[0])) { - return /* true */1; - } else { - _l2 = l2[1]; - _l1 = l1[1]; - continue ; - - } - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.exists2" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.exists2" - ]; - } else { - return /* false */0; - } - }; -} - -function mem(x, _param) { - while(true) { - var param = _param; - if (param) { - if (__WEBPACK_IMPORTED_MODULE_1__caml_obj_js__["a" /* caml_equal */](param[0], x)) { - return /* true */1; - } else { - _param = param[1]; - continue ; - - } - } else { - return /* false */0; - } - }; -} - -function memq(x, _param) { - while(true) { - var param = _param; - if (param) { - if (param[0] === x) { - return /* true */1; - } else { - _param = param[1]; - continue ; - - } - } else { - return /* false */0; - } - }; -} - -function assoc(x, _param) { - while(true) { - var param = _param; - if (param) { - var match = param[0]; - if (__WEBPACK_IMPORTED_MODULE_1__caml_obj_js__["a" /* caml_equal */](match[0], x)) { - return match[1]; - } else { - _param = param[1]; - continue ; - - } - } else { - throw __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["c" /* not_found */]; - } - }; -} - -function assq(x, _param) { - while(true) { - var param = _param; - if (param) { - var match = param[0]; - if (match[0] === x) { - return match[1]; - } else { - _param = param[1]; - continue ; - - } - } else { - throw __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["c" /* not_found */]; - } - }; -} - -function mem_assoc(x, _param) { - while(true) { - var param = _param; - if (param) { - if (__WEBPACK_IMPORTED_MODULE_1__caml_obj_js__["a" /* caml_equal */](param[0][0], x)) { - return /* true */1; - } else { - _param = param[1]; - continue ; - - } - } else { - return /* false */0; - } - }; -} - -function mem_assq(x, _param) { - while(true) { - var param = _param; - if (param) { - if (param[0][0] === x) { - return /* true */1; - } else { - _param = param[1]; - continue ; - - } - } else { - return /* false */0; - } - }; -} - -function remove_assoc(x, param) { - if (param) { - var l = param[1]; - var pair = param[0]; - if (__WEBPACK_IMPORTED_MODULE_1__caml_obj_js__["a" /* caml_equal */](pair[0], x)) { - return l; - } else { - return /* :: */[ - pair, - remove_assoc(x, l) - ]; - } - } else { - return /* [] */0; - } -} - -function remove_assq(x, param) { - if (param) { - var l = param[1]; - var pair = param[0]; - if (pair[0] === x) { - return l; - } else { - return /* :: */[ - pair, - remove_assq(x, l) - ]; - } - } else { - return /* [] */0; - } -} - -function find(p, _param) { - while(true) { - var param = _param; - if (param) { - var x = param[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](p, x)) { - return x; - } else { - _param = param[1]; - continue ; - - } - } else { - throw __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["c" /* not_found */]; - } - }; -} - -function find_all(p) { - return (function (param) { - var _accu = /* [] */0; - var _param = param; - while(true) { - var param$1 = _param; - var accu = _accu; - if (param$1) { - var l = param$1[1]; - var x = param$1[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](p, x)) { - _param = l; - _accu = /* :: */[ - x, - accu - ]; - continue ; - - } else { - _param = l; - continue ; - - } - } else { - return rev_append(accu, /* [] */0); - } - }; - }); -} - -function partition(p, l) { - var _yes = /* [] */0; - var _no = /* [] */0; - var _param = l; - while(true) { - var param = _param; - var no = _no; - var yes = _yes; - if (param) { - var l$1 = param[1]; - var x = param[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](p, x)) { - _param = l$1; - _yes = /* :: */[ - x, - yes - ]; - continue ; - - } else { - _param = l$1; - _no = /* :: */[ - x, - no - ]; - continue ; - - } - } else { - return /* tuple */[ - rev_append(yes, /* [] */0), - rev_append(no, /* [] */0) - ]; - } - }; -} - -function split(param) { - if (param) { - var match = param[0]; - var match$1 = split(param[1]); - return /* tuple */[ - /* :: */[ - match[0], - match$1[0] - ], - /* :: */[ - match[1], - match$1[1] - ] - ]; - } else { - return /* tuple */[ - /* [] */0, - /* [] */0 - ]; - } -} - -function combine(l1, l2) { - if (l1) { - if (l2) { - return /* :: */[ - /* tuple */[ - l1[0], - l2[0] - ], - combine(l1[1], l2[1]) - ]; - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.combine" - ]; - } - } else if (l2) { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "List.combine" - ]; - } else { - return /* [] */0; - } -} - -function merge(cmp, l1, l2) { - if (l1) { - if (l2) { - var h2 = l2[0]; - var h1 = l1[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, h1, h2) <= 0) { - return /* :: */[ - h1, - merge(cmp, l1[1], l2) - ]; - } else { - return /* :: */[ - h2, - merge(cmp, l1, l2[1]) - ]; - } - } else { - return l1; - } - } else { - return l2; - } -} - -function chop(_k, _l) { - while(true) { - var l = _l; - var k = _k; - if (k === 0) { - return l; - } else if (l) { - _l = l[1]; - _k = k - 1 | 0; - continue ; - - } else { - throw [ - __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["d" /* assert_failure */], - [ - "list.ml", - 223, - 11 - ] - ]; - } - }; -} - -function stable_sort(cmp, l) { - var sort = function (n, l) { - var exit = 0; - if (n !== 2) { - if (n !== 3 || !l) { - exit = 1; - } else { - var match = l[1]; - if (match) { - var match$1 = match[1]; - if (match$1) { - var x3 = match$1[0]; - var x2 = match[0]; - var x1 = l[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x2) <= 0) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3) <= 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3) <= 0) { - return /* :: */[ - x1, - /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3) <= 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3) <= 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - } - } else if (l) { - var match$2 = l[1]; - if (match$2) { - var x2$1 = match$2[0]; - var x1$1 = l[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1$1, x2$1) <= 0) { - return /* :: */[ - x1$1, - /* :: */[ - x2$1, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x2$1, - /* :: */[ - x1$1, - /* [] */0 - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - if (exit === 1) { - var n1 = (n >> 1); - var n2 = n - n1 | 0; - var l2 = chop(n1, l); - var s1 = rev_sort(n1, l); - var s2 = rev_sort(n2, l2); - var _l1 = s1; - var _l2 = s2; - var _accu = /* [] */0; - while(true) { - var accu = _accu; - var l2$1 = _l2; - var l1 = _l1; - if (l1) { - if (l2$1) { - var h2 = l2$1[0]; - var h1 = l1[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, h1, h2) > 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l1 = l1[1]; - continue ; - - } else { - _accu = /* :: */[ - h2, - accu - ]; - _l2 = l2$1[1]; - continue ; - - } - } else { - return rev_append(l1, accu); - } - } else { - return rev_append(l2$1, accu); - } - }; - } - - }; - var rev_sort = function (n, l) { - var exit = 0; - if (n !== 2) { - if (n !== 3 || !l) { - exit = 1; - } else { - var match = l[1]; - if (match) { - var match$1 = match[1]; - if (match$1) { - var x3 = match$1[0]; - var x2 = match[0]; - var x1 = l[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x2) > 0) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3) > 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3) > 0) { - return /* :: */[ - x1, - /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3) > 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3) > 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - } - } else if (l) { - var match$2 = l[1]; - if (match$2) { - var x2$1 = match$2[0]; - var x1$1 = l[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1$1, x2$1) > 0) { - return /* :: */[ - x1$1, - /* :: */[ - x2$1, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x2$1, - /* :: */[ - x1$1, - /* [] */0 - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - if (exit === 1) { - var n1 = (n >> 1); - var n2 = n - n1 | 0; - var l2 = chop(n1, l); - var s1 = sort(n1, l); - var s2 = sort(n2, l2); - var _l1 = s1; - var _l2 = s2; - var _accu = /* [] */0; - while(true) { - var accu = _accu; - var l2$1 = _l2; - var l1 = _l1; - if (l1) { - if (l2$1) { - var h2 = l2$1[0]; - var h1 = l1[0]; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, h1, h2) <= 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l1 = l1[1]; - continue ; - - } else { - _accu = /* :: */[ - h2, - accu - ]; - _l2 = l2$1[1]; - continue ; - - } - } else { - return rev_append(l1, accu); - } - } else { - return rev_append(l2$1, accu); - } - }; - } - - }; - var len = length(l); - if (len < 2) { - return l; - } else { - return sort(len, l); - } -} - -function sort_uniq(cmp, l) { - var sort = function (n, l) { - var exit = 0; - if (n !== 2) { - if (n !== 3 || !l) { - exit = 1; - } else { - var match = l[1]; - if (match) { - var match$1 = match[1]; - if (match$1) { - var x3 = match$1[0]; - var x2 = match[0]; - var x1 = l[0]; - var c = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x2); - if (c === 0) { - var c$1 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$1 === 0) { - return /* :: */[ - x2, - /* [] */0 - ]; - } else if (c$1 < 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } - } else if (c < 0) { - var c$2 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$2 === 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } else if (c$2 < 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else { - var c$3 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3); - if (c$3 === 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } else if (c$3 < 0) { - return /* :: */[ - x1, - /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } - } - } else { - var c$4 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3); - if (c$4 === 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ]; - } else if (c$4 < 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else { - var c$5 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$5 === 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ]; - } else if (c$5 < 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } - } - } - } else { - exit = 1; - } - } else { - exit = 1; - } - } - } else if (l) { - var match$2 = l[1]; - if (match$2) { - var x2$1 = match$2[0]; - var x1$1 = l[0]; - var c$6 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1$1, x2$1); - if (c$6 === 0) { - return /* :: */[ - x1$1, - /* [] */0 - ]; - } else if (c$6 < 0) { - return /* :: */[ - x1$1, - /* :: */[ - x2$1, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x2$1, - /* :: */[ - x1$1, - /* [] */0 - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - if (exit === 1) { - var n1 = (n >> 1); - var n2 = n - n1 | 0; - var l2 = chop(n1, l); - var s1 = rev_sort(n1, l); - var s2 = rev_sort(n2, l2); - var _l1 = s1; - var _l2 = s2; - var _accu = /* [] */0; - while(true) { - var accu = _accu; - var l2$1 = _l2; - var l1 = _l1; - if (l1) { - if (l2$1) { - var t2 = l2$1[1]; - var h2 = l2$1[0]; - var t1 = l1[1]; - var h1 = l1[0]; - var c$7 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, h1, h2); - if (c$7 === 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l2 = t2; - _l1 = t1; - continue ; - - } else if (c$7 > 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l1 = t1; - continue ; - - } else { - _accu = /* :: */[ - h2, - accu - ]; - _l2 = t2; - continue ; - - } - } else { - return rev_append(l1, accu); - } - } else { - return rev_append(l2$1, accu); - } - }; - } - - }; - var rev_sort = function (n, l) { - var exit = 0; - if (n !== 2) { - if (n !== 3 || !l) { - exit = 1; - } else { - var match = l[1]; - if (match) { - var match$1 = match[1]; - if (match$1) { - var x3 = match$1[0]; - var x2 = match[0]; - var x1 = l[0]; - var c = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x2); - if (c === 0) { - var c$1 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$1 === 0) { - return /* :: */[ - x2, - /* [] */0 - ]; - } else if (c$1 > 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } - } else if (c > 0) { - var c$2 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$2 === 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } else if (c$2 > 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else { - var c$3 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3); - if (c$3 === 0) { - return /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ]; - } else if (c$3 > 0) { - return /* :: */[ - x1, - /* :: */[ - x3, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x1, - /* :: */[ - x2, - /* [] */0 - ] - ] - ]; - } - } - } else { - var c$4 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1, x3); - if (c$4 === 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ]; - } else if (c$4 > 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* :: */[ - x3, - /* [] */0 - ] - ] - ]; - } else { - var c$5 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x2, x3); - if (c$5 === 0) { - return /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ]; - } else if (c$5 > 0) { - return /* :: */[ - x2, - /* :: */[ - x3, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } else { - return /* :: */[ - x3, - /* :: */[ - x2, - /* :: */[ - x1, - /* [] */0 - ] - ] - ]; - } - } - } - } else { - exit = 1; - } - } else { - exit = 1; - } - } - } else if (l) { - var match$2 = l[1]; - if (match$2) { - var x2$1 = match$2[0]; - var x1$1 = l[0]; - var c$6 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, x1$1, x2$1); - if (c$6 === 0) { - return /* :: */[ - x1$1, - /* [] */0 - ]; - } else if (c$6 > 0) { - return /* :: */[ - x1$1, - /* :: */[ - x2$1, - /* [] */0 - ] - ]; - } else { - return /* :: */[ - x2$1, - /* :: */[ - x1$1, - /* [] */0 - ] - ]; - } - } else { - exit = 1; - } - } else { - exit = 1; - } - if (exit === 1) { - var n1 = (n >> 1); - var n2 = n - n1 | 0; - var l2 = chop(n1, l); - var s1 = sort(n1, l); - var s2 = sort(n2, l2); - var _l1 = s1; - var _l2 = s2; - var _accu = /* [] */0; - while(true) { - var accu = _accu; - var l2$1 = _l2; - var l1 = _l1; - if (l1) { - if (l2$1) { - var t2 = l2$1[1]; - var h2 = l2$1[0]; - var t1 = l1[1]; - var h1 = l1[0]; - var c$7 = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, h1, h2); - if (c$7 === 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l2 = t2; - _l1 = t1; - continue ; - - } else if (c$7 < 0) { - _accu = /* :: */[ - h1, - accu - ]; - _l1 = t1; - continue ; - - } else { - _accu = /* :: */[ - h2, - accu - ]; - _l2 = t2; - continue ; - - } - } else { - return rev_append(l1, accu); - } - } else { - return rev_append(l2$1, accu); - } - }; - } - - }; - var len = length(l); - if (len < 2) { - return l; - } else { - return sort(len, l); - } -} - -var append = __WEBPACK_IMPORTED_MODULE_2__pervasives_js__["a" /* $at */]; - -var concat = flatten; - -var filter = find_all; - -var sort = stable_sort; - -var fast_sort = stable_sort; - - -/* No side effect */ - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - */ - - - -var emptyObject = {}; - -if (process.env.NODE_ENV !== 'production') { - Object.freeze(emptyObject); -} - -module.exports = emptyObject; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* +!function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=31)}([function(e,t,n){"use strict";n.d(t,"c",function(){return o}),n.d(t,"a",function(){return a}),n.d(t,"e",function(){return l}),n.d(t,"f",function(){return u}),n.d(t,"d",function(){return s}),n.d(t,"b",function(){return p});var r=["Out_of_memory",0],i=["Sys_error",-1],o=["Failure",-2],a=["Invalid_argument",-3],l=["End_of_file",-4],u=["Division_by_zero",-5],s=["Not_found",-6],c=["Match_failure",-7],f=["Stack_overflow",-8],d=["Sys_blocked_io",-9],p=["Assert_failure",-10],h=["Undefined_recursive_module",-11];r.tag=248,i.tag=248,o.tag=248,a.tag=248,l.tag=248,u.tag=248,s.tag=248,c.tag=248,f.tag=248,d.tag=248,p.tag=248,h.tag=248},function(e,t,n){"use strict";function r(e,t){for(;;){var n=t,i=e,o=i.length,a=0===o?1:o,l=n.length,u=a-l|0;if(0===u)return i.apply(null,n);if(!(u<0))return function(e,t){return function(n){return r(e,t.concat([n]))}}(i,n);t=d.b(n,a,0|-u),e=i.apply(null,d.b(n,0,a))}}function i(e,t,n){if(n>7||n<0)return r(e,[t]);switch(n){case 0:case 1:return e(t);case 2:return function(n){return e(t,n)};case 3:return function(n,r){return e(t,n,r)};case 4:return function(n,r,i){return e(t,n,r,i)};case 5:return function(n,r,i,o){return e(t,n,r,i,o)};case 6:return function(n,r,i,o,a){return e(t,n,r,i,o,a)};case 7:return function(n,r,i,o,a,l){return e(t,n,r,i,o,a,l)}}}function o(e,t){var n=e.length;return 1===n?e(t):i(e,t,n)}function a(e,t,n,i){if(i>7||i<0)return r(e,[t,n]);switch(i){case 0:case 1:return r(e(t),[n]);case 2:return e(t,n);case 3:return function(r){return e(t,n,r)};case 4:return function(r,i){return e(t,n,r,i)};case 5:return function(r,i,o){return e(t,n,r,i,o)};case 6:return function(r,i,o,a){return e(t,n,r,i,o,a)};case 7:return function(r,i,o,a,l){return e(t,n,r,i,o,a,l)}}}function l(e,t,n){var r=e.length;return 2===r?e(t,n):a(e,t,n,r)}function u(e,t,n,i,o){var a=0;if(o>7||o<0)return r(e,[t,n,i]);switch(o){case 0:case 1:a=1;break;case 2:return r(e(t,n),[i]);case 3:return e(t,n,i);case 4:return function(r){return e(t,n,i,r)};case 5:return function(r,o){return e(t,n,i,r,o)};case 6:return function(r,o,a){return e(t,n,i,r,o,a)};case 7:return function(r,o,a,l){return e(t,n,i,r,o,a,l)}}return 1===a?r(e(t),[n,i]):void 0}function s(e,t,n,r){var i=e.length;return 3===i?e(t,n,r):u(e,t,n,r,i)}function c(e,t,n,i,o,a,l){var u=0;if(l>7||l<0)return r(e,[t,n,i,o,a]);switch(l){case 0:case 1:u=1;break;case 2:return r(e(t,n),[i,o,a]);case 3:return r(e(t,n,i),[o,a]);case 4:return r(e(t,n,i,o),[a]);case 5:return e(t,n,i,o,a);case 6:return function(r){return e(t,n,i,o,a,r)};case 7:return function(r,l){return e(t,n,i,o,a,r,l)}}return 1===u?r(e(t),[n,i,o,a]):void 0}function f(e,t,n,r,i,o){var a=e.length;return 5===a?e(t,n,r,i,o):c(e,t,n,r,i,o,a)}n.d(t,"b",function(){return o}),n.d(t,"d",function(){return l}),n.d(t,"a",function(){return s}),n.d(t,"c",function(){return f});var d=n(10)},function(e,t,n){"use strict";e.exports=n(75)},function(e,t,n){"use strict";function r(){return 0}function i(){return 0}function o(){return 0}function a(){return 0}function l(){return 1}function u(e){return e[2]}function s(){return"RenderNotImplemented"}function c(){return 0}function f(e,t){return 0}function d(){return 0}function p(e,t,n){var r=e.reasonProps;if(null==r){if(t)return[b.b(t[0],e)];throw[x.a,"A JS component called the Reason component "+n+" which didn't implement the JS->Reason React props conversion."]}return r}function h(e){return C.a({displayName:e,subscriptions:null,self:function(e,t){var n=this;return[n.handleMethod,n.reduceMethod,e,t,n.sendMethod]},transitionNextTotalState:function(e,t){if("number"==typeof t)return e;switch(0|t.tag){case 0:return{reasonState:t[0],reasonStateVersion:e.reasonStateVersion+1|0,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements,sideEffects:e.sideEffects};case 1:return{reasonState:t[0],reasonStateVersion:e.reasonStateVersion+1|0,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements+1|0,sideEffects:e.sideEffects};case 2:return{reasonState:e.reasonState,reasonStateVersion:e.reasonStateVersion+1|0,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements+1|0,sideEffects:[t[0],e.sideEffects]};case 3:return{reasonState:t[0],reasonStateVersion:e.reasonStateVersion+1|0,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements,sideEffects:[t[1],e.sideEffects]};case 4:return{reasonState:t[0],reasonStateVersion:e.reasonStateVersion+1|0,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements+1|0,sideEffects:[t[1],e.sideEffects]}}},getInitialState:function(){var t=this,n=p(t.props,t.jsPropsToReason,e);return{reasonState:b.b(n[0][10],0),reasonStateVersion:1,reasonStateVersionUsedToComputeSubelements:1,sideEffects:0}},componentDidMount:function(){var t=this,n=this,i=p(n.props,n.jsPropsToReason,e),o=i[0],a=n.state,l=a.reasonState,u=t.self(l,o[11]);if(o[13]!==d){var s=y.a(function(e){var t=e[1],n=b.b(e[0],0);return function(){return b.b(t,n)}},b.b(o[13],u));t.subscriptions=s}if(o[4]!==r){var c=b.b(o[4],u),f=t.transitionNextTotalState(a,c);return f.reasonStateVersion!==a.reasonStateVersion?n.setState(f):0}return 0},componentDidUpdate:function(t,n){var r=this,i=this,a=i.state,l=a.reasonState,u=i.props,s=p(u,i.jsPropsToReason,e),c=s[0];if(c[5]!==o){var f=+(t===u),d=0!==f?s:p(t,i.jsPropsToReason,e),h=n.reasonState,g=r.self(l,c[11]),m=g[0],v=g[1],y=d[0][11],w=g[4],x=[m,v,h,y,w];return b.b(c[5],[x,g])}return 0},componentWillUnmount:function(){var t=this,n=this,r=p(n.props,n.jsPropsToReason,e),i=r[0],o=n.state,l=o.reasonState;i[6]!==a&&b.b(i[6],t.self(l,i[11]));var u=t.subscriptions;return null==u?0:y.b(function(e){return b.b(e,0)},y.c(u))},componentWillUpdate:function(t,n){var r=this,o=this,a=p(t,o.jsPropsToReason,e),l=a[0];if(l[7]!==i){var u=o.props,s=+(t===u),c=0!==s?a:p(u,o.jsPropsToReason,e),f=o.state,d=f.reasonState,h=n.reasonState,g=r.self(h,l[11]),m=g[0],v=g[1],y=c[0][11],w=g[4],x=[m,v,d,y,w];return b.b(l[7],[x,g])}return 0},componentWillReceiveProps:function(t){var n=this,r=this,i=p(t,r.jsPropsToReason,e),o=i[0];if(o[3]!==u){var a=r.props,l=+(t===a),s=0!==l?i:p(a,r.jsPropsToReason,e),c=s[0];return r.setState(function(e,t){var r=e.reasonState,i=e.reasonStateVersion,a=n.self(r,c[11]),l=b.b(o[3],a),u=+(l!==r),s=0!==u?i+1|0:i;return s!==i?{reasonState:l,reasonStateVersion:s,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements,sideEffects:l.sideEffects}:e})}return 0},shouldComponentUpdate:function(t,n,r){var i,o=this,a=this,u=a.props,s=+(t!==u),c=p(a.props,a.jsPropsToReason,e),f=+(t===u),d=0!==f?c:p(t,a.jsPropsToReason,e),h=d[0],g=n.reasonStateVersion,m=n.reasonStateVersionUsedToComputeSubelements,v=+(m!==g),w=s||v,x=n.reasonState,C=o.self(x,h[11]);if(w&&h[8]!==l){var k=a.state,S=k.reasonState,T=C[0],E=C[1],M=c[0][11],L=C[4],N=[T,E,S,M,L];i=b.b(h[8],[N,C])}else i=w;n.reasonStateVersionUsedToComputeSubelements=g;var O=y.c(n.sideEffects);return 0!==O&&(y.b(function(e){return b.b(e,C)},O),a.setState(function(e,t){var r=y.d(e.sideEffects)-y.d(n.sideEffects)|0,i=function(e,t,n){for(;;){var r=n,i=t,o=e;if(!(r&&i>0))return y.c(o);n=r[1],t=i-1|0,e=[r[0],o]}}(0,r,e.sideEffects);return{reasonState:e.reasonState,reasonStateVersion:e.reasonStateVersion,reasonStateVersionUsedToComputeSubelements:e.reasonStateVersionUsedToComputeSubelements,sideEffects:i}})),i},handleMethod:function(t){var n=this,r=this;return function(i){var o=r.state,a=o.reasonState,l=p(r.props,r.jsPropsToReason,e);return b.d(t,i,n.self(a,l[0][11]))}},updateMethod:function(t){var n=this,r=this;return function(i){var o=r.state,a=o.reasonState,l=p(r.props,r.jsPropsToReason,e),u=b.d(t,i,n.self(a,l[0][11]));if(0===u)return k;var s=n.transitionNextTotalState(o,u);return s.reasonStateVersion!==o.reasonStateVersion?r.setState(s):0}},sendMethod:function(t){var n=this,r=this,i=p(r.props,r.jsPropsToReason,e),o=i[0];if(o[12]!==f){var a=b.b(o[12],t);return r.setState(function(e,t){var r=e.reasonState,i=b.b(a,r);if(0===i)return k;var o=n.transitionNextTotalState(e,i);return o.reasonStateVersion!==e.reasonStateVersion?o:k})}return 0},reduceMethod:function(e,t){return this.sendMethod(b.b(e,t))},render:function(){var t=this,n=this,r=p(n.props,n.jsPropsToReason,e),i=r[0],o=n.state,a=o.reasonState;return b.b(i[9],t.self(a,i[11]))}})}function g(e){return[e,h(e),[0],u,r,o,a,i,l,s,c,0,f,d,0]}function m(e,t,n){var r=e?e[0]:void 0,i=t?t[0]:void 0,o=[n],a=n[14];return a?b.d(a[0],r,i):w.createElement(n[1],{key:r,ref:i,reasonProps:o})}function v(e,t,n){var r=[function(r,i){var o=e,a=t,l=n,u=r,s=i,c=Object.assign(Object.assign({},a),{ref:s,key:u}),f=[o,c].concat(l);return w.createElement.apply(null,f)}],i=E.slice();return i[14]=r,i}n.d(t,"c",function(){return S}),n.d(t,"b",function(){return T}),n.d(t,"a",function(){return m}),n.d(t,"d",function(){return v});var y=n(9),b=(n(15),n(1)),w=n(2),x=(n.n(w),n(0)),C=n(77),k=null,S=g,T=g,E=g("interop")},function(e,t,n){"use strict";function r(){return a[0]+=1,a[0]}function i(e){var t=r(0),n=[e,t];return n.tag=248,n}function o(e){if(void 0===e)return 0;if(248===e.tag)return 1;var t=e[0];return void 0!==t?+(248===t.tag):0}n.d(t,"a",function(){return i}),n.d(t,"b",function(){return o});var a=[0]},function(e,t,n){"use strict";function r(e,t){return t.tag=e,t}n.d(t,"a",function(){return r})},function(e,t,n){"use strict";function r(e){return(255&e)<<24|(65280&e)<<8|(16711680&e)>>>8|(4278190080&e)>>>24}n.d(t,"b",function(){return r}),n.d(t,"a",function(){return i});var i=(n(0),Math.imul||function(e,t){return t|=0,((e>>16)*t<<16)+(65535&e)*t|0})},function(e,t,n){"use strict";function r(e,t){return et?e:t}n.d(t,"b",function(){return r}),n.d(t,"d",function(){return l}),n.d(t,"a",function(){return i}),n.d(t,"e",function(){return o}),n.d(t,"c",function(){return a});var l=r},function(e,t,n){"use strict";function r(e){if(e<0)throw[c.a,"String.create"];for(var t=new Array(e),n=0,r=e-1|0;n<=r;++n)t[n]=0;return t}function i(e,t,n,r){if(n>0){for(var i=t,o=(n+t|0)-1|0;i<=o;++i)e[i]=r;return 0}return 0}function o(e,t,n,r,i){if(i>0){var o=e.length-t|0;if(i<=o){for(var a=0,l=i-1|0;a<=l;++a)n[r+a|0]=e.charCodeAt(t+a|0);return 0}for(var u=0,s=o-1|0;u<=s;++u)n[r+u|0]=e.charCodeAt(t+u|0);for(var c=o,f=i-1|0;c<=f;++c)n[r+c|0]=0;return 0}return 0}function a(e,t,n,r,i){if(i>0){if(e===n){var o=e,a=t,l=r,u=i;if(ac?c:s,d=f;d>=0;--d)o[l+d|0]=o[a+d|0];return 0}if(a>l){for(var p=(o.length-a|0)-1|0,h=u-1|0,g=p>h?h:p,m=0;m<=g;++m)o[l+m|0]=o[a+m|0];return 0}return 0}var v=e.length-t|0;if(i<=v){for(var y=0,b=i-1|0;y<=b;++y)n[r+y|0]=e[t+y|0];return 0}for(var w=0,x=v-1|0;w<=x;++w)n[r+w|0]=e[t+w|0];for(var C=v,k=i-1|0;C<=k;++C)n[r+C|0]=0;return 0}return 0}function l(e){for(var t=e.length,n=new Array(t),r=0,i=t-1|0;r<=i;++r)n[r]=e.charCodeAt(r);return n}function u(e){var t=e,n=e.length,r="",i=n;if(n<=4096&&n===t.length)return String.fromCharCode.apply(null,t);for(var o=0;i>0;){var l=i<1024?i:1024,u=new Array(l);a(t,o,u,0,l),r+=String.fromCharCode.apply(null,u),i=i-l|0,o=o+l|0}return r}function s(e,t){if(t<0||t>=e.length)throw[c.a,"index out of bounds"];return e.charCodeAt(t)}n.d(t,"e",function(){return l}),n.d(t,"c",function(){return u}),n.d(t,"b",function(){return r}),n.d(t,"g",function(){return i}),n.d(t,"f",function(){return o}),n.d(t,"d",function(){return a}),n.d(t,"a",function(){return s});var c=n(0)},function(e,t,n){"use strict";function r(e){for(var t=0,n=e;;){var r=n,i=t;if(!r)return i;n=r[1],t=i+1|0}}function i(e,t){for(;;){var n=t,r=e;if(!r)return n;t=[r[0],n],e=r[1]}}function o(e){return i(e,0)}function a(e,t){return t?[s.b(e,t[0]),a(e,t[1])]:0}function l(e,t){for(;;){var n=t;if(!n)return 0;s.b(e,n[0]),t=n[1]}}function u(e){return function(t){for(var n=0,r=t;;){var o=r,a=n;if(!o)return i(a,0);var l=o[1],u=o[0];s.b(e,u)?(r=l,n=[u,a]):r=l}}}n.d(t,"d",function(){return r}),n.d(t,"c",function(){return o}),n.d(t,"b",function(){return l}),n.d(t,"a",function(){return a}),n.d(t,"e",function(){return f});var s=n(1),c=(n(16),n(48)),f=(n(0),c.a,u)},function(e,t,n){"use strict";function r(e,t,n){for(var r=new Array(n),i=0,o=t;i=e.length)throw[f.a,"index out of bounds"];return e[t]=n,0}function u(e,t){if(t<0||t>=e.length)throw[f.a,"index out of bounds"];return e[t]}function s(e,t){for(var n=new Array(e),r=0,i=e-1|0;r<=i;++r)n[r]=t;return n}function c(e,t,n,r,i){if(r<=t){for(var o=0,a=i-1|0;o<=a;++o)n[o+r|0]=e[o+t|0];return 0}for(var l=i-1|0;l>=0;--l)n[l+r|0]=e[l+t|0];return 0}n.d(t,"b",function(){return r}),n.d(t,"f",function(){return a}),n.d(t,"a",function(){return s}),n.d(t,"c",function(){return c}),n.d(t,"d",function(){return u}),n.d(t,"e",function(){return l});var f=n(0)},function(e,t,n){!function(t,n){e.exports=function(){"use strict";function e(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function t(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function n(e,n){return t(e).appendChild(n)}function r(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o=t)return a+(t-o);a+=l-o,a+=n-a%n,o=l+1}}function d(e,t){for(var n=0;n=t)return r+Math.min(a,t-i);if(i+=o-r,i+=n-i%n,r=o+1,i>=t)return r}}function h(e){for(;qa.length<=e;)qa.push(g(qa)+" ");return qa[e]}function g(e){return e[e.length-1]}function m(e,t){for(var n=[],r=0;r"€"&&(e.toUpperCase()!=e.toLowerCase()||$a.test(e))}function x(e,t){return t?!!(t.source.indexOf("\\w")>-1&&w(e))||t.test(e):w(e)}function C(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function k(e){return e.charCodeAt(0)>=768&&Ya.test(e)}function S(e,t,n){for(;(n<0?t>0:tn?-1:1;;){if(t==n)return t;var i=(t+n)/2,o=r<0?Math.ceil(i):Math.floor(i);if(o==t)return e(o)?t:n;e(o)?n=o:t=o+r}}function E(e,t,n){var o=this;this.input=n,o.scrollbarFiller=r("div",null,"CodeMirror-scrollbar-filler"),o.scrollbarFiller.setAttribute("cm-not-content","true"),o.gutterFiller=r("div",null,"CodeMirror-gutter-filler"),o.gutterFiller.setAttribute("cm-not-content","true"),o.lineDiv=i("div",null,"CodeMirror-code"),o.selectionDiv=r("div",null,null,"position: relative; z-index: 1"),o.cursorDiv=r("div",null,"CodeMirror-cursors"),o.measure=r("div",null,"CodeMirror-measure"),o.lineMeasure=r("div",null,"CodeMirror-measure"),o.lineSpace=i("div",[o.measure,o.lineMeasure,o.selectionDiv,o.cursorDiv,o.lineDiv],null,"position: relative; outline: none");var a=i("div",[o.lineSpace],"CodeMirror-lines");o.mover=r("div",[a],null,"position: relative"),o.sizer=r("div",[o.mover],"CodeMirror-sizer"),o.sizerWidth=null,o.heightForcer=r("div",null,null,"position: absolute; height: "+Va+"px; width: 1px;"),o.gutters=r("div",null,"CodeMirror-gutters"),o.lineGutter=null,o.scroller=r("div",[o.sizer,o.heightForcer,o.gutters],"CodeMirror-scroll"),o.scroller.setAttribute("tabIndex","-1"),o.wrapper=r("div",[o.scrollbarFiller,o.gutterFiller,o.scroller],"CodeMirror"),ya&&ba<8&&(o.gutters.style.zIndex=-1,o.scroller.style.paddingRight=0),wa||ha&&Na||(o.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(o.wrapper):e(o.wrapper)),o.viewFrom=o.viewTo=t.first,o.reportedViewFrom=o.reportedViewTo=t.first,o.view=[],o.renderedView=null,o.externalMeasured=null,o.viewOffset=0,o.lastWrapHeight=o.lastWrapWidth=0,o.updateLineNumbers=null,o.nativeBarWidth=o.barHeight=o.barWidth=0,o.scrollbarsClipped=!1,o.lineNumWidth=o.lineNumInnerWidth=o.lineNumChars=null,o.alignWidgets=!1,o.cachedCharWidth=o.cachedTextHeight=o.cachedPaddingH=null,o.maxLine=null,o.maxLineLength=0,o.maxLineChanged=!1,o.wheelDX=o.wheelDY=o.wheelStartX=o.wheelStartY=null,o.shift=!1,o.selForContextMenu=null,o.activeTouch=null,n.init(o)}function M(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(t=e.first&&tn?I(n,M(e,n).text.length):B(t,M(e,t.line).text.length)}function B(e,t){var n=e.ch;return null==n||n>t?I(e.line,t):n<0?I(e.line,0):e}function j(e,t){for(var n=[],r=0;r=t:o.to>t);(r||(r=[])).push(new q(a,o.from,u?null:o.to))}}return r}function Z(e,t,n){var r;if(e)for(var i=0;i=t:o.to>t);if(l||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var u=null==o.from||(a.inclusiveLeft?o.from<=t:o.from0&&l)for(var x=0;x0)){var c=[u,1],f=R(s.from,l.from),p=R(s.to,l.to);(f<0||!a.inclusiveLeft&&!f)&&c.push({from:s.from,to:l.from}),(p>0||!a.inclusiveRight&&!p)&&c.push({from:l.to,to:s.to}),i.splice.apply(i,c),u+=c.length-3}}return i}function ne(e){var t=e.markedSpans;if(t){for(var n=0;n=0&&f<=0||c<=0&&f>=0)&&(c<=0&&(u.marker.inclusiveRight&&i.inclusiveLeft?R(s.to,n)>=0:R(s.to,n)>0)||c>=0&&(u.marker.inclusiveRight&&i.inclusiveLeft?R(s.from,r)<=0:R(s.from,r)<0)))return!0}}}function fe(e){for(var t;t=ue(e);)e=t.find(-1,!0).line;return e}function de(e){for(var t;t=se(e);)e=t.find(1,!0).line;return e}function pe(e){for(var t,n;t=se(e);)e=t.find(1,!0).line,(n||(n=[])).push(e);return n}function he(e,t){var n=M(e,t),r=fe(n);return n==r?t:P(r)}function ge(e,t){if(t>e.lastLine())return t;var n,r=M(e,t);if(!me(e,r))return t;for(;n=se(r);)r=n.find(1,!0).line;return P(r)+1}function me(e,t){var n=Qa&&t.markedSpans;if(n)for(var r=void 0,i=0;it.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}function xe(e,t,n,r){if(!e)return r(t,n,"ltr",0);for(var i=!1,o=0;ot||t==n&&a.to==t)&&(r(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr",o),i=!0)}i||r(t,n,"ltr")}function Ce(e,t,n){var r;Za=null;for(var i=0;it)return i;o.to==t&&(o.from!=o.to&&"before"==n?r=i:Za=i),o.from==t&&(o.from!=o.to&&"before"!=n?r=i:Za=i)}return null!=r?r:Za}function ke(e,t){var n=e.order;return null==n&&(n=e.order=Ja(e.text,t)),n}function Se(e,t){return e._handlers&&e._handlers[t]||el}function Te(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else if(e.detachEvent)e.detachEvent("on"+t,n);else{var r=e._handlers,i=r&&r[t];if(i){var o=d(i,n);o>-1&&(r[t]=i.slice(0,o).concat(i.slice(o+1)))}}}function Ee(e,t){var n=Se(e,t);if(n.length)for(var r=Array.prototype.slice.call(arguments,2),i=0;i0}function Oe(e){e.prototype.on=function(e,t){tl(this,e,t)},e.prototype.off=function(e,t){Te(this,e,t)}}function Pe(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function Ae(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function De(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function _e(e){Pe(e),Ae(e)}function Ie(e){return e.target||e.srcElement}function Re(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),Oa&&e.ctrlKey&&1==t&&(t=3),t}function Fe(e){if(null==za){var t=r("span","​");n(e,r("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(za=t.offsetWidth<=1&&t.offsetHeight>2&&!(ya&&ba<8))}var i=za?r("span","​"):r("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return i.setAttribute("cm-text",""),i}function He(e){if(null!=Ua)return Ua;var r=n(e,document.createTextNode("AخA")),i=_a(r,0,1).getBoundingClientRect(),o=_a(r,1,2).getBoundingClientRect();return t(e),!(!i||i.left==i.right)&&(Ua=o.right-i.right<3)}function We(e){if(null!=al)return al;var t=n(e,r("span","x")),i=t.getBoundingClientRect(),o=_a(t,0,1).getBoundingClientRect();return al=Math.abs(i.left-o.left)>1}function ze(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),ll[e]=t}function Ue(e,t){ul[e]=t}function Ve(e){if("string"==typeof e&&ul.hasOwnProperty(e))e=ul[e];else if(e&&"string"==typeof e.name&&ul.hasOwnProperty(e.name)){var t=ul[e.name];"string"==typeof t&&(t={name:t}),e=b(t,e),e.name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return Ve("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return Ve("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function Be(e,t){t=Ve(t);var n=ll[t.name];if(!n)return Be(e,"text/plain");var r=n(e,t);if(sl.hasOwnProperty(t.name)){var i=sl[t.name];for(var o in i)i.hasOwnProperty(o)&&(r.hasOwnProperty(o)&&(r["_"+o]=r[o]),r[o]=i[o])}if(r.name=t.name,t.helperType&&(r.helperType=t.helperType),t.modeProps)for(var a in t.modeProps)r[a]=t.modeProps[a];return r}function je(e,t){c(t,sl.hasOwnProperty(e)?sl[e]:sl[e]={})}function Ke(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n}function Ge(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function qe(e,t,n){return!e.startState||e.startState(t,n)}function $e(e,t,n,r){var i=[e.state.modeGen],o={};nt(e,t.text,e.doc.mode,n,function(e,t){return i.push(e,t)},o,r);for(var a=n.state,l=0;le&&i.splice(u,1,e,i[u+1],r),u+=2,s=Math.min(e,r)}if(t)if(l.opaque)i.splice(n,u-n,e,"overlay "+t),u=n+2;else for(;ne.options.maxHighlightLength&&Ke(e.doc.mode,r.state),o=$e(e,t,r);i&&(r.state=i),t.stateAfter=r.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function Xe(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return new dl(r,!0,t);var o=rt(e,t,n),a=o>r.first&&M(r,o-1).stateAfter,l=a?dl.fromSaved(r,a,o):new dl(r,qe(r.mode),o);return r.iter(o,t,function(n){Qe(e,n.text,l);var r=l.line;n.stateAfter=r==t-1||r%5==0||r>=i.viewFrom&&rt.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}function et(e,t,n,r){var i,o=e.doc,a=o.mode;t=V(o,t);var l,u=M(o,t.line),s=Xe(e,t.line,n),c=new cl(u.text,e.options.tabSize,s);for(r&&(l=[]);(r||c.pose.options.maxHighlightLength?(l=!1,a&&Qe(e,t,r,f.pos),f.pos=t.length,u=null):u=tt(Je(n,f,r.state,d),o),d){var p=d[0].name;p&&(u="m-"+(u?p+" "+u:p))}if(!l||c!=u){for(;sa;--l){if(l<=o.first)return o.first;var u=M(o,l-1),s=u.stateAfter;if(s&&(!n||l+(s instanceof fl?s.lookAhead:0)<=o.modeFrontier))return l;var c=f(u.text,null,e.options.tabSize);(null==i||r>c)&&(i=l-1,r=c)}return i}function it(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiern;r--){var i=M(e,r).stateAfter;if(i&&(!(i instanceof fl)||r+i.lookAhead1&&!/ /.test(e))return e;for(var n=t,r="",i=0;is&&f.from<=s));d++);if(f.to>=c)return e(n,r,i,o,a,l,u);e(n,r.slice(0,f.to-s),i,o,null,l,u),o=null,r=r.slice(f.to-s),s=f.to}}}function pt(e,t,n,r){var i=!r&&n.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!r&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",n.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function ht(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var a,l,u,s,c,f,d,p=i.length,h=0,g=1,m="",v=0;;){if(v==h){u=s=c=f=l="",d=null,v=1/0;for(var y=[],b=void 0,w=0;wh||C.collapsed&&x.to==h&&x.from==h)?(null!=x.to&&x.to!=h&&v>x.to&&(v=x.to,s=""),C.className&&(u+=" "+C.className),C.css&&(l=(l?l+";":"")+C.css),C.startStyle&&x.from==h&&(c+=" "+C.startStyle),C.endStyle&&x.to==v&&(b||(b=[])).push(C.endStyle,x.to),C.title&&!f&&(f=C.title),C.collapsed&&(!d||ae(d.marker,C)<0)&&(d=x)):x.from>h&&v>x.from&&(v=x.from)}if(b)for(var k=0;k=p)break;for(var T=Math.min(p,v);;){if(m){var E=h+m.length;if(!d){var M=E>T?m.slice(0,T-h):m;t.addToken(t,M,a?a+u:u,c,h+M.length==v?s:"",f,l)}if(E>=T){m=m.slice(T-h),h=T;break}h=E,c=""}m=i.slice(o,o=n[g++]),a=lt(n[g++],t.cm.options)}}else for(var L=1;L2&&o.push((u.bottom+s.top)/2-n.top)}}o.push(n.bottom-n.top)}}function Bt(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;rn)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function jt(e,t){t=fe(t);var r=P(t),i=e.display.externalMeasured=new gt(e.doc,t,r);i.lineN=r;var o=i.built=ut(e,i);return i.text=o.pre,n(e.display.lineMeasure,o.pre),i}function Kt(e,t,n,r){return $t(e,qt(e,t),n,r)}function Gt(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&tt)&&(o=u-l,i=o-1,t>=u&&(a="right")),null!=i){if(r=e[s+2],l==u&&n==(r.insertLeft?"left":"right")&&(a=n),"left"==n&&0==i)for(;s&&e[s-2]==e[s-3]&&e[s-1].insertLeft;)r=e[2+(s-=3)],a="left";if("right"==n&&i==u-l)for(;s=0&&(n=e[i]).left==n.right;i--);return n}function Qt(e,t,n,r){var i,o=Yt(t.map,n,r),a=o.node,l=o.start,u=o.end,s=o.collapse;if(3==a.nodeType){for(var c=0;c<4;c++){for(;l&&k(t.line.text.charAt(o.coverStart+l));)--l;for(;o.coverStart+u0&&(s=r="right");var f;i=e.options.lineWrapping&&(f=a.getClientRects()).length>1?f["right"==r?f.length-1:0]:a.getBoundingClientRect()}if(ya&&ba<9&&!l&&(!i||!i.left&&!i.right)){var d=a.parentNode.getClientRects()[0];i=d?{left:d.left,right:d.left+wn(e.display),top:d.top,bottom:d.bottom}:wl}for(var p=i.top-t.rect.top,h=i.bottom-t.rect.top,g=(p+h)/2,m=t.view.measure.heights,v=0;v=r.text.length?(s=r.text.length,c="before"):s<=0&&(s=0,c="after"),!u)return a("before"==c?s-1:s,"before"==c);var f=Ce(u,s,c),d=Za,p=l(s,f,"before"==c);return null!=d&&(p.other=l(s,d,"before"!=c)),p}function cn(e,t){var n=0;t=V(e.doc,t),e.options.lineWrapping||(n=wn(e.display)*t.ch);var r=M(e.doc,t.line),i=ye(r)+Rt(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function fn(e,t,n,r,i){var o=I(e,t,n);return o.xRel=i,r&&(o.outside=!0),o}function dn(e,t,n){var r=e.doc;if((n+=e.display.viewOffset)<0)return fn(r.first,0,null,!0,-1);var i=A(r,n),o=r.first+r.size-1;if(i>o)return fn(r.first+r.size-1,M(r,o).text.length,null,!0,1);t<0&&(t=0);for(var a=M(r,i);;){var l=mn(e,a,i,t,n),u=se(a),s=u&&u.find(0,!0);if(!u||!(l.ch>s.from.ch||l.ch==s.from.ch&&l.xRel>0))return l;i=P(a=s.to.line)}}function pn(e,t,n,r){r-=on(t);var i=t.text.length,o=T(function(t){return $t(e,n,t-1).bottom<=r},i,0);return i=T(function(t){return $t(e,n,t).top>r},o,i),{begin:o,end:i}}function hn(e,t,n,r){return n||(n=qt(e,t)),pn(e,t,n,an(e,t,$t(e,n,r),"line").top)}function gn(e,t,n,r){return!(e.bottom<=n)&&(e.top>n||(r?e.left:e.right)>t)}function mn(e,t,n,r,i){i-=ye(t);var o=qt(e,t),a=on(t),l=0,u=t.text.length,s=!0,c=ke(t,e.doc.direction);if(c){var f=(e.options.lineWrapping?yn:vn)(e,t,n,o,c,r,i);s=1!=f.level,l=s?f.from:f.to-1,u=s?f.to:f.from-1}var d,p,h=null,g=null,m=T(function(t){var n=$t(e,o,t);return n.top+=a,n.bottom+=a,!!gn(n,r,i,!1)&&(n.top<=i&&n.left<=r&&(h=t,g=n),!0)},l,u),v=!1;if(g){var y=r-g.left=w.bottom}return m=S(t.text,m,1),fn(n,m,p,v,r-d)}function vn(e,t,n,r,i,o,a){var l=T(function(l){var u=i[l],s=1!=u.level;return gn(sn(e,I(n,s?u.to:u.from,s?"before":"after"),"line",t,r),o,a,!0)},0,i.length-1),u=i[l];if(l>0){var s=1!=u.level,c=sn(e,I(n,s?u.from:u.to,s?"after":"before"),"line",t,r);gn(c,o,a,!0)&&c.top>a&&(u=i[l-1])}return u}function yn(e,t,n,r,i,o,a){var l=pn(e,t,r,a),u=l.begin,s=l.end;/\s/.test(t.text.charAt(s-1))&&s--;for(var c=null,f=null,d=0;d=s||p.to<=u)){var h=1!=p.level,g=$t(e,r,h?Math.min(s,p.to)-1:Math.max(u,p.from)).right,m=gm)&&(c=p,f=m)}}return c||(c=i[i.length-1]),c.froms&&(c={from:c.from,to:s,level:c.level}),c}function bn(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==gl){gl=r("pre");for(var i=0;i<49;++i)gl.appendChild(document.createTextNode("x")),gl.appendChild(r("br"));gl.appendChild(document.createTextNode("x"))}n(e.measure,gl);var o=gl.offsetHeight/50;return o>3&&(e.cachedTextHeight=o),t(e.measure),o||1}function wn(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=r("span","xxxxxxxxxx"),i=r("pre",[t]);n(e.measure,i);var o=t.getBoundingClientRect(),a=(o.right-o.left)/10;return a>2&&(e.cachedCharWidth=a),a||10}function xn(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a)n[e.options.gutters[a]]=o.offsetLeft+o.clientLeft+i,r[e.options.gutters[a]]=o.clientWidth;return{fixedPos:Cn(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function Cn(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function kn(e){var t=bn(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/wn(e.display)-3);return function(i){if(me(e.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,r=0;r=e.display.viewTo||l.to().line0?t.blinker=setInterval(function(){return t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function Dn(e){e.state.focused||(e.display.input.focus(),In(e))}function _n(e){e.state.delayingBlurEvent=!0,setTimeout(function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,Rn(e))},100)}function In(e,t){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(Ee(e,"focus",e,t),e.state.focused=!0,l(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),wa&&setTimeout(function(){return e.display.input.reset(!0)},20)),e.display.input.receivedFocus()),An(e))}function Rn(e,t){e.state.delayingBlurEvent||(e.state.focused&&(Ee(e,"blur",e,t),e.state.focused=!1,Fa(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150))}function Fn(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r.005||u<-.005)&&(O(i.line,o),Hn(i.line),i.rest))for(var s=0;s=a&&(o=A(t,ye(M(t,u))-e.wrapper.clientHeight),a=u)}return{from:o,to:Math.max(a,o+1)}}function zn(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=Cn(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",a=0;a(window.innerHeight||document.documentElement.clientHeight)&&(o=!1),null!=o&&!Ea){var a=r("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-Rt(e.display))+"px;\n height: "+(t.bottom-t.top+Wt(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(a),a.scrollIntoView(o),e.display.lineSpace.removeChild(a)}}}function Bn(e,t,n,r){null==r&&(r=0);var i;e.options.lineWrapping||t!=n||(t=t.ch?I(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t,n="before"==t.sticky?I(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,l=sn(e,t),u=n&&n!=t?sn(e,n):l;i={left:Math.min(l.left,u.left),top:Math.min(l.top,u.top)-r,right:Math.max(l.left,u.left),bottom:Math.max(l.bottom,u.bottom)+r};var s=Kn(e,i),c=e.doc.scrollTop,f=e.doc.scrollLeft;if(null!=s.scrollTop&&(Zn(e,s.scrollTop),Math.abs(e.doc.scrollTop-c)>1&&(a=!0)),null!=s.scrollLeft&&(er(e,s.scrollLeft),Math.abs(e.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}function jn(e,t){var n=Kn(e,t);null!=n.scrollTop&&Zn(e,n.scrollTop),null!=n.scrollLeft&&er(e,n.scrollLeft)}function Kn(e,t){var n=e.display,r=bn(e.display);t.top<0&&(t.top=0);var i=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:n.scroller.scrollTop,o=Ut(e),a={};t.bottom-t.top>o&&(t.bottom=t.top+o);var l=e.doc.height+Ft(n),u=t.topl-r;if(t.topi+o){var c=Math.min(t.top,(s?l:t.bottom)-o);c!=i&&(a.scrollTop=c)}var f=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft,d=zt(e)-(e.options.fixedGutter?n.gutters.offsetWidth:0),p=t.right-t.left>d;return p&&(t.right=t.left+d),t.left<10?a.scrollLeft=0:t.leftd+f-3&&(a.scrollLeft=t.right+(p?0:10)-d),a}function Gn(e,t){null!=t&&(Xn(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function qn(e){Xn(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function $n(e,t,n){null==t&&null==n||Xn(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Yn(e,t){Xn(e),e.curOp.scrollToPos=t}function Xn(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Qn(e,cn(e,t.from),cn(e,t.to),t.margin))}function Qn(e,t,n,r){var i=Kn(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-r,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+r});$n(e,i.scrollLeft,i.scrollTop)}function Zn(e,t){Math.abs(e.doc.scrollTop-t)<2||(ha||Or(e,{top:t}),Jn(e,t,!0),ha&&Or(e),kr(e,100))}function Jn(e,t,n){t=Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t),(e.display.scroller.scrollTop!=t||n)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function er(e,t,n,r){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!r||(e.doc.scrollLeft=t,zn(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function tr(e){var t=e.display,n=t.gutters.offsetWidth,r=Math.round(e.doc.height+Ft(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+Wt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}function nr(e,t){t||(t=tr(e));var n=e.display.barWidth,r=e.display.barHeight;rr(e,t);for(var i=0;i<4&&n!=e.display.barWidth||r!=e.display.barHeight;i++)n!=e.display.barWidth&&e.options.lineWrapping&&Fn(e),rr(e,tr(e)),n=e.display.barWidth,r=e.display.barHeight}function rr(e,t){var n=e.display,r=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px",n.heightForcer.style.borderBottom=r.bottom+"px solid transparent",r.right&&r.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=r.bottom+"px",n.scrollbarFiller.style.width=r.right+"px"):n.scrollbarFiller.style.display="",r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}function ir(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&Fa(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new kl[e.options.scrollbarStyle](function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),tl(t,"mousedown",function(){e.state.focused&&setTimeout(function(){return e.display.input.focus()},0)}),t.setAttribute("cm-not-content","true")},function(t,n){"horizontal"==n?er(e,t):Zn(e,t)},e),e.display.scrollbars.addClass&&l(e.display.wrapper,e.display.scrollbars.addClass)}function or(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Sl},vt(e.curOp)}function ar(e){bt(e.curOp,function(e){for(var t=0;t=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new Tl(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function sr(e){e.updatedDisplay=e.mustUpdate&&Lr(e.cm,e.update)}function cr(e){var t=e.cm,n=t.display;e.updatedDisplay&&Fn(t),e.barMeasure=tr(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Kt(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+Wt(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-zt(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}function fr(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeftt)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)Qa&&he(e.doc,t)i.viewFrom?br(e):(i.viewFrom+=r,i.viewTo+=r);else if(t<=i.viewFrom&&n>=i.viewTo)br(e);else if(t<=i.viewFrom){var o=wr(e,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):br(e)}else if(n>=i.viewTo){var a=wr(e,t,t,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):br(e)}else{var l=wr(e,t,t,-1),u=wr(e,n,n+r,1);l&&u?(i.view=i.view.slice(0,l.index).concat(mt(e,l.lineN,u.lineN)).concat(i.view.slice(u.index)),i.viewTo+=r):br(e)}var s=i.externalMeasured;s&&(n=i.lineN&&t=r.viewTo)){var o=r.view[En(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==d(a,n)&&a.push(n)}}}function br(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function wr(e,t,n,r){var i,o=En(e,t),a=e.display.view;if(!Qa||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var l=e.display.viewFrom,u=0;u0){if(o==a.length-1)return null;i=l+a[o].size-t,o++}else i=l-t;t+=i,n+=i}for(;he(e.doc,n)!=n;){if(o==(r<0?0:a.length-1))return null;n+=r*a[o-(r<0?1:0)].size,o+=r}return{index:o,lineN:n}}function xr(e,t,n){var r=e.display;0==r.view.length||t>=r.viewTo||n<=r.viewFrom?(r.view=mt(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=mt(e,t,r.viewFrom).concat(r.view):r.viewFromn&&(r.view=r.view.slice(0,En(e,n)))),r.viewTo=n}function Cr(e){for(var t=e.display.view,n=0,r=0;r=e.display.viewTo)){var n=+new Date+e.options.workTime,r=Xe(e,t.highlightFrontier),i=[];t.iter(r.line,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(r.line>=e.display.viewFrom){var a=o.styles,l=o.text.length>e.options.maxHighlightLength?Ke(t.mode,r.state):null,u=$e(e,o,r,!0);l&&(r.state=l),o.styles=u.styles;var s=o.styleClasses,c=u.classes;c?o.styleClasses=c:s&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||s!=c&&(!s||!c||s.bgClass!=c.bgClass||s.textClass!=c.textClass),d=0;!f&&dn)return kr(e,e.options.workDelay),!0}),t.highlightFrontier=r.line,t.modeFrontier=Math.max(t.modeFrontier,r.line),i.length&&pr(e,function(){for(var t=0;t=r.viewFrom&&n.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&r.renderedView==r.view&&0==Cr(e))return!1;Un(e)&&(br(e),n.dims=xn(e));var o=i.first+i.size,a=Math.max(n.visible.from-e.options.viewportMargin,i.first),l=Math.min(o,n.visible.to+e.options.viewportMargin);r.viewFroml&&r.viewTo-l<20&&(l=Math.min(o,r.viewTo)),Qa&&(a=he(e.doc,a),l=ge(e.doc,l));var u=a!=r.viewFrom||l!=r.viewTo||r.lastWrapHeight!=n.wrapperHeight||r.lastWrapWidth!=n.wrapperWidth;xr(e,a,l),r.viewOffset=ye(M(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var s=Cr(e);if(!u&&0==s&&!n.force&&r.renderedView==r.view&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return!1;var c=Er(e);return s>4&&(r.lineDiv.style.display="none"),Pr(e,r.updateLineNumbers,n.dims),s>4&&(r.lineDiv.style.display=""),r.renderedView=r.view,Mr(c),t(r.cursorDiv),t(r.selectionDiv),r.gutters.style.height=r.sizer.style.minHeight=0,u&&(r.lastWrapHeight=n.wrapperHeight,r.lastWrapWidth=n.wrapperWidth,kr(e,400)),r.updateLineNumbers=null,!0}function Nr(e,t){for(var n=t.viewport,r=!0;(r&&e.options.lineWrapping&&t.oldDisplayWidth!=zt(e)||(n&&null!=n.top&&(n={top:Math.min(e.doc.height+Ft(e.display)-Ut(e),n.top)}),t.visible=Wn(e.display,e.doc,n),!(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)))&&Lr(e,t);r=!1){Fn(e);var i=tr(e);Mn(e),nr(e,i),Dr(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function Or(e,t){var n=new Tl(e,t);if(Lr(e,n)){Fn(e),Nr(e,n);var r=tr(e);Mn(e),nr(e,r),Dr(e,r),n.finish()}}function Pr(e,n,r){function i(t){var n=t.nextSibling;return wa&&Oa&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var o=e.display,a=e.options.lineNumbers,l=o.lineDiv,u=l.firstChild,s=o.view,c=o.viewFrom,f=0;f-1&&(h=!1),Ct(e,p,c,r)),h&&(t(p.lineNumber),p.lineNumber.appendChild(document.createTextNode(_(e.options,c)))),u=p.node.nextSibling}else{var g=Ot(e,p,c,r);l.insertBefore(g,u)}c+=p.size}for(;u;)u=i(u)}function Ar(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function Dr(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Wt(e)+"px"}function _r(e){var n=e.display.gutters,i=e.options.gutters;t(n);for(var o=0;o-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function Rr(e){var t=e.wheelDeltaX,n=e.wheelDeltaY;return null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail),null==n&&e.detail&&e.axis==e.VERTICAL_AXIS?n=e.detail:null==n&&(n=e.wheelDelta),{x:t,y:n}}function Fr(e){var t=Rr(e);return t.x*=Ml,t.y*=Ml,t}function Hr(e,t){var n=Rr(t),r=n.x,i=n.y,o=e.display,a=o.scroller,l=a.scrollWidth>a.clientWidth,u=a.scrollHeight>a.clientHeight;if(r&&l||i&&u){if(i&&Oa&&wa)e:for(var s=t.target,c=o.view;s!=a;s=s.parentNode)for(var f=0;f=0){var a=z(o.from(),i.from()),l=W(o.to(),i.to()),u=o.empty()?i.from()==i.head:o.from()==o.head;r<=t&&--t,e.splice(--r,2,new Nl(u?l:a,u?a:l))}}return new Ll(e,t)}function zr(e,t){return new Ll([new Nl(e,t||e)],0)}function Ur(e){return e.text?I(e.from.line+e.text.length-1,g(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function Vr(e,t){if(R(e,t.from)<0)return e;if(R(e,t.to)<=0)return Ur(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Ur(t).ch-t.to.ch),I(n,r)}function Br(e,t){for(var n=[],r=0;r1&&e.remove(l.line+1,h-1),e.insert(l.line+1,y)}wt(e,"change",e,t)}function Xr(e,t,n){function r(e,i,o){if(e.linked)for(var a=0;a1&&!e.done[e.done.length-2].ranges?(e.done.pop(),g(e.done)):void 0}function ii(e,t,n,r){var i=e.history;i.undone.length=0;var o,a,l=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&i.lastModTime>l-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=ri(i,i.lastOp==r)))a=g(o.changes),0==R(t.from,t.to)&&0==R(t.from,a.to)?a.to=Ur(t):o.changes.push(ti(e,t));else{var u=g(i.done);for(u&&u.ranges||li(e.sel,i.done),o={changes:[ti(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=l,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,a||Ee(e,"historyAdded")}function oi(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function ai(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||oi(e,o,g(i.done),t))?i.done[i.done.length-1]=t:li(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&!1!==r.clearRedo&&ni(i.undone)}function li(e,t){var n=g(t);n&&n.ranges&&n.equals(e)||t.push(e)}function ui(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans),++o})}function si(e){if(!e)return null;for(var t,n=0;n-1&&(g(l)[f]=s[f],delete s[f])}}}return r}function pi(e,t,n,r){if(r){var i=e.anchor;if(n){var o=R(t,i)<0;o!=R(n,i)<0?(i=t,t=n):o!=R(t,n)<0&&(t=n)}return new Nl(i,t)}return new Nl(n||t,t)}function hi(e,t,n,r,i){null==i&&(i=e.cm&&(e.cm.display.shift||e.extend)),wi(e,new Ll([pi(e.sel.primary(),t,n,i)],0),r)}function gi(e,t,n){for(var r=[],i=e.cm&&(e.cm.display.shift||e.extend),o=0;o=t.ch:l.to>t.ch))){if(i&&(Ee(u,"beforeCursorEnter"),u.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!u.atomic)continue;if(n){var s=u.find(r<0?1:-1),c=void 0;if((r<0?u.inclusiveRight:u.inclusiveLeft)&&(s=Mi(e,s,-r,s&&s.line==t.line?o:null)),s&&s.line==t.line&&(c=R(s,n))&&(r<0?c<0:c>0))return Ti(e,s,t,r,i)}var f=u.find(r<0?-1:1);return(r<0?u.inclusiveLeft:u.inclusiveRight)&&(f=Mi(e,f,r,f.line==t.line?o:null)),f?Ti(e,f,t,r,i):null}}return t}function Ei(e,t,n,r,i){var o=r||1;return Ti(e,t,n,o,i)||!i&&Ti(e,t,n,o,!0)||Ti(e,t,n,-o,i)||!i&&Ti(e,t,n,-o,!0)||(e.cantEdit=!0,I(e.first,0))}function Mi(e,t,n,r){return n<0&&0==t.ch?t.line>e.first?V(e,I(t.line-1)):null:n>0&&t.ch==(r||M(e,t.line)).text.length?t.line=0;--i)Pi(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text,origin:t.origin});else Pi(e,t)}}function Pi(e,t){if(1!=t.text.length||""!=t.text[0]||0!=R(t.from,t.to)){var n=Br(e,t);ii(e,t,n,e.cm?e.cm.curOp.id:NaN),_i(e,t,n,J(e,t));var r=[];Xr(e,function(e,n){n||-1!=d(r,e.history)||(Wi(e.history,t),r.push(e.history)),_i(e,t,null,J(e,t))})}}function Ai(e,t,n){if(!e.cm||!e.cm.state.suppressEdits||n){for(var r,i=e.history,o=e.sel,a="undo"==t?i.done:i.undone,l="undo"==t?i.undone:i.done,u=0;u=0;--f){var p=function(n){var i=r.changes[n];if(i.origin=t,c&&!Ni(e,i,!1))return a.length=0,{};s.push(ti(e,i));var o=n?Br(e,i):g(a);_i(e,i,o,fi(e,i)),!n&&e.cm&&e.cm.scrollIntoView({from:i.from,to:Ur(i)});var l=[];Xr(e,function(e,t){t||-1!=d(l,e.history)||(Wi(e.history,i),l.push(e.history)),_i(e,i,null,fi(e,i))})}(f);if(p)return p.v}}}}function Di(e,t){if(0!=t&&(e.first+=t,e.sel=new Ll(m(e.sel.ranges,function(e){return new Nl(I(e.anchor.line+t,e.anchor.ch),I(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){vr(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;re.lastLine())){if(t.from.lineo&&(t={from:t.from,to:I(o,M(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=L(e,t.from,t.to),n||(n=Br(e,t)),e.cm?Ii(e.cm,t,r):Yr(e,t,r),xi(e,n,ja)}}function Ii(e,t,n){var r=e.doc,i=e.display,o=t.from,a=t.to,l=!1,u=o.line;e.options.lineWrapping||(u=P(fe(M(r,o.line))),r.iter(u,a.line+1,function(e){if(e==i.maxLine)return l=!0,!0})),r.sel.contains(t.from,t.to)>-1&&Le(e),Yr(r,t,n,kn(e)),e.options.lineWrapping||(r.iter(u,o.line+t.text.length,function(e){var t=be(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),it(r,o.line),kr(e,400);var s=t.text.length-(a.line-o.line)-1;t.full?vr(e):o.line!=a.line||1!=t.text.length||$r(e.doc,t)?vr(e,o.line,a.line+1,s):yr(e,o.line,"text");var c=Ne(e,"changes"),f=Ne(e,"change");if(f||c){var d={from:o,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&wt(e,"change",e,d),c&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(d)}e.display.selForContextMenu=null}function Ri(e,t,n,r,i){if(r||(r=n),R(r,n)<0){var o;o=[r,n],n=o[0],r=o[1]}"string"==typeof t&&(t=e.splitLines(t)),Oi(e,{from:n,to:r,text:t,origin:i})}function Fi(e,t,n,r){n0||0==l&&!1!==a.clearWhenEmpty)return a;if(a.replacedWith&&(a.collapsed=!0,a.widgetNode=i("span",[a.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||a.widgetNode.setAttribute("cm-ignore-events","true"),r.insertLeft&&(a.widgetNode.insertLeft=!0)),a.collapsed){if(ce(e,t.line,t,n,a)||t.line!=n.line&&ce(e,n.line,t,n,a))throw new Error("Inserting collapsed marker partially overlapping an existing one");G()}a.addToHistory&&ii(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var u,s=t.line,f=e.cm;if(e.iter(s,n.line+1,function(e){f&&a.collapsed&&!f.options.lineWrapping&&fe(e)==f.display.maxLine&&(u=!0),a.collapsed&&s!=t.line&&O(e,0),X(e,new q(a,s==t.line?t.ch:null,s==n.line?n.ch:null)),++s}),a.collapsed&&e.iter(t.line,n.line+1,function(t){me(e,t)&&O(t,0)}),a.clearOnEnter&&tl(a,"beforeCursorEnter",function(){return a.clear()}),a.readOnly&&(K(),(e.history.done.length||e.history.undone.length)&&e.clearHistory()),a.collapsed&&(a.id=++Pl,a.atomic=!0),f){if(u&&(f.curOp.updateMaxLine=!0),a.collapsed)vr(f,t.line,n.line+1);else if(a.className||a.title||a.startStyle||a.endStyle||a.css)for(var d=t.line;d<=n.line;d++)yr(f,d,"text");a.atomic&&ki(f.doc),wt(f,"markerAdded",f,a)}return a}function Gi(e,t,n,r,i){r=c(r),r.shared=!1;var o=[Ki(e,t,n,r,i)],a=o[0],l=r.widgetNode;return Xr(e,function(e){l&&(r.widgetNode=l.cloneNode(!0)),o.push(Ki(e,V(e,t),V(e,n),r,i));for(var u=0;u-1)return t.state.draggingText(e),void setTimeout(function(){return t.display.input.focus()},20);try{var u=e.dataTransfer.getData("Text");if(u){var s;if(t.state.draggingText&&!t.state.draggingText.copy&&(s=t.listSelections()),xi(t.doc,zr(n,n)),s)for(var c=0;c=0;t--)Ri(e.doc,"",r[t].from,r[t].to,"+delete");qn(e)})}function po(e,t,n){var r=S(e.text,t+n,n);return r<0||r>e.text.length?null:r}function ho(e,t,n){var r=po(e,t.ch,n);return null==r?null:new I(t.line,r,n<0?"after":"before")}function go(e,t,n,r,i){if(e){var o=ke(n,t.doc.direction);if(o){var a,l=i<0?g(o):o[0],u=i<0==(1==l.level),s=u?"after":"before";if(l.level>0||"rtl"==t.doc.direction){var c=qt(t,n);a=i<0?n.text.length-1:0;var f=$t(t,c,a).top;a=T(function(e){return $t(t,c,e).top==f},i<0==(1==l.level)?l.from:l.to-1,a),"before"==s&&(a=po(n,a,1))}else a=i<0?l.to:l.from;return new I(r,a,s)}}return new I(r,i<0?n.text.length:0,i<0?"before":"after")}function mo(e,t,n,r){var i=ke(t,e.doc.direction);if(!i)return ho(t,n,r);n.ch>=t.text.length?(n.ch=t.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var o=Ce(i,n.ch,n.sticky),a=i[o];if("ltr"==e.doc.direction&&a.level%2==0&&(r>0?a.to>n.ch:a.from=a.from&&d>=c.begin)){var p=f?"before":"after";return new I(n.line,d,p)}}var h=function(e,t,r){for(var o=function(e,t){return t?new I(n.line,u(e,1),"before"):new I(n.line,e,"after")};e>=0&&e0==(1!=a.level),s=l?r.begin:u(r.end,-1);if(a.from<=s&&s0?c.end:u(c.begin,-1);return null==m||r>0&&m==t.text.length||!(g=h(r>0?0:i.length-1,r,s(m)))?null:g}function vo(e,t){var n=M(e.doc,t),r=fe(n);return r!=n&&(t=P(r)),go(!0,e,r,t,1)}function yo(e,t){var n=M(e.doc,t),r=de(n);return r!=n&&(t=P(r)),go(!0,e,n,t,-1)}function bo(e,t){var n=vo(e,t.line),r=M(e.doc,n.line),i=ke(r,e.doc.direction);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),a=t.line==n.line&&t.ch<=o&&t.ch;return I(n.line,a?0:o,n.sticky)}return n}function wo(e,t,n){if("string"==typeof t&&!(t=Bl[t]))return!1;e.display.input.ensurePolled();var r=e.display.shift,i=!1;try{e.isReadOnly()&&(e.state.suppressEdits=!0),n&&(e.display.shift=!1),i=t(e)!=Ba}finally{e.display.shift=r,e.state.suppressEdits=!1}return i}function xo(e,t,n){for(var r=0;r-1&&(R((i=l.ranges[i]).from(),t)<0||t.xRel>0)&&(R(i.to(),t)>0||t.xRel<0)?Io(e,r,t,o):Fo(e,r,t,o)}function Io(e,t,n,r){var i=e.display,o=!1,a=hr(e,function(t){wa&&(i.scroller.draggable=!1),e.state.draggingText=!1,Te(document,"mouseup",a),Te(document,"mousemove",l),Te(i.scroller,"dragstart",u),Te(i.scroller,"drop",a),o||(Pe(t),r.addNew||hi(e.doc,n,null,null,r.extend),wa||ya&&9==ba?setTimeout(function(){document.body.focus(),i.input.focus()},20):i.input.focus())}),l=function(e){o=o||Math.abs(t.clientX-e.clientX)+Math.abs(t.clientY-e.clientY)>=10},u=function(){return o=!0};wa&&(i.scroller.draggable=!0),e.state.draggingText=a,a.copy=!r.moveOnDrag,i.scroller.dragDrop&&i.scroller.dragDrop(),tl(document,"mouseup",a),tl(document,"mousemove",l),tl(i.scroller,"dragstart",u),tl(i.scroller,"drop",a),_n(e),setTimeout(function(){return i.input.focus()},20)}function Ro(e,t,n){if("char"==n)return new Nl(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new Nl(I(t.line,0),V(e.doc,I(t.line+1,0)));var r=n(e,t);return new Nl(r.from,r.to)}function Fo(e,t,n,r){function i(t){if(0!=R(v,t))if(v=t,"rectangle"==r.unit){for(var i=[],o=e.options.tabSize,a=f(M(s,n.line).text,n.ch,o),l=f(M(s,t.line).text,t.ch,o),u=Math.min(a,l),g=Math.max(a,l),m=Math.min(n.line,t.line),y=Math.min(e.lastLine(),Math.max(n.line,t.line));m<=y;m++){var b=M(s,m).text,w=p(b,u,o);u==g?i.push(new Nl(I(m,w),I(m,w))):b.length>w&&i.push(new Nl(I(m,w),I(m,p(b,g,o))))}i.length||i.push(new Nl(n,n)),wi(s,Wr(h.ranges.slice(0,d).concat(i),d),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var x,C=c,k=Ro(e,t,r.unit),S=C.anchor;R(k.anchor,S)>0?(x=k.head,S=z(C.from(),k.anchor)):(x=k.anchor,S=W(C.to(),k.head));var T=h.ranges.slice(0);T[d]=Ho(e,new Nl(V(s,S),x)),wi(s,Wr(T,d),Ka)}}function o(t){var n=++b,l=Tn(e,t,!0,"rectangle"==r.unit);if(l)if(0!=R(l,v)){e.curOp.focus=a(),i(l);var c=Wn(u,s);(l.line>=c.to||l.liney.bottom?20:0;f&&setTimeout(hr(e,function(){b==n&&(u.scroller.scrollTop+=f,o(t))}),50)}}function l(t){e.state.selectingText=!1,b=1/0,Pe(t),u.input.focus(),Te(document,"mousemove",w),Te(document,"mouseup",x),s.history.lastSelOrigin=null}var u=e.display,s=e.doc;Pe(t);var c,d,h=s.sel,g=h.ranges;if(r.addNew&&!r.extend?(d=s.sel.contains(n),c=d>-1?g[d]:new Nl(n,n)):(c=s.sel.primary(),d=s.sel.primIndex),"rectangle"==r.unit)r.addNew||(c=new Nl(n,n)),n=Tn(e,t,!0,!0),d=-1;else{var m=Ro(e,n,r.unit);c=r.extend?pi(c,m.anchor,m.head,r.extend):m}r.addNew?-1==d?(d=g.length,wi(s,Wr(g.concat([c]),d),{scroll:!1,origin:"*mouse"})):g.length>1&&g[d].empty()&&"char"==r.unit&&!r.extend?(wi(s,Wr(g.slice(0,d).concat(g.slice(d+1)),0),{scroll:!1,origin:"*mouse"}),h=s.sel):mi(s,d,c,Ka):(d=0,wi(s,new Ll([c],0),Ka),h=s.sel);var v=n,y=u.wrapper.getBoundingClientRect(),b=0,w=hr(e,function(e){Re(e)?o(e):l(e)}),x=hr(e,l);e.state.selectingText=x,tl(document,"mousemove",w),tl(document,"mouseup",x)}function Ho(e,t){var n=t.anchor,r=t.head,i=M(e.doc,n.line);if(0==R(n,r)&&n.sticky==r.sticky)return t;var o=ke(i);if(!o)return t;var a=Ce(o,n.ch,n.sticky),l=o[a];if(l.from!=n.ch&&l.to!=n.ch)return t;var u=a+(l.from==n.ch==(1!=l.level)?0:1);if(0==u||u==o.length)return t;var s;if(r.line!=n.line)s=(r.line-n.line)*("ltr"==e.doc.direction?1:-1)>0;else{var c=Ce(o,r.ch,r.sticky),f=c-a||(r.ch-n.ch)*(1==l.level?-1:1);s=c==u-1||c==u?f<0:f>0}var d=o[u+(s?-1:0)],p=s==(1==d.level),h=p?d.from:d.to,g=p?"after":"before";return n.ch==h&&n.sticky==g?t:new Nl(new I(n.line,h,g),r)}function Wo(e,t,n,r){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(t){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&Pe(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(o>l.bottom||!Ne(e,n))return De(t);o-=l.top-a.viewOffset;for(var u=0;u=i)return Ee(e,n,e,A(e.doc,o),e.options.gutters[u],t),De(t)}}function zo(e,t){return Wo(e,t,"gutterClick",!0)}function Uo(e,t){It(e.display,t)||Vo(e,t)||Me(e,t,"contextmenu")||e.display.input.onContextMenu(t)}function Vo(e,t){return!!Ne(e,"gutterContextMenu")&&Wo(e,t,"gutterContextMenu",!1)}function Bo(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),tn(e)}function jo(e){_r(e),vr(e),zn(e)}function Ko(e,t,n){if(!t!=!(n&&n!=Yl)){var r=e.display.dragFunctions,i=t?tl:Te;i(e.display.scroller,"dragstart",r.start),i(e.display.scroller,"dragenter",r.enter),i(e.display.scroller,"dragover",r.over),i(e.display.scroller,"dragleave",r.leave),i(e.display.scroller,"drop",r.drop)}}function Go(e){e.options.lineWrapping?(l(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(Fa(e.display.wrapper,"CodeMirror-wrap"),we(e)),Sn(e),vr(e),tn(e),setTimeout(function(){return nr(e)},100)}function qo(e,t){var n=this;if(!(this instanceof qo))return new qo(e,t);this.options=t=t?c(t):{},c(Xl,t,!1),Ir(t);var r=t.value;"string"==typeof r&&(r=new Il(r,t.mode,null,t.lineSeparator,t.direction)),this.doc=r;var i=new qo.inputStyles[t.inputStyle](this),o=this.display=new E(e,r,i);o.wrapper.CodeMirror=this,_r(this),Bo(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),ir(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new Wa,keySeq:null,specialChars:null},t.autofocus&&!Na&&o.input.focus(),ya&&ba<11&&setTimeout(function(){return n.display.input.reset(!0)},20),$o(this),to(),or(this),this.curOp.forceUpdate=!0,Qr(this,r),t.autofocus&&!Na||this.hasFocus()?setTimeout(s(In,this),20):Rn(this);for(var a in Ql)Ql.hasOwnProperty(a)&&Ql[a](n,t[a],Yl);Un(this),t.finishInit&&t.finishInit(this);for(var l=0;l400}var i=e.display;tl(i.scroller,"mousedown",hr(e,Po)),ya&&ba<11?tl(i.scroller,"dblclick",hr(e,function(t){if(!Me(e,t)){var n=Tn(e,t);if(n&&!zo(e,t)&&!It(e.display,t)){Pe(t);var r=e.findWordAt(n);hi(e.doc,r.anchor,r.head)}}})):tl(i.scroller,"dblclick",function(t){return Me(e,t)||Pe(t)}),Ra||tl(i.scroller,"contextmenu",function(t){return Uo(e,t)});var o,a={end:0};tl(i.scroller,"touchstart",function(t){if(!Me(e,t)&&!n(t)&&!zo(e,t)){i.input.ensurePolled(),clearTimeout(o);var r=+new Date;i.activeTouch={start:r,moved:!1,prev:r-a.end<=300?a:null},1==t.touches.length&&(i.activeTouch.left=t.touches[0].pageX,i.activeTouch.top=t.touches[0].pageY)}}),tl(i.scroller,"touchmove",function(){i.activeTouch&&(i.activeTouch.moved=!0)}),tl(i.scroller,"touchend",function(n){var o=i.activeTouch;if(o&&!It(i,n)&&null!=o.left&&!o.moved&&new Date-o.start<300){var a,l=e.coordsChar(i.activeTouch,"page");a=!o.prev||r(o,o.prev)?new Nl(l,l):!o.prev.prev||r(o,o.prev.prev)?e.findWordAt(l):new Nl(I(l.line,0),V(e.doc,I(l.line+1,0))),e.setSelection(a.anchor,a.head),e.focus(),Pe(n)}t()}),tl(i.scroller,"touchcancel",t),tl(i.scroller,"scroll",function(){i.scroller.clientHeight&&(Zn(e,i.scroller.scrollTop),er(e,i.scroller.scrollLeft,!0),Ee(e,"scroll",e))}),tl(i.scroller,"mousewheel",function(t){return Hr(e,t)}),tl(i.scroller,"DOMMouseScroll",function(t){return Hr(e,t)}),tl(i.wrapper,"scroll",function(){return i.wrapper.scrollTop=i.wrapper.scrollLeft=0}),i.dragFunctions={enter:function(t){Me(e,t)||_e(t)},over:function(t){Me(e,t)||(Zi(e,t),_e(t))},start:function(t){return Qi(e,t)},drop:hr(e,Xi),leave:function(t){Me(e,t)||Ji(e)}};var l=i.input.getField();tl(l,"keyup",function(t){return Lo.call(e,t)}),tl(l,"keydown",hr(e,Eo)),tl(l,"keypress",hr(e,No)),tl(l,"focus",function(t){return In(e,t)}),tl(l,"blur",function(t){return Rn(e,t)})}function Yo(e,t,n,r){var i,o=e.doc;null==n&&(n="add"),"smart"==n&&(o.mode.indent?i=Xe(e,t).state:n="prev");var a=e.options.tabSize,l=M(o,t),u=f(l.text,null,a);l.stateAfter&&(l.stateAfter=null);var s,c=l.text.match(/^\s*/)[0];if(r||/\S/.test(l.text)){if("smart"==n&&((s=o.mode.indent(i,l.text.slice(c.length),l.text))==Ba||s>150)){if(!r)return;n="prev"}}else s=0,n="not";"prev"==n?s=t>o.first?f(M(o,t-1).text,null,a):0:"add"==n?s=u+e.options.indentUnit:"subtract"==n?s=u-e.options.indentUnit:"number"==typeof n&&(s=u+n),s=Math.max(0,s);var d="",p=0;if(e.options.indentWithTabs)for(var g=Math.floor(s/a);g;--g)p+=a,d+="\t";if(p1)if(Jl&&Jl.text.join("\n")==t){if(r.ranges.length%Jl.text.length==0){u=[];for(var s=0;s=0;f--){var d=r.ranges[f],p=d.from(),h=d.to();d.empty()&&(n&&n>0?p=I(p.line,p.ch-n):e.state.overwrite&&!a?h=I(h.line,Math.min(M(o,h.line).text.length,h.ch+g(l).length)):Jl&&Jl.lineWise&&Jl.text.join("\n")==t&&(p=h=I(p.line,0))),c=e.curOp.updateInput;var v={from:p,to:h,text:u?u[f%u.length]:l,origin:i||(a?"paste":e.state.cutIncoming?"cut":"+input")};Oi(e.doc,v),wt(e,"inputRead",e,v)}t&&!a&&Jo(e,t),qn(e),e.curOp.updateInput=c,e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=!1}function Zo(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");if(n)return e.preventDefault(),t.isReadOnly()||t.options.disableInput||pr(t,function(){return Qo(t,n,0,null,"paste")}),!0}function Jo(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,r=n.ranges.length-1;r>=0;r--){var i=n.ranges[r];if(!(i.head.ch>100||r&&n.ranges[r-1].head.line==i.head.line)){var o=e.getModeAt(i.head),a=!1;if(o.electricChars){for(var l=0;l-1){a=Yo(e,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(M(e.doc,i.head.line).text.slice(0,i.head.ch))&&(a=Yo(e,i.head.line,"smart"));a&&wt(e,"electricInput",e,i.head.line)}}}function ea(e){for(var t=[],n=[],r=0;r=e.first+e.size)&&(t=new I(r,t.ch,t.sticky),s=M(e,r))}function a(r){var a;if(null==(a=i?mo(e.cm,s,t,n):ho(s,t,n))){if(r||!o())return!1;t=go(i,e.cm,s,t.line,n)}else t=a;return!0}var l=t,u=n,s=M(e,t.line);if("char"==r)a();else if("column"==r)a(!0);else if("word"==r||"group"==r)for(var c=null,f="group"==r,d=e.cm&&e.cm.getHelper(t,"wordChars"),p=!0;!(n<0)||a(!p);p=!1){var h=s.text.charAt(t.ch)||"\n",g=x(h,d)?"w":f&&"\n"==h?"n":!f||/\s/.test(h)?null:"p";if(!f||p||g||(g="s"),c&&c!=g){n<0&&(n=1,a(),t.sticky="after");break}if(g&&(c=g),n>0&&!a(!p))break}var m=Ei(e,t,l,u,!0);return F(l,m)&&(m.hitSide=!0),m}function ia(e,t,n,r){var i,o=e.doc,a=t.left;if("page"==r){var l=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),u=Math.max(l-.5*bn(e.display),3);i=(n>0?t.bottom:t.top)+n*u}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(var s;s=dn(e,a,i),s.outside;){if(n<0?i<=0:i>=o.height){s.hitSide=!0;break}i+=5*n}return s}function oa(e,t){var n=Gt(e,t.line);if(!n||n.hidden)return null;var r=M(e.doc,t.line),i=Bt(n,r,t.line),o=ke(r,e.doc.direction),a="left";o&&(a=Ce(o,t.ch)%2?"right":"left");var l=Yt(i.map,t.ch,a);return l.offset="right"==l.collapse?l.end:l.start,l}function aa(e){for(var t=e;t;t=t.parentNode)if(/CodeMirror-gutter-wrapper/.test(t.className))return!0;return!1}function la(e,t){return t&&(e.bad=!0),e}function ua(e,t,n,r,i){function o(e){return function(t){return t.id==e}}function a(){c&&(s+=f,c=!1)}function l(e){e&&(a(),s+=e)}function u(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(null!=n)return void l(n||t.textContent.replace(/\u200b/g,""));var s,d=t.getAttribute("cm-marker");if(d){var p=e.findMarks(I(r,0),I(i+1,0),o(+d));return void(p.length&&(s=p[0].find(0))&&l(L(e.doc,s.from,s.to).join(f)))}if("false"==t.getAttribute("contenteditable"))return;var h=/^(pre|div|p)$/i.test(t.nodeName);h&&a();for(var g=0;g=15&&(ka=!1,wa=!0);var _a,Ia=Oa&&(xa||ka&&(null==Da||Da<12.11)),Ra=ha||ya&&ba>=9,Fa=function(t,n){var r=t.className,i=e(n).exec(r);if(i){var o=r.slice(i.index+i[0].length);t.className=r.slice(0,i.index)+(o?i[1]+o:"")}};_a=document.createRange?function(e,t,n,r){var i=document.createRange();return i.setEnd(r||e,n),i.setStart(e,t),i}:function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r};var Ha=function(e){e.select()};Ma?Ha=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:ya&&(Ha=function(e){try{e.select()}catch(e){}});var Wa=function(){this.id=null};Wa.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var za,Ua,Va=30,Ba={toString:function(){return"CodeMirror.Pass"}},ja={scroll:!1},Ka={origin:"*mouse"},Ga={origin:"+move"},qa=[""],$a=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Ya=/[\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]/,Xa=!1,Qa=!1,Za=null,Ja=function(){function e(e){return e<=247?n.charAt(e):1424<=e&&e<=1524?"R":1536<=e&&e<=1785?r.charAt(e-1536):1774<=e&&e<=2220?"r":8192<=e&&e<=8203?"w":8204==e?"b":"L"}function t(e,t,n){this.level=e,this.from=t,this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,a=/[LRr]/,l=/[Lb1n]/,u=/[1n]/;return function(n,r){var s="ltr"==r?"L":"R";if(0==n.length||"ltr"==r&&!i.test(n))return!1;for(var c=n.length,f=[],d=0;d=this.string.length},cl.prototype.sol=function(){return this.pos==this.lineStart},cl.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},cl.prototype.next=function(){if(this.post},cl.prototype.eatSpace=function(){for(var e=this,t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++e.pos;return this.pos>t},cl.prototype.skipToEnd=function(){this.pos=this.string.length},cl.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},cl.prototype.backUp=function(e){this.pos-=e},cl.prototype.column=function(){return this.lastColumnPos0?null:(r&&!1!==t&&(this.pos+=r[0].length),r)}var i=function(e){return n?e.toLowerCase():e};if(i(this.string.substr(this.pos,e.length))==i(e))return!1!==t&&(this.pos+=e.length),!0},cl.prototype.current=function(){return this.string.slice(this.start,this.pos)},cl.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},cl.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},cl.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};var fl=function(e,t){this.state=e,this.lookAhead=t},dl=function(e,t,n,r){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=r||0,this.baseTokens=null,this.baseTokenPos=1};dl.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},dl.prototype.baseToken=function(e){var t=this;if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)t.baseTokenPos+=2;var n=this.baseTokens[this.baseTokenPos+1];return{type:n&&n.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},dl.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},dl.fromSaved=function(e,t,n){return t instanceof fl?new dl(e,Ke(e.mode,t.state),n,t.lookAhead):new dl(e,Ke(e.mode,t),n)},dl.prototype.save=function(e){var t=!1!==e?Ke(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new fl(t,this.maxLookAhead):t};var pl=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n},hl=function(e,t,n){this.text=e,re(this,t),this.height=n?n(this):1};hl.prototype.lineNo=function(){return P(this)},Oe(hl);var gl,ml={},vl={},yl=null,bl=null,wl={left:0,right:0,top:0,bottom:0},xl=function(e,t,n){this.cm=n;var i=this.vert=r("div",[r("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),o=this.horiz=r("div",[r("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(i),e(o),tl(i,"scroll",function(){i.clientHeight&&t(i.scrollTop,"vertical")}),tl(o,"scroll",function(){o.clientWidth&&t(o.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,ya&&ba<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};xl.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=t?r+"px":"0";var i=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=n?r+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(n?r:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==r&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?r:0,bottom:t?r:0}},xl.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},xl.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},xl.prototype.zeroWidthHack=function(){var e=Oa&&!Ta?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new Wa,this.disableVert=new Wa},xl.prototype.enableZeroWidthBar=function(e,t,n){function r(){var i=e.getBoundingClientRect();("vert"==n?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=e?e.style.pointerEvents="none":t.set(1e3,r)}e.style.pointerEvents="auto",t.set(1e3,r)},xl.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var Cl=function(){};Cl.prototype.update=function(){return{bottom:0,right:0}},Cl.prototype.setScrollLeft=function(){},Cl.prototype.setScrollTop=function(){},Cl.prototype.clear=function(){};var kl={native:xl,null:Cl},Sl=0,Tl=function(e,t,n){var r=e.display;this.viewport=t,this.visible=Wn(r,e.doc,t),this.editorIsHidden=!r.wrapper.offsetWidth,this.wrapperHeight=r.wrapper.clientHeight,this.wrapperWidth=r.wrapper.clientWidth,this.oldDisplayWidth=zt(e),this.force=n,this.dims=xn(e),this.events=[]};Tl.prototype.signal=function(e,t){Ne(e,t)&&this.events.push(arguments)},Tl.prototype.finish=function(){for(var e=this,t=0;t=0&&R(e,i.to())<=0)return r}return-1};var Nl=function(e,t){this.anchor=e,this.head=t};Nl.prototype.from=function(){return z(this.anchor,this.head)},Nl.prototype.to=function(){return W(this.anchor,this.head)},Nl.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},Ui.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n=this,r=e,i=e+t;r1||!(this.children[0]instanceof Ui))){var u=[];this.collapse(u),this.children=[new Ui(u)],this.children[0].parent=this}},collapse:function(e){for(var t=this,n=0;n50){for(var l=o.lines.length%25+25,u=l;u10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=this,i=0;it.display.maxLineLength&&(t.display.maxLine=c,t.display.maxLineLength=f,t.display.maxLineChanged=!0)}null!=i&&t&&this.collapsed&&vr(t,i,o+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&ki(t.doc)),t&&wt(t,"markerCleared",t,this,i,o),n&&ar(t),this.parent&&this.parent.clear()}},Al.prototype.find=function(e,t){var n=this;null==e&&"bookmark"==this.type&&(e=1);for(var r,i,o=0;o=0;s--)Oi(r,i[s]);u?bi(this,u):this.cm&&qn(this.cm)}),undo:mr(function(){Ai(this,"undo")}),redo:mr(function(){Ai(this,"redo")}),undoSelection:mr(function(){Ai(this,"undo",!0)}),redoSelection:mr(function(){Ai(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=V(this,e),t=V(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(o){var a=o.markedSpans;if(a)for(var l=0;l=u.to||null==u.from&&i!=e.line||null!=u.from&&i==t.line&&u.from>=t.ch||n&&!n(u.marker)||r.push(u.marker.parent||u.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;re)return t=e,!0;e-=o,++n}),V(this,I(n,t))},indexFromPos:function(e){e=V(this,e);var t=e.ch;if(e.linet&&(t=e.from),null!=e.to&&e.to0)i=new I(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),I(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var a=M(e.doc,i.line-1).text;a&&(i=new I(i.line,1),e.replaceRange(o.charAt(0)+e.doc.lineSeparator()+a.charAt(a.length-1),I(i.line-1,a.length-1),i,"+transpose"))}n.push(new Nl(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){return pr(e,function(){for(var t=e.listSelections(),n=t.length-1;n>=0;n--)e.replaceRange(e.doc.lineSeparator(),t[n].anchor,t[n].head,"+input");t=e.listSelections();for(var r=0;re&&0==R(t,this.pos)&&n==this.button};var ql,$l,Yl={toString:function(){return"CodeMirror.Init"}},Xl={},Ql={};qo.defaults=Xl,qo.optionHandlers=Ql;var Zl=[];qo.defineInitHook=function(e){return Zl.push(e)};var Jl=null,eu=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new Wa,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};eu.prototype.init=function(e){function t(e){if(!Me(i,e)){if(i.somethingSelected())Xo({lineWise:!1,text:i.getSelections()}),"cut"==e.type&&i.replaceSelection("",null,"cut");else{if(!i.options.lineWiseCopyCut)return;var t=ea(i);Xo({lineWise:!0,text:t.text}),"cut"==e.type&&i.operation(function(){i.setSelections(t.ranges,0,ja),i.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var n=Jl.text.join("\n");if(e.clipboardData.setData("Text",n),e.clipboardData.getData("Text")==n)return void e.preventDefault()}var a=na(),l=a.firstChild;i.display.lineSpace.insertBefore(a,i.display.lineSpace.firstChild),l.value=Jl.text.join("\n");var u=document.activeElement;Ha(l),setTimeout(function(){i.display.lineSpace.removeChild(a),u.focus(),u==o&&r.showPrimarySelection()},50)}}var n=this,r=this,i=r.cm,o=r.div=e.lineDiv;ta(o,i.options.spellcheck),tl(o,"paste",function(e){Me(i,e)||Zo(e,i)||ba<=11&&setTimeout(hr(i,function(){return n.updateFromDOM()}),20)}),tl(o,"compositionstart",function(e){n.composing={data:e.data,done:!1}}),tl(o,"compositionupdate",function(e){n.composing||(n.composing={data:e.data,done:!1})}),tl(o,"compositionend",function(e){n.composing&&(e.data!=n.composing.data&&n.readFromDOMSoon(),n.composing.done=!0)}),tl(o,"touchstart",function(){return r.forceCompositionEnd()}),tl(o,"input",function(){n.composing||n.readFromDOMSoon()}),tl(o,"copy",t),tl(o,"cut",t)},eu.prototype.prepareSelection=function(){var e=Ln(this.cm,!1);return e.focus=this.cm.state.focused,e},eu.prototype.showSelection=function(e,t){e&&this.cm.display.view.length&&((e.focus||t)&&this.showPrimarySelection(),this.showMultipleSelections(e))},eu.prototype.showPrimarySelection=function(){var e=window.getSelection(),t=this.cm,n=t.doc.sel.primary(),r=n.from(),i=n.to();if(t.display.viewTo==t.display.viewFrom||r.line>=t.display.viewTo||i.line=t.display.viewFrom&&oa(t,r)||{node:l[0].measure.map[2],offset:0},s=i.linee.firstLine()&&(r=I(r.line-1,M(e.doc,r.line-1).length)),i.ch==M(e.doc,i.line).text.length&&i.linet.viewTo-1)return!1;var o,a,l;r.line==t.viewFrom||0==(o=En(e,r.line))?(a=P(t.view[0].line),l=t.view[0].node):(a=P(t.view[o].line),l=t.view[o-1].node.nextSibling);var u,s,c=En(e,i.line);if(c==t.view.length-1?(u=t.viewTo-1,s=t.lineDiv.lastChild):(u=P(t.view[c+1].line)-1,s=t.view[c+1].node.previousSibling),!l)return!1;for(var f=e.doc.splitLines(ua(e,l,s,a,u)),d=L(e.doc,I(a,0),I(u,M(e.doc,u).text.length));f.length>1&&d.length>1;)if(g(f)==g(d))f.pop(),d.pop(),u--;else{if(f[0]!=d[0])break;f.shift(),d.shift(),a++}for(var p=0,h=0,m=f[0],v=d[0],y=Math.min(m.length,v.length);pr.ch&&b.charCodeAt(b.length-h-1)==w.charCodeAt(w.length-h-1);)p--,h++;f[f.length-1]=b.slice(0,b.length-h).replace(/^\u200b+/,""),f[0]=f[0].slice(p).replace(/\u200b+$/,"");var C=I(a,p),k=I(u,d.length?g(d).length-h:0);return f.length>1||f[0]||R(C,k)?(Ri(e.doc,f,C,k,"+input"),!0):void 0},eu.prototype.ensurePolled=function(){this.forceCompositionEnd()},eu.prototype.reset=function(){this.forceCompositionEnd()},eu.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},eu.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()},80))},eu.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||pr(this.cm,function(){return vr(e.cm)})},eu.prototype.setUneditable=function(e){e.contentEditable="false"},eu.prototype.onKeyPress=function(e){0!=e.charCode&&(e.preventDefault(),this.cm.isReadOnly()||hr(this.cm,Qo)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},eu.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},eu.prototype.onContextMenu=function(){},eu.prototype.resetPosition=function(){},eu.prototype.needsContentAttribute=!0;var tu=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new Wa,this.hasSelection=!1,this.composing=null};tu.prototype.init=function(e){function t(e){if(!Me(i,e)){if(i.somethingSelected())Xo({lineWise:!1,text:i.getSelections()});else{if(!i.options.lineWiseCopyCut)return;var t=ea(i);Xo({lineWise:!0,text:t.text}),"cut"==e.type?i.setSelections(t.ranges,null,ja):(r.prevInput="",a.value=t.text.join("\n"),Ha(a))}"cut"==e.type&&(i.state.cutIncoming=!0)}}var n=this,r=this,i=this.cm,o=this.wrapper=na(),a=this.textarea=o.firstChild;e.wrapper.insertBefore(o,e.wrapper.firstChild),Ma&&(a.style.width="0px"),tl(a,"input",function(){ya&&ba>=9&&n.hasSelection&&(n.hasSelection=null),r.poll()}),tl(a,"paste",function(e){Me(i,e)||Zo(e,i)||(i.state.pasteIncoming=!0,r.fastPoll())}),tl(a,"cut",t),tl(a,"copy",t),tl(e.scroller,"paste",function(t){It(e,t)||Me(i,t)||(i.state.pasteIncoming=!0,r.focus())}),tl(e.lineSpace,"selectstart",function(t){It(e,t)||Pe(t)}),tl(a,"compositionstart",function(){var e=i.getCursor("from");r.composing&&r.composing.range.clear(),r.composing={start:e,range:i.markText(e,i.getCursor("to"),{className:"CodeMirror-composing"})}}),tl(a,"compositionend",function(){r.composing&&(r.poll(),r.composing.range.clear(),r.composing=null)})},tu.prototype.prepareSelection=function(){var e=this.cm,t=e.display,n=e.doc,r=Ln(e);if(e.options.moveInputWithCursor){var i=sn(e,n.sel.primary().head,"div"),o=t.wrapper.getBoundingClientRect(),a=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,i.top+a.top-o.top)),r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,i.left+a.left-o.left))}return r},tu.prototype.showSelection=function(e){var t=this.cm,r=t.display;n(r.cursorDiv,e.cursors),n(r.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},tu.prototype.reset=function(e){if(!this.contextMenuPending&&!this.composing){var t=this.cm;if(t.somethingSelected()){this.prevInput="";var n=t.getSelection();this.textarea.value=n,t.state.focused&&Ha(this.textarea),ya&&ba>=9&&(this.hasSelection=n)}else e||(this.prevInput=this.textarea.value="",ya&&ba>=9&&(this.hasSelection=null))}},tu.prototype.getField=function(){return this.textarea},tu.prototype.supportsTouch=function(){return!1},tu.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!Na||a()!=this.textarea))try{this.textarea.focus()}catch(e){}},tu.prototype.blur=function(){this.textarea.blur()},tu.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},tu.prototype.receivedFocus=function(){this.slowPoll()},tu.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){e.poll(),e.cm.state.focused&&e.slowPoll()})},tu.prototype.fastPoll=function(){function e(){n.poll()||t?(n.pollingFast=!1,n.slowPoll()):(t=!0,n.polling.set(60,e))}var t=!1,n=this;n.pollingFast=!0,n.polling.set(20,e)},tu.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,r=this.prevInput;if(this.contextMenuPending||!t.state.focused||il(n)&&!r&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var i=n.value;if(i==r&&!t.somethingSelected())return!1;if(ya&&ba>=9&&this.hasSelection===i||Oa&&/[\uf700-\uf7ff]/.test(i))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||r||(r="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var a=0,l=Math.min(r.length,i.length);a1e3||i.indexOf("\n")>-1?n.value=e.prevInput="":e.prevInput=i,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},tu.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},tu.prototype.onKeyPress=function(){ya&&ba>=9&&(this.hasSelection=null),this.fastPoll()},tu.prototype.onContextMenu=function(e){function t(){if(null!=a.selectionStart){var e=i.somethingSelected(),t="​"+(e?a.value:"");a.value="⇚",a.value=t,r.prevInput=e?"":"​",a.selectionStart=1,a.selectionEnd=t.length,o.selForContextMenu=i.doc.sel}}function n(){if(r.contextMenuPending=!1,r.wrapper.style.cssText=c,a.style.cssText=s,ya&&ba<9&&o.scrollbars.setScrollTop(o.scroller.scrollTop=u),null!=a.selectionStart){(!ya||ya&&ba<9)&&t();var e=0,n=function(){o.selForContextMenu==i.doc.sel&&0==a.selectionStart&&a.selectionEnd>0&&"​"==r.prevInput?hr(i,Li)(i):e++<10?o.detectingSelectAll=setTimeout(n,500):(o.selForContextMenu=null,o.input.reset())};o.detectingSelectAll=setTimeout(n,200)}}var r=this,i=r.cm,o=i.display,a=r.textarea,l=Tn(i,e),u=o.scroller.scrollTop;if(l&&!ka){i.options.resetSelectionOnContextMenu&&-1==i.doc.sel.contains(l)&&hr(i,wi)(i.doc,zr(l),ja);var s=a.style.cssText,c=r.wrapper.style.cssText;r.wrapper.style.cssText="position: absolute";var f=r.wrapper.getBoundingClientRect();a.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-f.top-5)+"px; left: "+(e.clientX-f.left-5)+"px;\n z-index: 1000; background: "+(ya?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var d;if(wa&&(d=window.scrollY),o.input.focus(),wa&&window.scrollTo(null,d),o.input.reset(),i.somethingSelected()||(a.value=r.prevInput=" "),r.contextMenuPending=!0,o.selForContextMenu=i.doc.sel,clearTimeout(o.detectingSelectAll),ya&&ba>=9&&t(),Ra){_e(e);var p=function(){Te(window,"mouseup",p),setTimeout(n,20)};tl(window,"mouseup",p)}else setTimeout(n,50)}},tu.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e},tu.prototype.setUneditable=function(){},tu.prototype.needsContentAttribute=!1,function(e){function t(t,r,i,o){e.defaults[t]=r,i&&(n[t]=o?function(e,t,n){n!=Yl&&i(e,t,n)}:i)}var n=e.optionHandlers;e.defineOption=t,e.Init=Yl,t("value","",function(e,t){return e.setValue(t)},!0),t("mode",null,function(e,t){e.doc.modeOption=t,Gr(e)},!0),t("indentUnit",2,Gr,!0),t("indentWithTabs",!1),t("smartIndent",!0),t("tabSize",4,function(e){qr(e),tn(e),vr(e)},!0),t("lineSeparator",null,function(e,t){if(e.doc.lineSep=t,t){var n=[],r=e.doc.first;e.doc.iter(function(e){for(var i=0;;){var o=e.text.indexOf(t,i);if(-1==o)break;i=o+t.length,n.push(I(r,o))}r++});for(var i=n.length-1;i>=0;i--)Ri(e.doc,t,n[i],I(n[i].line,n[i].ch+t.length))}}),t("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=Yl&&e.refresh()}),t("specialCharPlaceholder",st,function(e){return e.refresh()},!0),t("electricChars",!0),t("inputStyle",Na?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),t("spellcheck",!1,function(e,t){return e.getInputField().spellcheck=t},!0),t("rtlMoveVisually",!Aa),t("wholeLineUpdateBefore",!0),t("theme","default",function(e){Bo(e),jo(e)},!0),t("keyMap","default",function(e,t,n){var r=co(t),i=n!=Yl&&co(n);i&&i.detach&&i.detach(e,r),r.attach&&r.attach(e,i||null)}),t("extraKeys",null),t("configureMouse",null),t("lineWrapping",!1,Go,!0),t("gutters",[],function(e){Ir(e.options),jo(e)},!0),t("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?Cn(e.display)+"px":"0",e.refresh()},!0),t("coverGutterNextToScrollbar",!1,function(e){return nr(e)},!0),t("scrollbarStyle","native",function(e){ir(e),nr(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0),t("lineNumbers",!1,function(e){Ir(e.options),jo(e)},!0),t("firstLineNumber",1,jo,!0),t("lineNumberFormatter",function(e){return e},jo,!0),t("showCursorWhenSelecting",!1,Mn,!0),t("resetSelectionOnContextMenu",!0),t("lineWiseCopyCut",!0),t("pasteLinesPerSelection",!0),t("readOnly",!1,function(e,t){"nocursor"==t&&(Rn(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)}),t("disableInput",!1,function(e,t){t||e.display.input.reset()},!0),t("dragDrop",!0,Ko),t("allowDropFileTypes",null),t("cursorBlinkRate",530),t("cursorScrollMargin",0),t("cursorHeight",1,Mn,!0),t("singleCursorHeightPerLine",!0,Mn,!0),t("workTime",100),t("workDelay",100),t("flattenSpans",!0,qr,!0),t("addModeClass",!1,qr,!0),t("pollInterval",100),t("undoDepth",200,function(e,t){return e.doc.history.undoDepth=t}),t("historyEventDelay",1250),t("viewportMargin",10,function(e){return e.refresh()},!0),t("maxHighlightLength",1e4,qr,!0),t("moveInputWithCursor",!0,function(e,t){t||e.display.input.resetPosition()}),t("tabindex",null,function(e,t){return e.display.input.getField().tabIndex=t||""}),t("autofocus",null),t("direction","ltr",function(e,t){return e.doc.setDirection(t)},!0)}(qo),function(e){var t=e.optionHandlers,n=e.helpers={};e.prototype={constructor:e,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,n){var r=this.options,i=r[e];r[e]==n&&"mode"!=e||(r[e]=n,t.hasOwnProperty(e)&&hr(this,t[e])(this,n,i),Ee(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](co(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;nr&&(Yo(t,o.head.line,e,!0),r=o.head.line,i==t.doc.sel.primIndex&&qn(t));else{var a=o.from(),l=o.to(),u=Math.max(r,a.line);r=Math.min(t.lastLine(),l.line-(l.ch?0:1))+1;for(var s=u;s0&&mi(t.doc,i,new Nl(a,c[i].to()),ja)}}}),getTokenAt:function(e,t){return et(this,e,t)},getLineTokens:function(e,t){return et(this,I(e),t,!0)},getTokenTypeAt:function(e){e=V(this.doc,e);var t,n=Ye(this,M(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]o&&(e=o,i=!0),r=M(this.doc,e)}else r=e;return an(this,r,{top:0,left:0},t||"page",n||i).top+(i?this.doc.height-ye(r):0)},defaultTextHeight:function(){return bn(this.display)},defaultCharWidth:function(){return wn(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o=this.display;e=sn(this,V(this.doc,e));var a=e.bottom,l=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),o.sizer.appendChild(t),"over"==r)a=e.top;else if("above"==r||"near"==r){var u=Math.max(o.wrapper.clientHeight,this.doc.height),s=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>u)&&e.top>t.offsetHeight?a=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=u&&(a=e.bottom),l+t.offsetWidth>s&&(l=s-t.offsetWidth)}t.style.top=a+"px",t.style.left=t.style.right="","right"==i?(l=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?l=0:"middle"==i&&(l=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=l+"px"),n&&jn(this,{left:l,top:a,right:l+t.offsetWidth,bottom:a+t.offsetHeight})},triggerOnKeyDown:gr(Eo),triggerOnKeyPress:gr(No),triggerOnKeyUp:Lo,triggerOnMouseDown:gr(Po),execCommand:function(e){if(Bl.hasOwnProperty(e))return Bl[e].call(null,this)},triggerElectric:gr(function(e){Jo(this,e)}),findPosH:function(e,t,n,r){var i=this,o=1;t<0&&(o=-1,t=-t);for(var a=V(this.doc,e),l=0;l0&&l(n.charAt(r-1));)--r;for(;i.5)&&Sn(this),Ee(this,"refresh",this)}),swapDoc:gr(function(e){var t=this.doc;return t.cm=null,Qr(this,e),tn(this),this.display.input.reset(),$n(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,wt(this,"swapDoc",this,t),t}),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}},Oe(e),e.registerHelper=function(t,r,i){n.hasOwnProperty(t)||(n[t]=e[t]={_global:[]}),n[t][r]=i},e.registerGlobalHelper=function(t,r,i,o){e.registerHelper(t,r,o),n[t]._global.push({pred:i,val:o})}}(qo);var nu="iter insert remove copy getEditor constructor".split(" ");for(var ru in Il.prototype)Il.prototype.hasOwnProperty(ru)&&d(nu,ru)<0&&(qo.prototype[ru]=function(e){return function(){return e.apply(this.doc,arguments)}}(Il.prototype[ru]));return Oe(Il),qo.inputStyles={textarea:tu,contenteditable:eu},qo.defineMode=function(e){qo.defaults.mode||"null"==e||(qo.defaults.mode=e),ze.apply(this,arguments)},qo.defineMIME=Ue,qo.defineMode("null",function(){return{token:function(e){return e.skipToEnd()}}}),qo.defineMIME("text/plain","null"),qo.defineExtension=function(e,t){qo.prototype[e]=t},qo.defineDocExtension=function(e,t){Il.prototype[e]=t},qo.fromTextArea=fa,function(e){e.off=Te,e.on=tl,e.wheelEventPixels=Fr,e.Doc=Il,e.splitLines=rl,e.countColumn=f,e.findColumn=p,e.isWordChar=w,e.Pass=Ba,e.signal=Ee,e.Line=hl,e.changeEnd=Ur,e.scrollbarModel=kl,e.Pos=I,e.cmpPos=R,e.modes=ll,e.mimeModes=ul,e.resolveMode=Ve,e.getMode=Be,e.modeExtensions=sl,e.extendMode=je,e.copyState=Ke,e.startState=qe,e.innerMode=Ge,e.commands=Bl,e.keyMap=Vl,e.keyName=so,e.isModifierKey=lo,e.lookupKey=ao,e.normalizeKeyMap=oo,e.StringStream=cl,e.SharedTextMarker=Dl,e.TextMarker=Al,e.LineWidget=Ol,e.e_preventDefault=Pe,e.e_stopPropagation=Ae,e.e_stop=_e,e.addClass=l,e.contains=o,e.rmClass=Fa,e.keyNames=Hl}(qo),qo.version="5.34.0",qo}()}()},function(e,t,n){"use strict";function r(e){return function(){return e}}var i=function(){};i.thatReturns=r,i.thatReturnsFalse=r(!1),i.thatReturnsTrue=r(!0),i.thatReturnsNull=r(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(e){return e},e.exports=i},function(e,t,n){"use strict";function r(e){return{outText:e[0],inLang:e[1],outLang:e[2]}}function i(e){return[e.outText,e.inLang,e.outLang]}function o(e){return e.tag?["Ok",r(e[0])]:["Error",e[0]]}function a(e){return"Ok"===e[0]?h.a(1,[i(e[1])]):h.a(0,[e[1]])}function l(e,t,n,r,i){var o=t?t[0]:3,l=n?n[0]:2,u=r?r[0]:3;return v.a("refmt:refmt",[m.a(m.b(e)),o,l,u],function(e){return g.b(i,a(e))})}function u(e){return v.b("refmt:refmt",function(t,n,r){return g.d(e,t,function(e){return g.b(r,o(e))})})}function s(e){return chrome.storage.local.get("disabled",function(t){return g.b(e,y.a(0,w.a(t.disabled)))}),0}function c(e){return chrome.storage.local.set({disabled:e}),0}function f(e){return chrome.storage.onChanged.addListener(function(t,n){var r=t.disabled;return void 0!==r?g.b(e,r.newValue):0}),0}function d(e){return chrome.storage.local.get("latestRefmtString",function(t){return g.b(e,w.b(t.latestRefmtString))}),0}function p(e){return chrome.storage.local.set({latestRefmtString:e}),0}n.d(t,"c",function(){return T}),n.d(t,"d",function(){return E}),n.d(t,"a",function(){return k}),n.d(t,"b",function(){return S});var h=n(5),g=n(1),m=n(30),v=n(27),y=n(45),b=n(34),w=n(46),x=n(4),C=x.a("Protocol.Refmt.DeserializationFail"),k=[C,r,i,o,a,l,u],S=[s,c,f,d,p],T=b.a,E=b.b;b.c},function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return i}),n.d(t,"c",function(){return o}),n.d(t,"f",function(){return a}),n.d(t,"d",function(){return l}),n.d(t,"e",function(){return u}),n.d(t,"g",function(){return s});var r={display:"flex",overflow:"hidden",flex:"1",flexDirection:"row",justifyContent:"space-around"},i={display:"flex",paddingBottom:"1%",position:"relative",flexDirection:"column"},o={display:"flex",fontFamily:"sans-serif",fontSize:"3vh",maxHeight:"25px",minHeight:"16px",paddingTop:"0.5vh",paddingBottom:"0.5vh",width:"100%",alignItems:"center",flex:"1",justifyContent:"space-between"},a={backgroundColor:"rgba(0,0,0,0.8)",color:"white",display:"flex",fontFamily:"sans-serif",left:"50%",padding:"4vh 8vh 6vh",position:"absolute",top:"50%",zIndex:"10",borderRadius:"2vh",alignItems:"center",flexDirection:"column",justifyContent:"center",transform:"translate(-50%,-50%)"},l={color:"rgb(219, 76, 63)",cursor:"pointer",fontSize:"16px",lineHeight:"16px",paddingLeft:"1vw",textDecoration:"none"},u={cursor:"pointer",height:"16px",paddingLeft:"1vw",width:"16px"},s={flex:"1"}},function(e,t,n){"use strict";function r(e){for(var t=e.length-1|0,n=0;;){var r=n,i=t;if(i<0)return r;n=[e[i],r],t=i-1|0}}n.d(t,"a",function(){return r});var i=(n(1),n(44),n(10)),o=n(4);n(0),o.a("Array.Bottom"),i.f},function(e,t,n){"use strict";function r(e,t){for(;;){var n=t,i=e;if(i===n)return 0;var l=typeof i,u=typeof n;if("string"===l)return o.a(i,n);var s=+("number"===l),c=+("number"===u);if(0!==s)return 0!==c?o.b(i,n):-1;if(0!==c)return 1;if("boolean"===l||"undefined"===l||null===i){var f=i,d=n;return f===d?0:f=1<<28)throw new RangeError("repeat count must not overflow maximum string size");for(var n="";1==(1&e)&&(n+=t),0!=(e>>>=1);)t+=t;return n}},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}/* object-assign (c) Sindre Sorhus @license MIT */ - - -/* eslint-disable no-unused-vars */ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; - -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); -} - -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } - - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } -} - -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; -}; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE - -// 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 . - -(function (global, factory) { - true ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.CodeMirror = factory()); -}(this, (function () { 'use strict'; - -// 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); - -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); - -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); - -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 : ""); - } -}; - -function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - { e.removeChild(e.firstChild); } - return e -} - -function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e) -} - -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 -} - -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 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 -} - -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 -} - -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)} -} - -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 -} - -// 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; - } -} - -var Delayed = function() {this.id = null;}; -Delayed.prototype.set = function (ms, f) { - clearTimeout(this.id); - this.id = setTimeout(f, ms); -}; - -function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - { if (array[i] == elt) { return i } } - return -1 -} - -// Number of pixels added to scroller and sizer to hide scrollbar -var scrollerGap = 30; - -// Returned or thrown by various protocols to signal 'I'm not -// handling this'. -var Pass = {toString: function(){return "CodeMirror.Pass"}}; - -// 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 } - } -} - -var spaceStrs = [""]; -function spaceStr(n) { - while (spaceStrs.length <= n) - { spaceStrs.push(lst(spaceStrs) + " "); } - return spaceStrs[n] -} - -function lst(arr) { return arr[arr.length-1] } - -function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } - return out -} - -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 nothing() {} - -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 -} - -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 isEmpty(obj) { - for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } - return true -} - -// 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 -} - -// 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; } - } -} - -// 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; } - - if (place) { - if (place.appendChild) { place.appendChild(d.wrapper); } - else { place(d.wrapper); } - } - - // 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; - - // 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; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // 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; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - input.init(d); -} - -// 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; - } - } - return chunk.lines[n] -} - -// 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 -} - -// 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; } } -} - -// 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(); - } - } - return no + cur.first -} - -// 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; - } - 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)) -} - -// 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; -} - -// 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 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 } - -// 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 -} - -// Optimize some code when these features are not used. -var sawReadOnlySpans = false; -var sawCollapsedSpans = false; - -function seeReadOnlySpans() { - sawReadOnlySpans = true; -} - -function seeCollapsedSpans() { - sawCollapsedSpans = true; -} - -// TEXTMARKER SPANS - -function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; -} - -// 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); -} - -// 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)); - } - } } - return nw -} - -// 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 } - - 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; } - } - } - } - 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 -} - -// 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 -} - -// 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 -} - -// 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; -} - -// 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 } - -// 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 -} - -// 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) } - -// 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 } - } } -} - -// 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 -} - -function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) - { line = merged.find(1, true).line; } - return line -} - -// 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 -} - -// 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) -} - -// 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 -} - -// 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 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 } - } -} - -// 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 -} - -// 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 -} - -// 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; - } - }); -} - -// BIDI HELPERS - -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 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 -} - -// 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 - -// 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]/; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - 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"; } } - } - - // 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; - } - - // 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; - } - } - - // 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; } - } - - // 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; - } - } - - // 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 (direction == "ltr") { - 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)); - } - } - - return direction == "rtl" ? order.reverse() : order - } -})(); - -// 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 -} - -// EVENT HANDLING - -// Lightweight event framework. on/off also work on DOM nodes, -// registering native DOM handlers. - -var noHandlers = []; - -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); - } -}; - -function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers -} - -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)); } - } - } -} - -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); } -} - -// 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 -} - -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 hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0 -} - -// 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);}; -} - -// Due to the fact that we still support jurassic IE versions, some -// compatibility wrappers are needed. - -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);} - -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 -} - -// 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 -}(); - -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 -} - -// 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) -} - -// 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/); }; - -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 -}; - -var hasCopyEvent = (function () { - var e = elt("div"); - if ("oncopy" in e) { return true } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function" -})(); - -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 -} - -// 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; -} - -function defineMIME(mime, spec) { - mimeModes[mime] = spec; -} - -// 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"} } -} - -// 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]; } } - - return modeObj -} - -// 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); -} - -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 -} - -// 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} -} - -function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true -} - -// STRING STREAM - -// Fed to the mode parsers, provides helper functions to make -// parsers more succinct. - -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; -}; - -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; } -}; -StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n) -}; -StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos) -}; - -var SavedContext = function(state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; -}; - -var Context = function(doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; -}; - -Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } - return line -}; - -Context.prototype.baseToken = function (n) { - var this$1 = this; - - if (!this.baseTokens) { return null } - while (this.baseTokens[this.baseTokenPos] <= n) - { this$1.baseTokenPos += 2; } - var type = this.baseTokens[this.baseTokenPos + 1]; - return {type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n} -}; - -Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { this.maxLookAhead--; } -}; - -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) } -}; - -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 -}; - - -// 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; - - // Run overlays, adjust style array. - var loop = function ( o ) { - context.baseTokens = st; - 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); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - - 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 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); } - } - return line.styles -} - -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 -} - -// 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; - } -} - -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 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.") -} - -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))); } - } - return asArray ? tokens : new Token(stream, style, context.state) -} - -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 -} - -// 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; - } -} - -// 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 -} - -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); -} - -// 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; -}; - -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); } -} - -// Detach a line from the document tree and its markers. -function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); -} - -// 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-$&")) -} - -// 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 = {}; - - // 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({}); - } - } - - // 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"; } - } - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } - - return builder -} - -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 -} - -// 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); -} - -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 -} - -// 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 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; -} - -// 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 (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); - } - } -} - - -// 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); -} - -// 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 -} - -var operationGroup = null; - -function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } -} - -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) -} - -function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { return } - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - endCb(group); - } -} - -var orphanDelayedCallbacks = 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); }); - }; - - for (var i = 0; i < arr.length; ++i) - loop( i ); -} - -function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) { delayed[i](); } -} - -// 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); } - } - 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; } - } - 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); - } -} - -// 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) -} - -// 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; - } -} - -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 || ""; -} - -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 -} - -// 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 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"); - } -} - -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 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 -} - -// 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 } - } -} - -// POSITION MEASUREMENT - -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 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 -} - -// 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); } - } - } - heights.push(rect.bottom - rect.top); - } -} - -// 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} } } -} - -// 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 -} - -// 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) -} - -// 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 } -} - -// 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); } - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - } -} - -// 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} -} - -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 - } - } - 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 -} - -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; - - 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 -} - -// 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} -} - -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] = {}; } } - } -} - -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]); } -} - -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 -} - -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 -} - -// 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; - } - 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; - } - 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; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} -} - -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) -} - -// 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"; - } - if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } - - function getBidi(ch, partPos, invert) { - var part = order[partPos], right = part.level == 1; - return get(invert ? ch - 1 : ch, right != invert) - } - 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 -} - -// 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; } - - 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 } - } -} - -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} -} - -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) -} - -// 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 -} - -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; - - 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; - if (/\s/.test(lineObj.text.charAt(end - 1))) { 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 -} - -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")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { display.cachedTextHeight = height; } - removeChildren(display.measure); - return height || 1 -} - -// 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 -} - -// 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} -} - -// 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 -} - -// 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 } - } -} - -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); } - }); -} - -// 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 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 -} - -// 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 updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); -} - -function prepareSelection(cm, primary) { - if ( primary === void 0 ) primary = true; - - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - 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); } - } - 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); - - 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 cmpCoords(a, b) { return a.top - b.top || a.left - b.left } - -// 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; - var docLTR = doc.direction == "ltr"; - - 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 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) - } - - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop)[prop] - } - - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - - var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; - var first = i == 0, last = !order || i == order.length - 1; - if (toPos.top - fromPos.top <= 3) { // Single line - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { // Multiple lines - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); - } - - 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} - } - - 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); -} - -// 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 ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } -} - -function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } }, 100); -} - -function onFocus(cm, e) { - if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } - - 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(); - } - restartBlink(cm); -} -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); -} - -// 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 > .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]); } } - } - } -} - -// 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) { - var w = line.widgets[i], parent = w.node.parentNode; - if (parent) { w.height = parent.offsetHeight; } - } } -} - -// 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; - } - } - return {from: from, to: Math.max(to, from + 1)} -} - -// 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"; } -} - -// 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 -} - -// 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); - } -} - -// 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 } - } - return rect -} - -// 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); } -} - -// 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; } - } - - 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 -} - -// 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; -} - -// 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}; -} - -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; } -} - -function scrollToRange(cm, range$$1) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range$$1; -} - -// 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); - } -} - -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 - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); -} - -// 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 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; } -} - -// 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); -} - -// SCROLLBARS - -// 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 - } -} - -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); - - 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"; - } - - 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"; - } - - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { this.zeroWidthHack(); } - this.checkedZeroWidth = true; - } - - 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; -}; - -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); -}; - -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; - } -} - -// 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); - - 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"; - - 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 = ""; } -} - -var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - -function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } - } - - 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); } -} - -// 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); -} - -// 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); - }); -} - -// 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]); } -} - -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 endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); -} - -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)); - } - - if (op.updatedDisplay || op.selectionChanged) - { op.preparedSelection = display.input.prepareSelection(); } -} - -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(); - 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); } -} - -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) { setScrollTop(cm, op.scrollTop, op.forceScroll); } - - 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); - } - - // 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"); } } } - - if (display.wrapper.offsetHeight) - { doc.scrollTop = cm.display.scroller.scrollTop; } - - // Fire change events, and delayed event handlers - if (op.changeObjs) - { signal(cm, "changes", cm, op.changeObjs); } - if (op.update) - { op.update.finish(); } -} - -// 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); } - } -} - -// 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); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - { ext.lineN += lendiff; } - else if (from < ext.lineN + ext.size) - { display.externalMeasured = null; } - } -} - -// 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; } - - 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); } -} - -// Clear the view. -function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; -} - -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; - } - 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} -} - -// 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)); } - } - 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 -} - -// HIGHLIGHT WORKER - -function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) - { cm.state.highlight.set(time, bind(highlightWorker, cm)); } -} - -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 = []; - - 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(); - } - 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"); } - }); } -} - -// DISPLAY DRAWING - -var DisplayUpdate = function(cm, viewport, force) { - var display = cm.display; - - 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 = []; -}; - -DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) - { this.events.push(arguments); } -}; -DisplayUpdate.prototype.finish = function () { - var this$1 = this; - - for (var i = 0; i < this.events.length; i++) - { signal.apply(null, this$1.events[i]); } -}; - -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; - } -} - -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; - } - } - return result -} - -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); - } -} - -// 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; - - if (update.editorIsHidden) { - resetView(cm); - return false - } - - // 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); - } - - // 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 different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - 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"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - { return false } - - // 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); - - // 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; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true -} - -function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - - 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; - } - - 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; - } -} - -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(); - } -} - -// 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; - - 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 - } - - 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); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { cur = rm(cur); } -} - -function updateGutterSpace(cm) { - var width = cm.display.gutters.offsetWidth; - cm.display.sizer.style.marginLeft = width + "px"; -} - -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"; -} - -// 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); -} - -// 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); - } -} - -// 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; } - -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 wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta -} - -function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - 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 } - - // 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 - } - } - } - } - - // 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 - } - - // '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 (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; - } - } -} - -// 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] }; - -Selection.prototype.equals = function (other) { - 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 -}; - -Selection.prototype.deepCopy = function () { - 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) -}; - -Selection.prototype.somethingSelected = function () { - var this$1 = this; - - for (var i = 0; i < this.ranges.length; i++) - { if (!this$1.ranges[i].empty()) { return true } } - return false -}; - -Selection.prototype.contains = function (pos, end) { - 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 } - } - return -1 -}; - -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)); - } - } - return new Selection(ranges, primIndex) -} - -function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0) -} - -// 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)) -} - -// 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) -} - -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) -} - -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) } -} - -// 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 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); -} - -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); } -} - -// DOCUMENT DATA STRUCTURE - -// 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) -} - -// 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 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; - - // 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); - } - - signalLater(doc, "change", doc, change); -} - -// 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); -} - -// 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); -} - -function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); -} - -function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); -} - -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; -} - -// 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 -} - -// 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 } - } -} - -// 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) - } -} - -// 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; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || - 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(); } - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) { signal(doc, "historyAdded"); } -} - -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) -} - -// 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; - - // 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); } - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - { clearSelectionEvents(hist.undone); } -} - -function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - { dest.push(sel); } -} - -// 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; - }); -} - -// 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 -} - -// 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 -} - -// 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 } - - 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 -} - -// 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 -} - -// The 'scroll' parameter given to many of these indicated whether -// the new cursor position should be scrolled into view after -// modifying the selection. - -// 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) - } -} - -// 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); -} - -// 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); -} - -// 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); -} - -// Reset the selection to a single range. -function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); -} - -// 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 - }; - 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); -} - -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)); - - if (!(options && options.scroll === false) && doc.cm) - { ensureCursorVisible(doc.cm); } -} - -function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { return } - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); -} - -// Verify that the selection does not partially select any atomic -// marked ranges. -function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); -} - -// 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 -} - -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 (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) } - } - - 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 -} - -// 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 -} - -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) - } -} - -function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); -} - -// UPDATING - -// 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 (obj.canceled) { return null } - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} -} - -// 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 } - } - - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { return } - } - - // 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 { - makeChangeInner(doc, change); - } -} - -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); - - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - - 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)); - }); -} - -// Revert a change stored in a document's history. -function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { return } - - 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; - } else if (suppress) { - source.push(event); - return - } else { break } - } - - // 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 {} - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - 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 = []; - - // 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)); - }); - }; - - for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { - var returned = loop( i$1 ); - - if ( returned ) return returned.v; - } -} - -// 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"); } - } -} - -// 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) } - - 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 } - - // 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}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } - if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } - else { updateDoc(doc, change, spans); } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); -} - -// 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; - - 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 - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - { signalCursorActivity(cm); } - - updateDoc(doc, change, spans, estimateHeight(cm)); - - 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; } - } - - 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 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]); } - if (typeof code == "string") { code = doc.splitLines(code); } - makeChange(doc, {from: from, to: to, text: code, origin: origin}); -} - -// Rebasing/resetting history to deal with externally-sourced changes - -function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } -} - -// 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; - } - } -} - -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); -} - -// 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 -} - -// 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 - -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; -} - -LeafChunk.prototype = { - chunkSize: function() { return this.lines.length }, - - // Remove the n lines at offset 'at'. - 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); - }, - - // Helper used to collapse a small branch into a single leaf. - collapse: function(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(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; } - }, - - // Used to iterate over a part of the tree. - 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 } } - } -}; - -function BranchChunk(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; -} - -BranchChunk.prototype = { - chunkSize: function() { return this.size }, - - 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; - } - }, - - collapse: function(lines) { - var this$1 = this; - - for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } - }, - - insertInner: function(at, lines, height) { - var this$1 = this; - - 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; - } - }, - - // When a node has grown, check whether it should be split. - 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); - } - sibling.parent = me.parent; - } while (me.children.length > 10) - me.parent.maybeSpill(); - }, - - iterN: function(at, n, op) { - var this$1 = this; - - 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; } - } - } -}; - -// 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); - } -}; - -LineWidget.prototype.changed = function () { - var this$1 = this; - - 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); - -function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - { addToScrollTop(cm, diff); } -} - -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 - }); - if (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; -}; - -// Clear the marker. -TextMarker.prototype.clear = function () { - var this$1 = this; - - 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; - } - } } - - 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(); } -}; - -// 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 } - } - } - 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 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); - }); -}; - -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(); - } - - 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); } - }); } - - if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } - - 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 -} - -// SHARED TEXTMARKERS - -// 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; } -}; - -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"); -}; - -SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj) -}; -eventMixin(SharedTextMarker); - -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 findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) -} - -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; - } - } -} - -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); - } - } - }; - - for (var i = 0; i < markers.length; i++) loop( i ); -} - -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; } - - 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; - - if (typeof text == "string") { text = this.splitLines(text); } - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); -}; - -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); } - }, - - // 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); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - 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()) - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, - - getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, - getLineNumber: function(line) {return lineNo(line)}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") { line = getLine(this, line); } - return visualLine(line) - }, - - lineCount: function() {return this.size}, - firstLine: function() {return this.first}, - lastLine: function() {return this.first + this.size - 1}, - - clipPos: function(pos) {return clipPos(this, pos)}, - - 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()}, - - 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; - - 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); - }), - - getSelection: function(lineSep) { - var this$1 = this; - - 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; - } - 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 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);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend}, - - 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);}, - - 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) - }, - - 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); - }, - - 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 - }) - }), - - clearGutter: docMethodOp(function(gutterID) { - var this$1 = this; - - 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 - }); - } - }); - }), - - 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 } - } - 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; - } - 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()); - } - 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; - - 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);}, - - 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" }, - - 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); } - }) -}); - -// Public alias. -Doc.prototype.eachLine = Doc.prototype.iter; - -// 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; - -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){} - } -} - -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 } - - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - - // 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); } - } -} - -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; - } -} - -// These must be handled carefully, because naively registering a -// handler for each editor will cause the editors to never be -// garbage collected. - -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); } - } -} - -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); }); -} -// 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(); -} - -var keyNames = { - 3: "Pause", 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", 145: "ScrollLock", - 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" -}; - -// 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 keyMap = {}; - -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; - -// KEYMAP DISPATCH - -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 -} - -// 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 } - - 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 = "..."; - } - var prev = copy[name]; - if (!prev) { copy[name] = val; } - else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } - } - delete keymap[keyname]; - } } - for (var prop in copy) { keymap[prop] = copy[prop]; } - return keymap -} - -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" } - - 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 } - } - } -} - -// 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 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 -} - -// 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 } - // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, - // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) - if (event.keyCode == 3 && event.code) { name = event.code; } - return addModifierNames(name, event, noShift) -} - -function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val -} - -// 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 - } - } - 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 moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target -} - -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") -} - -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 || cm.doc.direction == "rtl") { - 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) - } - } - return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") -} - -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) - } - - 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); - - 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) - } - } - - // 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) } - } - }; - - // Case 3a: Look for other bidi parts on the same visual line - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); - if (res) { return res } - - // 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 } - } - - // Case 4: Nowhere to move - return null -} - -// 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(); } -}; - - -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 -} - -// 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 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) -} - -// 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" } - if (/\'$/.test(name)) - { cm.state.keySeq = null; } - else - { stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } - } - return dispatchKeyInner(cm, name, e, handle) -} - -function dispatchKeyInner(cm, name, e, handle) { - 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); - } - - return !!result -} - -// 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); }) - } -} - -// 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); -} - -function onKeyUp(e) { - if (e.keyCode == 16) { this.doc.sel.shift = false; } - signalDOMEvent(this, e); -} - -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); -} - -var DOUBLECLICK_DELAY = 400; - -var PastClick = function(time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; -}; - -PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && - cmp(pos, this.pos) == 0 && button == this.button -}; - -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" - } -} - -// 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; - - 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(); - - // #3261: make sure, that we're not starting a second selection - if (button == 1 && cm.state.selectingText) - { cm.state.selectingText(e); } - - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } - - 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); } - } -} - -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; - - 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 - }) -} - -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 -} - -function leftButtonDown(cm, pos, repeat, event) { - if (ie) { setTimeout(bind(ensureFocus, cm), 0); } - else { cm.curOp.focus = activeElt(); } - - var behavior = configureMouse(cm, repeat, event); - - 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); } -} - -// 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(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "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 () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } - else - { display.input.focus(); } - } - }); - 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(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - - delayBlurEvent(cm); - setTimeout(function () { return display.input.focus(); }, 20); -} - -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) -} - -// Normal selection, as opposed to text dragging. -function leftButtonSelect(cm, event, start, behavior) { - var display = cm.display, doc = cm.doc; - e_preventDefault(event); - - 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; - } - - 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; } - } - - 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); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { return } - lastPos = pos; - - 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)))); } - } - 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 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); - } - 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); - } - } - - 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; - - 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); } - } - } - - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - e_preventDefault(e); - display.input.focus(); - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - 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(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); -} - -// 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; } - } - - 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) -} - - -// 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); } - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } - mY -= lineBox.top - display.viewOffset; - - 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) - } - } -} - -function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true) -} - -// CONTEXT MENU HANDLING - -// 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); -} - -function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { return false } - return gutterEvent(cm, e, "gutterContextMenu", false) -} - -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 Init = {toString: function(){return "CodeMirror.Init"}}; - -var defaults = {}; -var optionHandlers = {}; - -function defineOptions(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - 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; } - } - - CodeMirror.defineOption = option; - - // Passed to option handlers when there is no old value. - CodeMirror.Init = Init; - - // 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); - - 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)); - } - 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(); - } - 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 guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - alignHorizontally(cm); -} - -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); - } -} - -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); -} - -// A CodeMirror instance represents an editor. This is the object -// that user code is usually dealing with. - -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"; } -} - -// 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; - } - } - 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; - } - } - }); - 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); - } - 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); - } - }); - - // 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); }); - - // 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); }); -} - -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; } - } - - 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; - } - 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 (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 - } - } - } -} - -// 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; - -function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; -} - -function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { sel = doc.sel; } - - var paste = cm.state.pasteIncoming || origin == "paste"; - var textLines = splitLinesAuto(inserted), multiPaste = null; - // When pasting 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]; }); - } - } - - 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; -} - -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 - } -} - -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; - - 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); } - } -} - -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 disableBrowserMagic(field, spellcheck) { - field.setAttribute("autocorrect", "off"); - field.setAttribute("autocapitalize", "off"); - field.setAttribute("spellcheck", !!spellcheck); -} - -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 -} - -// The publicly visible API. Note that methodOp(f) means -// 'wrap f in an operation, performed on its `this` parameter'. - -// 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 addEditorMethods = function(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - var helpers = CodeMirror.helpers = {}; - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - 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); - }, - - getOption: function(option) {return this.options[option]}, - getDoc: function() {return this.doc}, - - 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 - } } - }, - - 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; - - 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 - } - } - }), - - 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; - - 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); } - } - } - }), - - // 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) - }, - - 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) - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { return mode } - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0] - }, - - getHelpers: function(pos, type) { - var this$1 = this; - - 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 - }, - - 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 - }, - - 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") - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page") - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top) - }, - - 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) - }, - - defaultTextHeight: function() { return textHeight(this.display) }, - defaultCharWidth: function() { return charWidth(this.display) }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, - - 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}); } - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - { return commands[cmd].call(null, this) } - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var this$1 = this; - - 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 - }, - - moveH: methodOp(function(dir, unit) { - var this$1 = this; - - 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); - }), - - 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} - }); } - }), - - findPosV: function(from, amount, unit, goalColumn) { - var this$1 = this; - - 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 - }, - - moveV: methodOp(function(dir, unit) { - var this$1 = this; - - 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]; } } - }), - - // 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)) - }, - - 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"); } - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt() }, - isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, - - 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)} - }, - - 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; - - if (range$$1.from.line != null) { - scrollToRange(this, range$$1); - } else { - scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); - } - }), - - setSize: methodOp(function(width, height) { - var this$1 = this; - - 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); - }), - - operation: function(f){return runInOp(this, f)}, - startOperation: function(){return startOperation(this)}, - endOperation: function(){return endOperation(this)}, - - 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); - }), - - 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 - }), - - 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); - - 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}); - }; -}; - -// 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 (type) { sawType = type; } - if (dir > 0 && !moveOnce(!first)) { break } - } - } - 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; - } - 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 -} - -// 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(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; - } - }); - - on(div, "touchstart", function () { return input.forceCompositionEnd(); }); - - on(div, "input", function () { - if (!this$1.composing) { this$1.readFromDOMSoon(); } - }); - - 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); -}; - -ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = this.cm.state.focused; - return result -}; - -ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { return } - if (info.focus || takeFocus) { this.showPrimarySelection(); } - this.showMultipleSelections(info); -}; - -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 - } - - 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 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]}; - } - - if (!start || !end) { - sel.removeAllRanges(); - return - } - - 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.rememberSelection(); -}; - -ContentEditableInput.prototype.startGracePeriod = function () { - var this$1 = this; - - 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); -}; - -ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); -}; - -ContentEditableInput.prototype.rememberSelection = function () { - var sel = window.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; -}; - -ContentEditableInput.prototype.selectionInEditor = function () { - var sel = window.getSelection(); - if (!sel.rangeCount) { return false } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node) -}; - -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 }; - -ContentEditableInput.prototype.supportsTouch = function () { return true }; - -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); - } - } - this.polling.set(this.cm.options.pollInterval, poll); -}; - -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 - } - 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+$/, ""); - - 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 - } -}; - -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; - - 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); -}; - -ContentEditableInput.prototype.updateFromDOM = function () { - var this$1 = this; - - if (this.cm.isReadOnly() || !this.pollContent()) - { runInOp(this.cm, function () { return regChange(this$1.cm); }); } -}; - -ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; -}; - -ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { return } - e.preventDefault(); - if (!this.cm.isReadOnly()) - { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } -}; - -ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); -}; - -ContentEditableInput.prototype.onContextMenu = function () {}; -ContentEditableInput.prototype.resetPosition = function () {}; - -ContentEditableInput.prototype.needsContentAttribute = true; - -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); - - 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 -} - -function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) - { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } - return false -} - -function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } - -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 - } - 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 - } - 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) } - } -} - -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 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 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 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; } - } -} - -// TEXTAREA INPUT STYLE - -var TextareaInput = function(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // 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; -}; - -TextareaInput.prototype.init = function (display) { - var this$1 = this; - - var input = this, cm = this.cm; - this.createField(display); - var te = this.textarea; - - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - - // 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"; } - - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } - input.poll(); - }); - - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } - - cm.state.pasteIncoming = true; - input.fastPoll(); - }); - - 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); - } - } - 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); } - }); - - 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; - } - }); -}; - -TextareaInput.prototype.createField = function (_display) { - // Wraps and hides input textarea - this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - this.textarea = this.wrapper.firstChild; -}; - -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"; - } -}; - -// 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; } - } -}; - -TextareaInput.prototype.getField = function () { return this.textarea }; - -TextareaInput.prototype.supportsTouch = function () { return false }; - -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 - } -}; - -TextareaInput.prototype.blur = function () { this.textarea.blur(); }; - -TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; -}; - -TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; - -// 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 (this.pollingFast) { return } - this.polling.set(this.cm.options.pollInterval, function () { - this$1.poll(); - if (this$1.cm.state.focused) { this$1.slowPoll(); } - }); -}; - -// 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();} - } - input.polling.set(20, p); -}; - -// 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; - - 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 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 - } - - 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; } - - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, this$1.composing ? "*compose" : null); - - // 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; } - - 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 -}; - -TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { this.pollingFast = false; } -}; - -TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { this.hasSelection = null; } - this.fastPoll(); -}; - -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; - } - } - 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); - } - } - - 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); - } -}; - -TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { this.reset(); } - this.textarea.disabled = val == "nocursor"; -}; - -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) {} - } - } - - 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; } - } - }; - }; - - 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 - -// 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); -}; - -CodeMirror$1.defineMIME = defineMIME; - -// Minimal default mode. -CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); -CodeMirror$1.defineMIME("text/plain", "null"); - -// EXTENSIONS - -CodeMirror$1.defineExtension = function (name, func) { - CodeMirror$1.prototype[name] = func; -}; -CodeMirror$1.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; -}; - -CodeMirror$1.fromTextArea = fromTextArea; - -addLegacyProps(CodeMirror$1); - -CodeMirror$1.version = "5.37.0"; - -return CodeMirror$1; - -}))); - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - */ - - - -var emptyFunction = __webpack_require__(6); - -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warning = emptyFunction; - -if (process.env.NODE_ENV !== 'production') { - 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) {} - }; - - warning = function warning(condition, format) { - if (format === undefined) { - throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); - } - - if (format.indexOf('Failed Composite propType: ') === 0) { - return; // Ignore CompositeComponent proptype check. - } - - 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__(3))) - -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stringOfLanguage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return languageOfString; }); -/* unused harmony export stringOfType */ -/* unused harmony export stringOfLanguageHuman */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Refmt; }); -/* unused harmony export OpenInTab */ -/* unused harmony export ToggleConversion */ -/* unused harmony export RefmtSelection */ -/* unused harmony export LoadScripts */ -/* unused harmony export NotifyLoaded */ -/* unused harmony export QueryLoaded */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Storage; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__content_common_js__ = __webpack_require__(36); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__message_js__ = __webpack_require__(33); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_bs_platform_lib_es6_js_option_js__ = __webpack_require__(52); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__refmt_RefmtShared_js__ = __webpack_require__(40); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_bs_platform_lib_es6_js_primitive_js__ = __webpack_require__(53); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_bs_platform_lib_es6_caml_exceptions_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_bs_platform_lib_es6_caml_builtin_exceptions_js__ = __webpack_require__(0); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - - - - - - - -function stringOfLanguageHuman(lang) { - switch (lang) { - case 0 : - return "ML"; - case 1 : - return "RE"; - case 2 : - return "RE v1"; - case 3 : - return "Unkown"; - - } -} - -var DeserializationFail = __WEBPACK_IMPORTED_MODULE_7_bs_platform_lib_es6_caml_exceptions_js__["a" /* create */]("Protocol.Refmt.DeserializationFail"); - -function payloadToJs(param) { - return { - outText: param[/* outText */0], - inLang: param[/* inLang */1], - outLang: param[/* outLang */2] - }; -} - -function payloadFromJs(param) { - return /* record */[ - /* outText */param.outText, - /* inLang */param.inLang, - /* outLang */param.outLang - ]; -} - -function responseToJs(x) { - console.log("hdon sez responseToJs got:", x); - if (x.tag) { - return /* tuple */[ - "Error", - x[0] - ]; - } else { - return /* tuple */[ - "Ok", - payloadToJs(x[0]) - ]; - } -} - -function responseFromJs(x) { - console.log("hdon sez responseFromJs got:", x); - switch (x[0]) { - case "Error" : - return /* Error */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](1, [x[1]]); - case "Ok" : - return /* Ok */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](0, [payloadFromJs(x[1])]); - default: - throw [ - __WEBPACK_IMPORTED_MODULE_8_bs_platform_lib_es6_caml_builtin_exceptions_js__["g" /* match_failure */], - [ - "protocol.re", - 46, - 4 - ] - ]; - } -} - -function send(text, $staropt$star, $staropt$star$1, $staropt$star$2, cb) { - var inLang = $staropt$star ? $staropt$star[0] : /* UnknownLang */3; - var inType = $staropt$star$1 ? $staropt$star$1[0] : /* UnknownType */2; - var outLang = $staropt$star$2 ? $staropt$star$2[0] : /* UnknownLang */3; - return __WEBPACK_IMPORTED_MODULE_3__message_js__["a" /* query */]("refmt:refmt", /* record */[ - /* input */__WEBPACK_IMPORTED_MODULE_2__content_common_js__["a" /* untoplevel */](__WEBPACK_IMPORTED_MODULE_2__content_common_js__["b" /* normalizeText */](text)), - /* inLang */inLang, - /* inType */inType, - /* outLang */outLang - ], (function (response) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](cb, responseFromJs(response)); - })); -} - -function listen(cb) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("refmt:refmt", (function (request, _, respond) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["d" /* _2 */](cb, request, (function (r) { - console.log("hdon sez listener responding with:", r); - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](respond, responseToJs(r)); - })); - })); -} - -var Refmt = /* module */[ - /* DeserializationFail */DeserializationFail, - /* payloadToJs */payloadToJs, - /* payloadFromJs */payloadFromJs, - /* responseToJs */responseToJs, - /* responseFromJs */responseFromJs, - /* send */send, - /* listen */listen -]; - -function send$1(text) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["c" /* send */]("background:open", text); -} - -function listen$1(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("background:open", (function (text, _, _$1) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, text); - })); -} - -var OpenInTab = /* module */[ - /* send */send$1, - /* listen */listen$1 -]; - -function send$2(tabId) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["d" /* sendTab */](tabId, "content:toggle", /* () */0); -} - -function listen$2(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("content:toggle", (function (_, _$1, _$2) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, /* () */0); - })); -} - -var ToggleConversion = /* module */[ - /* send */send$2, - /* listen */listen$2 -]; - -function send$3(tabId) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["d" /* sendTab */](tabId, "content:refmt-selection", /* () */0); -} - -function listen$3(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("content:refmt-selection", (function (_, _$1, _$2) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, /* () */0); - })); -} - -var RefmtSelection = /* module */[ - /* send */send$3, - /* listen */listen$3 -]; - -function send$4() { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["c" /* send */]("background:load-content-scripts", /* () */0); -} - -function listen$4(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("background:load-content-scripts", (function (_, sender, _$1) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, sender.tab.id); - })); -} - -var LoadScripts = /* module */[ - /* send */send$4, - /* listen */listen$4 -]; - -function send$5(tabId) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["d" /* sendTab */](tabId, "content:notify-loaded", /* () */0); -} - -function listen$5(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("content:notify-loaded", (function (_, _$1, _$2) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, /* () */0); - })); -} - -var NotifyLoaded = /* module */[ - /* send */send$5, - /* listen */listen$5 -]; - -function query(tabId, callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["e" /* queryTab */](tabId, "content:query-loaded", /* () */0, callback); -} - -function listen$6(callback) { - return __WEBPACK_IMPORTED_MODULE_3__message_js__["b" /* receive */]("content:query-loaded", (function (_, _$1, respond) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](respond, __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, /* () */0)); - })); -} - -var QueryLoaded = /* module */[ - /* query */query, - /* listen */listen$6 -]; - -function queryDisabled(callback) { - chrome.storage.local.get("disabled", (function (response) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, __WEBPACK_IMPORTED_MODULE_4_bs_platform_lib_es6_js_option_js__["a" /* getWithDefault */](/* false */0, __WEBPACK_IMPORTED_MODULE_6_bs_platform_lib_es6_js_primitive_js__["a" /* undefined_to_opt */](response.disabled))); - })); - return /* () */0; -} - -function setDisabled(value) { - chrome.storage.local.set({ - disabled: value - }); - return /* () */0; -} - -function onDisabledChanged(callback) { - chrome.storage.onChanged.addListener((function (changes, _) { - var match = changes["disabled"]; - if (match !== undefined) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, match.newValue); - } else { - return /* () */0; - } - })); - return /* () */0; -} - -function queryLatestInput(callback) { - chrome.storage.local.get("latestRefmtString", (function (response) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](callback, __WEBPACK_IMPORTED_MODULE_6_bs_platform_lib_es6_js_primitive_js__["b" /* null_undefined_to_opt */](response.latestRefmtString)); - })); - return /* () */0; -} - -function setLatestInput(value) { - chrome.storage.local.set({ - latestRefmtString: value - }); - return /* () */0; -} - -var Storage = /* module */[ - /* queryDisabled */queryDisabled, - /* setDisabled */setDisabled, - /* onDisabledChanged */onDisabledChanged, - /* queryLatestInput */queryLatestInput, - /* setLatestInput */setLatestInput -]; - -var stringOfLanguage = __WEBPACK_IMPORTED_MODULE_5__refmt_RefmtShared_js__["a" /* stringOfLanguage */]; - -var languageOfString = __WEBPACK_IMPORTED_MODULE_5__refmt_RefmtShared_js__["b" /* languageOfString */]; - -var stringOfType = __WEBPACK_IMPORTED_MODULE_5__refmt_RefmtShared_js__["c" /* stringOfType */]; - - -/* No side effect */ - - -/***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return popup; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return popupColumn; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return popupContext; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return copyConfirmation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return contextLink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return contextIcon; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return contextTitle; }); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - -var popup = { - display: "flex", - overflow: "hidden", - flex: "1", - flexDirection: "row", - justifyContent: "space-around" -}; - -var popupColumn = { - display: "flex", - paddingBottom: "1%", - position: "relative", - flexDirection: "column" -}; - -var popupContext = { - display: "flex", - fontFamily: "sans-serif", - fontSize: "3vh", - maxHeight: "25px", - minHeight: "16px", - paddingTop: "0.5vh", - paddingBottom: "0.5vh", - width: "100%", - alignItems: "center", - flex: "1", - justifyContent: "space-between" -}; - -var copyConfirmation = { - backgroundColor: "rgba(0,0,0,0.8)", - color: "white", - display: "flex", - fontFamily: "sans-serif", - left: "50%", - padding: "4vh 8vh 6vh", - position: "absolute", - top: "50%", - zIndex: "10", - borderRadius: "2vh", - alignItems: "center", - flexDirection: "column", - justifyContent: "center", - transform: "translate(-50%,-50%)" -}; - -var contextLink = { - color: "rgb(219, 76, 63)", - cursor: "pointer", - fontSize: "16px", - lineHeight: "16px", - paddingLeft: "1vw", - textDecoration: "none" -}; - -var contextIcon = { - cursor: "pointer", - height: "16px", - paddingLeft: "1vw", - width: "16px" -}; - -var contextTitle = { - flex: "1" -}; - - -/* No side effect */ - - -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return caml_array_sub; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return caml_array_concat; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_make_vect; }); -/* unused harmony export caml_make_float_vect */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return caml_array_blit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return caml_array_get; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return caml_array_set; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - -function caml_array_sub(x, offset, len) { - var result = new Array(len); - var j = 0; - var i = offset; - while(j < len) { - result[j] = x[i]; - j = j + 1 | 0; - i = i + 1 | 0; - }; - return result; -} - -function len(_acc, _l) { - while(true) { - var l = _l; - var acc = _acc; - if (l) { - _l = l[1]; - _acc = l[0].length + acc | 0; - continue ; - - } else { - return acc; - } - }; -} - -function fill(arr, _i, _l) { - while(true) { - var l = _l; - var i = _i; - if (l) { - var x = l[0]; - var l$1 = x.length; - var k = i; - var j = 0; - while(j < l$1) { - arr[k] = x[j]; - k = k + 1 | 0; - j = j + 1 | 0; - }; - _l = l[1]; - _i = k; - continue ; - - } else { - return /* () */0; - } - }; -} - -function caml_array_concat(l) { - var v = len(0, l); - var result = new Array(v); - fill(result, 0, l); - return result; -} - -function caml_array_set(xs, index, newval) { - if (index < 0 || index >= xs.length) { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "index out of bounds" - ]; - } else { - xs[index] = newval; - return /* () */0; - } -} - -function caml_array_get(xs, index) { - if (index < 0 || index >= xs.length) { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "index out of bounds" - ]; - } else { - return xs[index]; - } -} - -function caml_make_vect(len, init) { - var b = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - b[i] = init; - } - return b; -} - -function caml_make_float_vect(len) { - var b = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - b[i] = 0; - } - return b; -} - -function caml_array_blit(a1, i1, a2, i2, len) { - if (i2 <= i1) { - for(var j = 0 ,j_finish = len - 1 | 0; j <= j_finish; ++j){ - a2[j + i2 | 0] = a1[j + i1 | 0]; - } - return /* () */0; - } else { - for(var j$1 = len - 1 | 0; j$1 >= 0; --j$1){ - a2[j$1 + i2 | 0] = a1[j$1 + i1 | 0]; - } - return /* () */0; - } -} - - -/* No side effect */ - - -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export caml_obj_block */ -/* unused harmony export caml_obj_dup */ -/* unused harmony export caml_obj_truncate */ -/* unused harmony export caml_lazy_make_forward */ -/* unused harmony export caml_update_dummy */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_compare; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return caml_equal; }); -/* unused harmony export caml_equal_null */ -/* unused harmony export caml_equal_undefined */ -/* unused harmony export caml_equal_nullable */ -/* unused harmony export caml_notequal */ -/* unused harmony export caml_greaterequal */ -/* unused harmony export caml_greaterthan */ -/* unused harmony export caml_lessthan */ -/* unused harmony export caml_lessequal */ -/* unused harmony export caml_min */ -/* unused harmony export caml_max */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__block_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_primitive_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - -function caml_obj_block(tag, size) { - var v = new Array(size); - v.tag = tag; - return v; -} - -function caml_obj_dup(x) { - var len = x.length | 0; - var v = new Array(len); - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - v[i] = x[i]; - } - v.tag = x.tag | 0; - return v; -} - -function caml_obj_truncate(x, new_size) { - var len = x.length | 0; - if (new_size <= 0 || new_size > len) { - throw [ - __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Obj.truncate" - ]; - } else if (len !== new_size) { - for(var i = new_size ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - x[i] = 0; - } - x.length = new_size; - return /* () */0; - } else { - return 0; - } -} - -function caml_lazy_make_forward(x) { - return __WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](250, [x]); -} - -function caml_update_dummy(x, y) { - var len = y.length | 0; - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - x[i] = y[i]; - } - var y_tag = y.tag | 0; - if (y_tag !== 0) { - x.tag = y_tag; - return /* () */0; - } else { - return 0; - } -} - -function caml_compare(_a, _b) { - while(true) { - var b = _b; - var a = _a; - if (a === b) { - return 0; - } else { - var a_type = typeof a; - var b_type = typeof b; - if (a_type === "string") { - return __WEBPACK_IMPORTED_MODULE_1__caml_primitive_js__["a" /* caml_string_compare */](a, b); - } else { - var is_a_number = +(a_type === "number"); - var is_b_number = +(b_type === "number"); - if (is_a_number !== 0) { - if (is_b_number !== 0) { - return __WEBPACK_IMPORTED_MODULE_1__caml_primitive_js__["b" /* caml_int_compare */](a, b); - } else { - return -1; - } - } else if (is_b_number !== 0) { - return 1; - } else if (a_type === "boolean" || a_type === "undefined" || a === null) { - var x = a; - var y = b; - if (x === y) { - return 0; - } else if (x < y) { - return -1; - } else { - return 1; - } - } else if (a_type === "function" || b_type === "function") { - throw [ - __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "compare: functional value" - ]; - } else { - var tag_a = a.tag | 0; - var tag_b = b.tag | 0; - if (tag_a === 250) { - _a = a[0]; - continue ; - - } else if (tag_b === 250) { - _b = b[0]; - continue ; - - } else if (tag_a === 248) { - return __WEBPACK_IMPORTED_MODULE_1__caml_primitive_js__["b" /* caml_int_compare */](a[1], b[1]); - } else if (tag_a === 251) { - throw [ - __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "equal: abstract value" - ]; - } else if (tag_a !== tag_b) { - if (tag_a < tag_b) { - return -1; - } else { - return 1; - } - } else { - var len_a = a.length | 0; - var len_b = b.length | 0; - if (len_a === len_b) { - var a$1 = a; - var b$1 = b; - var _i = 0; - var same_length = len_a; - while(true) { - var i = _i; - if (i === same_length) { - return 0; - } else { - var res = caml_compare(a$1[i], b$1[i]); - if (res !== 0) { - return res; - } else { - _i = i + 1 | 0; - continue ; - - } - } - }; - } else if (len_a < len_b) { - var a$2 = a; - var b$2 = b; - var _i$1 = 0; - var short_length = len_a; - while(true) { - var i$1 = _i$1; - if (i$1 === short_length) { - return -1; - } else { - var res$1 = caml_compare(a$2[i$1], b$2[i$1]); - if (res$1 !== 0) { - return res$1; - } else { - _i$1 = i$1 + 1 | 0; - continue ; - - } - } - }; - } else { - var a$3 = a; - var b$3 = b; - var _i$2 = 0; - var short_length$1 = len_b; - while(true) { - var i$2 = _i$2; - if (i$2 === short_length$1) { - return 1; - } else { - var res$2 = caml_compare(a$3[i$2], b$3[i$2]); - if (res$2 !== 0) { - return res$2; - } else { - _i$2 = i$2 + 1 | 0; - continue ; - - } - } - }; - } - } - } - } - } - }; -} - -function caml_equal(_a, _b) { - while(true) { - var b = _b; - var a = _a; - if (a === b) { - return /* true */1; - } else { - var a_type = typeof a; - if (a_type === "string" || a_type === "number" || a_type === "boolean" || a_type === "undefined" || a === null) { - return /* false */0; - } else { - var b_type = typeof b; - if (a_type === "function" || b_type === "function") { - throw [ - __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "equal: functional value" - ]; - } else if (b_type === "number" || b_type === "undefined" || b === null) { - return /* false */0; - } else { - var tag_a = a.tag | 0; - var tag_b = b.tag | 0; - if (tag_a === 250) { - _a = a[0]; - continue ; - - } else if (tag_b === 250) { - _b = b[0]; - continue ; - - } else if (tag_a === 248) { - return +(a[1] === b[1]); - } else if (tag_a === 251) { - throw [ - __WEBPACK_IMPORTED_MODULE_2__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "equal: abstract value" - ]; - } else if (tag_a !== tag_b) { - return /* false */0; - } else { - var len_a = a.length | 0; - var len_b = b.length | 0; - if (len_a === len_b) { - var a$1 = a; - var b$1 = b; - var _i = 0; - var same_length = len_a; - while(true) { - var i = _i; - if (i === same_length) { - return /* true */1; - } else if (caml_equal(a$1[i], b$1[i])) { - _i = i + 1 | 0; - continue ; - - } else { - return /* false */0; - } - }; - } else { - return /* false */0; - } - } - } - } - } - }; -} - -function caml_equal_null(x, y) { - if (y !== null) { - return caml_equal(x, y); - } else { - return +(x === y); - } -} - -function caml_equal_undefined(x, y) { - if (y !== undefined) { - return caml_equal(x, y); - } else { - return +(x === y); - } -} - -function caml_equal_nullable(x, y) { - if (y == null) { - return +(x === y); - } else { - return caml_equal(x, y); - } -} - -function caml_notequal(a, b) { - return 1 - caml_equal(a, b); -} - -function caml_greaterequal(a, b) { - return +(caml_compare(a, b) >= 0); -} - -function caml_greaterthan(a, b) { - return +(caml_compare(a, b) > 0); -} - -function caml_lessequal(a, b) { - return +(caml_compare(a, b) <= 0); -} - -function caml_lessthan(a, b) { - return +(caml_compare(a, b) < 0); -} - -function caml_min(x, y) { - if (caml_compare(x, y) <= 0) { - return x; - } else { - return y; - } -} - -function caml_max(x, y) { - if (caml_compare(x, y) >= 0) { - return x; - } else { - return y; - } -} - - -/* No side effect */ - - -/***/ }), -/* 21 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return repeat; }); - - - -var repeat = ( (String.prototype.repeat && function (count,self){return self.repeat(count)}) || - function(count , self) { - if (self.length == 0 || count == 0) { - return ''; - } - // Ensuring count is a 31-bit integer allows us to heavily optimize the - // main part. But anyway, most current (August 2014) browsers can't handle - // strings 1 << 28 chars or longer, so: - if (self.length * count >= 1 << 28) { - throw new RangeError('repeat count must not overflow maximum string size'); - } - var rpt = ''; - for (;;) { - if ((count & 1) == 1) { - rpt += self; - } - count >>>= 1; - if (count == 0) { - break; - } - self += self; - } - return rpt; - } -); - - -/* repeat Not a pure module */ - - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -"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. - * - */ - - - -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; - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"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. - * - * - */ - -var isTextNode = __webpack_require__(65); - -/*eslint-disable no-bitwise */ - -/** - * Checks if a given DOM node contains or is another DOM node. - */ -function containsNode(outerNode, innerNode) { - if (!outerNode || !innerNode) { - return false; - } else if (outerNode === innerNode) { - return true; - } else if (isTextNode(outerNode)) { - return false; - } else if (isTextNode(innerNode)) { - return containsNode(outerNode, innerNode.parentNode); - } else if ('contains' in outerNode) { - return outerNode.contains(innerNode); - } else if (outerNode.compareDocumentPosition) { - return !!(outerNode.compareDocumentPosition(innerNode) & 16); - } else { - return false; - } -} - -module.exports = containsNode; - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 - */ - -/* eslint-disable fb-www/typeof-undefined */ - -/** - * Same as document.activeElement but wraps in a try-catch block. In IE it is - * not safe to call document.activeElement if there is nothing focused. - * - * The activeElement will be null only if the document or document body is not - * yet defined. - * - * @param {?DOMDocument} doc Defaults to current document. - * @return {?DOMElement} - */ -function getActiveElement(doc) /*?DOMElement*/{ - doc = doc || (typeof document !== 'undefined' ? document : undefined); - if (typeof doc === 'undefined') { - return null; - } - try { - return doc.activeElement || doc.body; - } catch (e) { - return doc.body; - } -} - -module.exports = getActiveElement; - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 - * - */ - -/*eslint-disable no-self-compare */ - - - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -/** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ -function is(x, y) { - // SameValue algorithm - if (x === y) { - // Steps 1-5, 7-10 - // Steps 6.b-6.e: +0 != -0 - // Added the nonzero y check to make Flow happy, but it is redundant - return x !== 0 || y !== 0 || 1 / x === 1 / y; - } else { - // Step 6.a: NaN == NaN - return x !== x && y !== y; - } -} - -/** - * Performs equality by iterating through keys on an object and returning false - * when any key has values which are not strictly equal between the arguments. - * Returns true when the values of all keys are strictly equal. - */ -function shallowEqual(objA, objB) { - if (is(objA, objB)) { - return true; - } - - if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { - return false; - } - - var keysA = Object.keys(objA); - var keysB = Object.keys(objB); - - if (keysA.length !== keysB.length) { - return false; - } - - // Test for A's keys different from B. - for (var i = 0; i < keysA.length; i++) { - if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { - return false; - } - } - - return true; -} - -module.exports = shallowEqual; - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/** - * 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. - */ - - - -if (process.env.NODE_ENV !== 'production') { - var invariant = __webpack_require__(7); - var warning = __webpack_require__(16); - var ReactPropTypesSecret = __webpack_require__(75); - var loggedTypeFailures = {}; -} - -/** - * Assert that the values match with the type specs. - * Error messages are memorized and will only be shown once. - * - * @param {object} typeSpecs Map of name to a ReactPropType - * @param {object} values Runtime values that need to be type-checked - * @param {string} location e.g. "prop", "context", "child context" - * @param {string} componentName Name of the component for error messages. - * @param {?Function} getStack Returns the component stack. - * @private - */ -function checkPropTypes(typeSpecs, values, location, componentName, getStack) { - if (process.env.NODE_ENV !== 'production') { - for (var typeSpecName in typeSpecs) { - if (typeSpecs.hasOwnProperty(typeSpecName)) { - var error; - // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - 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; - } - warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); - if (error instanceof Error && !(error.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error.message] = true; - - var stack = getStack ? getStack() : ''; - - warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); - } - } - } - } -} - -module.exports = checkPropTypes; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 27 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export rejectedPromise */ -/* unused harmony export setHash */ -/* unused harmony export makeContentHash */ -/* unused harmony export generateShareableLink */ -/* unused harmony export getInputFromUrl */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return init; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReactDOMRe_js__ = __webpack_require__(84); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__popupWindow_js__ = __webpack_require__(39); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - - -((__webpack_require__(74))); - -((__webpack_require__(70))); - -((__webpack_require__(72))); - -((__webpack_require__(71))); - -((__webpack_require__(73))); - -((__webpack_require__(69))); - -((__webpack_require__(66))); - -((__webpack_require__(68))); - -((__webpack_require__(57))); - -((__webpack_require__(58))); - -function rejectedPromise() { - return new Promise((function (_, reject) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__["b" /* _1 */](reject, /* () */0); - })); -} - -function setHash(hash) { - window.history.replaceState(({}), "", hash); - return /* () */0; -} - -function makeContentHash(text) { - return "#" + window.btoa(text); -} - -function generateShareableLink(text) { - return "https://reasonml.github.io/reason-tools/popup.html" + text; -} - -function getInputFromUrl() { - var text = window.atob(window.location.hash.slice(1)); - if (text === "") { - return Promise.reject(/* () */0); - } else { - return Promise.resolve(text); - } -} - -function init($staropt$star, $staropt$star$1, onOpen, refmt, _) { - var getSelection = $staropt$star ? $staropt$star[0] : rejectedPromise; - var getLatestInput = $staropt$star$1 ? $staropt$star$1[0] : rejectedPromise; - var inputChanged = function ($staropt$star, $staropt$star$1, input) { - var inLang = $staropt$star ? $staropt$star[0] : /* UnknownLang */3; - var outLang = $staropt$star$1 ? $staropt$star$1[0] : /* UnknownLang */3; - var hash = "#" + window.btoa(input); - var link = "https://reasonml.github.io/reason-tools/popup.html" + hash; - setHash(hash); - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__["c" /* _5 */](refmt, input, /* Some */[inLang], /* None */0, /* Some */[outLang], (function (outText, inLang, outLang) { - var inText = input; - var outText$1 = outText; - var inLang$1 = inLang; - var outLang$1 = outLang; - var link$1 = link; - return __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReactDOMRe_js__["a" /* renderToElementWithId */](__WEBPACK_IMPORTED_MODULE_3_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_2__popupWindow_js__["a" /* make */](inText, inLang$1, outText$1, outLang$1, link$1, onOpen, inputChanged, /* array */[])), "app"); - })); - }; - getInputFromUrl(/* () */0).catch(getSelection).catch(getLatestInput).catch((function () { - return ""; - })).then((function (eta) { - return inputChanged(/* None */0, /* None */0, eta); - })); - return /* () */0; -} - - -/* Not a pure module */ - - -/***/ }), -/* 28 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__vendor_copyToClipboard_js__ = __webpack_require__(35); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - -var component = __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__["c" /* statelessComponent */]("CopyButton"); - -function make($staropt$star, text, onCopy, style, _) { - var label = $staropt$star ? $staropt$star[0] : "copy"; - var newrecord = component.slice(); - newrecord[/* render */9] = (function () { - var tmp = { - className: "copy-button" - }; - if (style) { - tmp.style = style[0]; - } - return __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_2__vendor_copyToClipboard_js__["a" /* make */](text, onCopy, /* array */[__WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("span", tmp, label)])); - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export iconStyle */ -/* unused harmony export textStyle */ -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - -var iconStyle = { - fontSize: "16vh" -}; - -var textStyle = { - fontSize: "3vh", - marginTop: "4vh", - whiteSpace: "nowrap" -}; - -var component = __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__["c" /* statelessComponent */]("CopyConfirmation"); - -function make(show, $staropt$star, style, _) { - var text = $staropt$star ? $staropt$star[0] : "Text copied to clipboard"; - var newrecord = component.slice(); - newrecord[/* render */9] = (function () { - if (show !== 0) { - var tmp = { }; - if (style) { - tmp.style = style[0]; - } - return __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("div", tmp, __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("div", { - style: iconStyle - }, String.fromCodePoint(9112)), __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("div", { - style: textStyle - }, text)); - } else { - return null; - } - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 30 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__vendor_codeMirror_js__ = __webpack_require__(34); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_js_boolean_js__ = __webpack_require__(50); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - -var component = __WEBPACK_IMPORTED_MODULE_2_reason_react_lib_es6_src_ReasonReact_js__["c" /* statelessComponent */]("Editor"); - -function make(value, autoFocus, editorDidMount, lang, $staropt$star, onChange, _) { - var readOnly = $staropt$star ? $staropt$star[0] : /* false */0; - var newrecord = component.slice(); - newrecord[/* render */9] = (function () { - var match = +(lang === /* ML */0); - return __WEBPACK_IMPORTED_MODULE_2_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_0__vendor_codeMirror_js__["a" /* make */](autoFocus, /* None */0, /* Some */[value], editorDidMount, onChange, /* Some */[{ - mode: match !== 0 ? "text/x-ocaml" : "javascript", - theme: "oceanic-next", - readOnly: __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_js_boolean_js__["a" /* to_js_boolean */](readOnly) - }], /* array */[])); - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 31 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - -var component = __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__["c" /* statelessComponent */]("OpenButton"); - -function make(onClick, style, _) { - var newrecord = component.slice(); - newrecord[/* render */9] = (function () { - var tmp = { - className: "open-button", - onClick: onClick - }; - if (style) { - tmp.style = style[0]; - } - return __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("span", tmp, __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("svg", { - style: { - height: "100%", - width: "100%" - }, - viewBox: "0 0 748 1024" - }, __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("path", { - d: "M640 768H128V257.90599999999995L256 256V128H0v768h768V576H640V768zM384 128l128 128L320 448l128 128 192-192 128 128V128H384z" - }))); - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 32 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export Unreachable */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return noop; }); -/* unused harmony export MaybeArray */ -/* unused harmony export Promise */ -/* unused harmony export History */ -/* unused harmony export Util */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_string_js__ = __webpack_require__(56); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_caml_exceptions_js__ = __webpack_require__(5); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - -var Unreachable = __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_caml_exceptions_js__["a" /* create */]("Core.Unreachable"); - -function noop() { - return /* () */0; -} - -var MaybeArray = /* module */[]; - -var Promise = /* module */[]; - -var History = /* module */[]; - -function classNames(items) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_string_js__["a" /* concat */](" ", __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["e" /* filter */]((function (s) { - return +(s !== ""); - }))(__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_list_js__["a" /* map */]((function (param) { - if (param[1] !== 0) { - return param[0]; - } else { - return ""; - } - }), items))); -} - -var Util = /* module */[/* classNames */classNames]; - - -/* No side effect */ - - -/***/ }), -/* 33 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return send; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return sendTab; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return query; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return queryTab; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return receive; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_js__ = __webpack_require__(32); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - -function send(type_, message) { - chrome.runtime.sendMessage(/* record */[ - /* type_ */type_, - /* message */message - ], __WEBPACK_IMPORTED_MODULE_0__core_js__["a" /* noop */]); - return /* () */0; -} - -function sendTab(id, type_, message) { - chrome.tabs.sendMessage(id, /* record */[ - /* type_ */type_, - /* message */message - ], __WEBPACK_IMPORTED_MODULE_0__core_js__["a" /* noop */]); - return /* () */0; -} - -function query(type_, message, callback) { - chrome.runtime.sendMessage(/* record */[ - /* type_ */type_, - /* message */message - ], callback); - return /* () */0; -} - -function queryTab(id, type_, message, callback) { - chrome.tabs.sendMessage(id, /* record */[ - /* type_ */type_, - /* message */message - ], callback); - return /* () */0; -} - -function receive(type_, callback) { - chrome.runtime.onMessage.addListener((function (request, sender, respond) { - if (request[/* type_ */0] === type_) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["a" /* _3 */](callback, request[/* message */1], sender, respond); - } else { - return 0; - } - })); - return /* () */0; -} - - -/* No side effect */ - - -/***/ }), -/* 34 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_js_undefined_js__ = __webpack_require__(54); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_react_codemirror2__ = __webpack_require__(76); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_react_codemirror2___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_react_codemirror2__); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - - -function make(autoFocus, style, value, editorDidMount, onChange, options, children) { - return __WEBPACK_IMPORTED_MODULE_1_reason_react_lib_es6_src_ReasonReact_js__["d" /* wrapJsForReason */](__WEBPACK_IMPORTED_MODULE_3_react_codemirror2__["Controlled"], { - autoFocus: autoFocus && autoFocus[0] !== 0 ? true : false, - style: __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_js_undefined_js__["a" /* fromOption */](style), - value: __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_js_undefined_js__["a" /* fromOption */](value), - onBeforeChange: (function (_, _$1, value) { - if (onChange) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__["b" /* _1 */](onChange[0], value); - } else { - return /* () */0; - } - }), - editorDidMount: __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_js_undefined_js__["a" /* fromOption */](editorDidMount), - options: __WEBPACK_IMPORTED_MODULE_2_bs_platform_lib_es6_js_undefined_js__["a" /* fromOption */](options) - }, children); -} - - -/* ReasonReact Not a pure module */ - - -/***/ }), -/* 35 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_react_copy_to_clipboard__ = __webpack_require__(78); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_react_copy_to_clipboard___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_react_copy_to_clipboard__); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - -function make(text, onCopy, children) { - return __WEBPACK_IMPORTED_MODULE_0_reason_react_lib_es6_src_ReasonReact_js__["d" /* wrapJsForReason */](__WEBPACK_IMPORTED_MODULE_1_react_copy_to_clipboard__, { - text: text, - onCopy: onCopy - }, children); -} - - -/* ReasonReact Not a pure module */ - - -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return normalizeText; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return untoplevel; }); -/* unused harmony export getElementsByTagName */ -/* unused harmony export getElementsByClassName */ -/* unused harmony export querySelectorAll */ -/* unused harmony export createStylesheet */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_array_js__ = __webpack_require__(41); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - -function normalizeText(text) { - return text.trim().replace((/[^\x00-\x7F]/g), " ").replace(String.fromCharCode(65533), ""); -} - -function untoplevel(text) { - if (text.startsWith("# ")) { - return text.slice(2); - } else { - return text; - } -} - -function getElementsByTagName(maybeEl, name) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_array_js__["a" /* to_list */](Array.prototype.slice.call(maybeEl ? maybeEl[0].getElementsByTagName(name) : document.getElementsByTagName(name))); -} - -function getElementsByClassName(maybeEl, name) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_array_js__["a" /* to_list */](Array.prototype.slice.call(maybeEl ? maybeEl[0].getElementsByClassName(name) : document.getElementsByClassName(name))); -} - -function querySelectorAll(el, selector) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_array_js__["a" /* to_list */](Array.prototype.slice.call(el.querySelectorAll(selector))); -} - -function createStylesheet() { - var stylesheet = document.createElement("link"); - var css = (__webpack_require__(67)); - stylesheet.type = "text/css"; - stylesheet.rel = "stylesheet"; - stylesheet.href = chrome.extension.getURL(css); - return stylesheet; -} - - -/* No side effect */ - - -/***/ }), -/* 37 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onOpen", function() { return onOpen; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refmt", function() { return refmt; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__common_protocol_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__popup_popupCommon_js__ = __webpack_require__(27); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - -var onOpen = ( - function (hash) { - window.open( - window.location.href, - "_blank" - ); - } -); - -function refmt(input, $staropt$star, $staropt$star$1, $staropt$star$2, cb) { - var inLang = $staropt$star ? $staropt$star[0] : /* UnknownLang */3; - var inType = $staropt$star$1 ? $staropt$star$1[0] : /* UnknownType */2; - var outLang = $staropt$star$2 ? $staropt$star$2[0] : /* UnknownLang */3; - __WEBPACK_IMPORTED_MODULE_1__common_protocol_js__["a" /* Refmt */][/* send */5](input, /* Some */[inLang], /* Some */[inType], /* Some */[outLang], (function (error) { - if (error.tag) { - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__["a" /* _3 */](cb, error[0], /* UnknownLang */3, /* UnknownLang */3); - } else { - var match = error[0]; - return __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_curry_js__["a" /* _3 */](cb, match[/* outText */0], match[/* inLang */1], match[/* outLang */2]); - } - })); - return __WEBPACK_IMPORTED_MODULE_1__common_protocol_js__["b" /* Storage */][/* setLatestInput */4](input); -} - -document.addEventListener("DOMContentLoaded", (function () { - return __WEBPACK_IMPORTED_MODULE_2__popup_popupCommon_js__["a" /* init */](/* None */0, /* None */0, onOpen, refmt, /* () */0); - })); - - -/* onOpen Not a pure module */ - - -/***/ }), -/* 38 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export showVersion */ -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__popupStyles_js__ = __webpack_require__(18); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - -function showVersion(lang) { - if (lang !== 1) { - if (lang !== 0) { - return ""; - } else { - return "4.02.3"; - } - } else { - return "3.0.0"; - } -} - -var component = __WEBPACK_IMPORTED_MODULE_2_reason_react_lib_es6_src_ReasonReact_js__["c" /* statelessComponent */]("ColumnTItle"); - -function make(lang, select, _) { - var newrecord = component.slice(); - newrecord[/* render */9] = (function () { - return __WEBPACK_IMPORTED_MODULE_0_react__["createElement"]("span", { - style: __WEBPACK_IMPORTED_MODULE_1__popupStyles_js__["g" /* contextTitle */], - title: showVersion(lang) - }, select); - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 39 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export select */ -/* unused harmony export resetTimer */ -/* unused harmony export component */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_react__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__common_components_editor_js__ = __webpack_require__(30); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__common_protocol_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__common_components_copyButton_js__ = __webpack_require__(28); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__common_components_openButton_js__ = __webpack_require__(31); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__columnTitle_js__ = __webpack_require__(38); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__ = __webpack_require__(18); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__common_components_copyConfirmation_js__ = __webpack_require__(29); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - - - - - - - - - - - - -function select(name, onChange, language, lang) { - return __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("select", { - name: name, - value: __WEBPACK_IMPORTED_MODULE_4__common_protocol_js__["c" /* stringOfLanguage */](language), - onChange: onChange - }, __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("option", { - value: "auto" - }, "Auto" + ( - language >= 3 && lang !== /* UnknownLang */3 ? " (" + (__WEBPACK_IMPORTED_MODULE_4__common_protocol_js__["c" /* stringOfLanguage */](lang) + ")") : "" - )), __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("option", { - value: "RE" - }, "RE"), __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("option", { - value: "ML" - }, "ML"), __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("option", { - value: "REO" - }, "RE v1")); -} - -function resetTimer(param) { - var state = param[/* state */2]; - var match = state[/* dialogKillTimer */3][0]; - if (match) { - clearTimeout(match[0]); - } - state[/* dialogKillTimer */3][0] = /* Some */[setTimeout(__WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](param[/* reduce */1], (function () { - return /* RemoveCopyConfirmation */2; - })), 2500)]; - return /* () */0; -} - -var component = __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["b" /* reducerComponent */]("PopupWindow"); - -function make(inText, inLang, outText, outLang, link, onOpen, onInputChanged, _) { - var newrecord = component.slice(); - newrecord[/* render */9] = (function (param) { - var state = param[/* state */2]; - var reduce = param[/* reduce */1]; - console.log(inText); - var inLanguageChange = function ($$event) { - var lang = __WEBPACK_IMPORTED_MODULE_4__common_protocol_js__["d" /* languageOfString */]($$event.target.value); - return /* InLanguageChange */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](0, [lang]); - }; - var outLanguageChange = function ($$event) { - var lang = __WEBPACK_IMPORTED_MODULE_4__common_protocol_js__["d" /* languageOfString */]($$event.target.value); - return /* OutLanguageChange */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](1, [lang]); - }; - var handleInputChange = function (input, param) { - var state = param[/* state */2]; - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["a" /* _3 */](onInputChanged, /* Some */[state[/* inLanguage */1]], /* Some */[state[/* outLanguage */2]], input); - }; - return __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("div", { - style: __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["a" /* popup */] - }, __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("div", { - style: __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["b" /* popupColumn */] - }, __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("h1", { - style: __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["c" /* popupContext */] - }, __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_7__columnTitle_js__["a" /* make */](inLang, select("in", __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](reduce, inLanguageChange), state[/* inLanguage */1], inLang), /* array */[]))), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_3__common_components_editor_js__["a" /* make */](inText, /* Some */[/* true */1], /* Some */[(function (editor) { - editor.execCommand("selectAll"); - return /* () */0; - })], inLang, /* None */0, /* Some */[__WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](param[/* handle */0], handleInputChange)], /* array */[]))), __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("div", { - style: __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["b" /* popupColumn */] - }, __WEBPACK_IMPORTED_MODULE_2_react__["createElement"]("h1", { - style: __WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["c" /* popupContext */] - }, __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_7__columnTitle_js__["a" /* make */](outLang, select("out", __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](reduce, outLanguageChange), state[/* outLanguage */2], outLang), /* array */[])), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_5__common_components_copyButton_js__["a" /* make */](/* Some */["share"], link, __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](reduce, (function () { - return /* LinkCopyConfirmation */0; - })), /* Some */[__WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["d" /* contextLink */]], /* array */[])), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_5__common_components_copyButton_js__["a" /* make */](/* None */0, outText, __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](reduce, (function () { - return /* TextCopyConfirmation */1; - })), /* Some */[__WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["d" /* contextLink */]], /* array */[])), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_6__common_components_openButton_js__["a" /* make */]((function () { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["b" /* _1 */](onOpen, inText); - }), /* Some */[__WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["e" /* contextIcon */]], /* array */[]))), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_3__common_components_editor_js__["a" /* make */](outText, /* None */0, /* None */0, outLang, /* Some */[/* true */1], /* None */0, /* array */[])), __WEBPACK_IMPORTED_MODULE_9_reason_react_lib_es6_src_ReasonReact_js__["a" /* element */](/* None */0, /* None */0, __WEBPACK_IMPORTED_MODULE_10__common_components_copyConfirmation_js__["a" /* make */](+(state[/* copyConfirmation */0] !== ""), /* Some */[state[/* copyConfirmation */0]], /* Some */[__WEBPACK_IMPORTED_MODULE_8__popupStyles_js__["f" /* copyConfirmation */]], /* array */[])))); - }); - newrecord[/* initialState */10] = (function () { - return /* record */[ - /* copyConfirmation */"", - /* inLanguage : UnknownLang */3, - /* outLanguage : UnknownLang */3, - /* dialogKillTimer */[/* None */0] - ]; - }); - newrecord[/* reducer */12] = (function (action, state) { - if (typeof action === "number") { - switch (action) { - case 0 : - return /* UpdateWithSideEffects */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](3, [ - /* record */[ - /* copyConfirmation */"Link copied to clipboard", - /* inLanguage */state[/* inLanguage */1], - /* outLanguage */state[/* outLanguage */2], - /* dialogKillTimer */state[/* dialogKillTimer */3] - ], - resetTimer - ]); - case 1 : - return /* UpdateWithSideEffects */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](3, [ - /* record */[ - /* copyConfirmation */"Text copied to clipboard", - /* inLanguage */state[/* inLanguage */1], - /* outLanguage */state[/* outLanguage */2], - /* dialogKillTimer */state[/* dialogKillTimer */3] - ], - resetTimer - ]); - case 2 : - return /* Update */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](0, [/* record */[ - /* copyConfirmation */"", - /* inLanguage */state[/* inLanguage */1], - /* outLanguage */state[/* outLanguage */2], - /* dialogKillTimer */state[/* dialogKillTimer */3] - ]]); - - } - } else if (action.tag) { - var lang = action[0]; - return /* UpdateWithSideEffects */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](3, [ - /* record */[ - /* copyConfirmation */state[/* copyConfirmation */0], - /* inLanguage */state[/* inLanguage */1], - /* outLanguage */lang, - /* dialogKillTimer */state[/* dialogKillTimer */3] - ], - (function (self) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["a" /* _3 */](onInputChanged, /* Some */[self[/* state */2][/* inLanguage */1]], /* Some */[lang], inText); - }) - ]); - } else { - var lang$1 = action[0]; - return /* UpdateWithSideEffects */__WEBPACK_IMPORTED_MODULE_0_bs_platform_lib_es6_block_js__["a" /* __ */](3, [ - /* record */[ - /* copyConfirmation */state[/* copyConfirmation */0], - /* inLanguage */lang$1, - /* outLanguage */state[/* outLanguage */2], - /* dialogKillTimer */state[/* dialogKillTimer */3] - ], - (function (self) { - return __WEBPACK_IMPORTED_MODULE_1_bs_platform_lib_es6_curry_js__["a" /* _3 */](onInputChanged, /* Some */[lang$1], /* Some */[self[/* state */2][/* outLanguage */2]], inText); - }) - ]); - } - }); - return newrecord; -} - - -/* component Not a pure module */ - - -/***/ }), -/* 40 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return languageOfString; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return stringOfLanguage; }); -/* unused harmony export typeOfString */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stringOfType; }); -// Generated by BUCKLESCRIPT VERSION 2.2.3, PLEASE EDIT WITH CARE - - -function languageOfString(str) { - switch (str) { - case "ML" : - return /* ML */0; - case "RE" : - return /* RE */1; - case "REO" : - return /* REO */2; - default: - return /* UnknownLang */3; - } -} - -function stringOfLanguage(lang) { - switch (lang) { - case 0 : - return "ML"; - case 1 : - return "RE"; - case 2 : - return "REO"; - case 3 : - return "Unkown"; - - } -} - -function typeOfString(str) { - switch (str) { - case "implementation" : - return /* Implementation */0; - case "interface" : - return /* Interface */1; - default: - return /* UnknownType */2; - } -} - -function stringOfType(codeType) { - switch (codeType) { - case 0 : - return "implementation"; - case 1 : - return "interface"; - case 2 : - return "Unkown"; - - } -} - - -/* No side effect */ - - -/***/ }), -/* 41 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export init */ -/* unused harmony export make_matrix */ -/* unused harmony export create_matrix */ -/* unused harmony export append */ -/* unused harmony export concat */ -/* unused harmony export sub */ -/* unused harmony export copy */ -/* unused harmony export fill */ -/* unused harmony export blit */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return to_list; }); -/* unused harmony export of_list */ -/* unused harmony export iter */ -/* unused harmony export map */ -/* unused harmony export iteri */ -/* unused harmony export mapi */ -/* unused harmony export fold_left */ -/* unused harmony export fold_right */ -/* unused harmony export sort */ -/* unused harmony export stable_sort */ -/* unused harmony export fast_sort */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__js_exn_js__ = __webpack_require__(51); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_array_js__ = __webpack_require__(19); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_exceptions_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - - - -function init(l, f) { - if (l === 0) { - return /* array */[]; - } else if (l < 0) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Array.init" - ]; - } else { - var res = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](l, __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, 0)); - for(var i = 1 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ - res[i] = __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, i); - } - return res; - } -} - -function make_matrix(sx, sy, init) { - var res = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](sx, /* array */[]); - for(var x = 0 ,x_finish = sx - 1 | 0; x <= x_finish; ++x){ - res[x] = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](sy, init); - } - return res; -} - -function copy(a) { - var l = a.length; - if (l === 0) { - return /* array */[]; - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["a" /* caml_array_sub */](a, 0, l); - } -} - -function append(a1, a2) { - var l1 = a1.length; - if (l1 === 0) { - return copy(a2); - } else if (a2.length === 0) { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["a" /* caml_array_sub */](a1, 0, l1); - } else { - return a1.concat(a2); - } -} - -function sub(a, ofs, len) { - if (len < 0 || ofs > (a.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Array.sub" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["a" /* caml_array_sub */](a, ofs, len); - } -} - -function fill(a, ofs, len, v) { - if (ofs < 0 || len < 0 || ofs > (a.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Array.fill" - ]; - } else { - for(var i = ofs ,i_finish = (ofs + len | 0) - 1 | 0; i <= i_finish; ++i){ - a[i] = v; - } - return /* () */0; - } -} - -function blit(a1, ofs1, a2, ofs2, len) { - if (len < 0 || ofs1 < 0 || ofs1 > (a1.length - len | 0) || ofs2 < 0 || ofs2 > (a2.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Array.blit" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["c" /* caml_array_blit */](a1, ofs1, a2, ofs2, len); - } -} - -function iter(f, a) { - for(var i = 0 ,i_finish = a.length - 1 | 0; i <= i_finish; ++i){ - __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, a[i]); - } - return /* () */0; -} - -function map(f, a) { - var l = a.length; - if (l === 0) { - return /* array */[]; - } else { - var r = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](l, __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, a[0])); - for(var i = 1 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ - r[i] = __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, a[i]); - } - return r; - } -} - -function iteri(f, a) { - for(var i = 0 ,i_finish = a.length - 1 | 0; i <= i_finish; ++i){ - __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, i, a[i]); - } - return /* () */0; -} - -function mapi(f, a) { - var l = a.length; - if (l === 0) { - return /* array */[]; - } else { - var r = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](l, __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, 0, a[0])); - for(var i = 1 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ - r[i] = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, i, a[i]); - } - return r; - } -} - -function to_list(a) { - var _i = a.length - 1 | 0; - var _res = /* [] */0; - while(true) { - var res = _res; - var i = _i; - if (i < 0) { - return res; - } else { - _res = /* :: */[ - a[i], - res - ]; - _i = i - 1 | 0; - continue ; - - } - }; -} - -function list_length(_accu, _param) { - while(true) { - var param = _param; - var accu = _accu; - if (param) { - _param = param[1]; - _accu = accu + 1 | 0; - continue ; - - } else { - return accu; - } - }; -} - -function of_list(l) { - if (l) { - var a = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](list_length(0, l), l[0]); - var _i = 1; - var _param = l[1]; - while(true) { - var param = _param; - var i = _i; - if (param) { - a[i] = param[0]; - _param = param[1]; - _i = i + 1 | 0; - continue ; - - } else { - return a; - } - }; - } else { - return /* array */[]; - } -} - -function fold_left(f, x, a) { - var r = x; - for(var i = 0 ,i_finish = a.length - 1 | 0; i <= i_finish; ++i){ - r = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, r, a[i]); - } - return r; -} - -function fold_right(f, a, x) { - var r = x; - for(var i = a.length - 1 | 0; i >= 0; --i){ - r = __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](f, a[i], r); - } - return r; -} - -var Bottom = __WEBPACK_IMPORTED_MODULE_3__caml_exceptions_js__["a" /* create */]("Array.Bottom"); - -function sort(cmp, a) { - var maxson = function (l, i) { - var i31 = ((i + i | 0) + i | 0) + 1 | 0; - var x = i31; - if ((i31 + 2 | 0) < l) { - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i31), __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i31 + 1 | 0)) < 0) { - x = i31 + 1 | 0; - } - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, x), __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i31 + 2 | 0)) < 0) { - x = i31 + 2 | 0; - } - return x; - } else if ((i31 + 1 | 0) < l && __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i31), __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i31 + 1 | 0)) < 0) { - return i31 + 1 | 0; - } else if (i31 < l) { - return i31; - } else { - throw [ - Bottom, - i - ]; - } - }; - var trickle = function (l, i, e) { - try { - var l$1 = l; - var _i = i; - var e$1 = e; - while(true) { - var i$1 = _i; - var j = maxson(l$1, i$1); - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, j), e$1) > 0) { - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i$1, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, j)); - _i = j; - continue ; - - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i$1, e$1); - } - }; - } - catch (raw_exn){ - var exn = __WEBPACK_IMPORTED_MODULE_1__js_exn_js__["a" /* internalToOCamlException */](raw_exn); - if (exn[0] === Bottom) { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, exn[1], e); - } else { - throw exn; - } - } - }; - var bubble = function (l, i) { - try { - var l$1 = l; - var _i = i; - while(true) { - var i$1 = _i; - var j = maxson(l$1, i$1); - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i$1, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, j)); - _i = j; - continue ; - - }; - } - catch (raw_exn){ - var exn = __WEBPACK_IMPORTED_MODULE_1__js_exn_js__["a" /* internalToOCamlException */](raw_exn); - if (exn[0] === Bottom) { - return exn[1]; - } else { - throw exn; - } - } - }; - var trickleup = function (_i, e) { - while(true) { - var i = _i; - var father = (i - 1 | 0) / 3 | 0; - if (i === father) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["d" /* assert_failure */], - [ - "array.ml", - 168, - 4 - ] - ]; - } - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, father), e) < 0) { - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, father)); - if (father > 0) { - _i = father; - continue ; - - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, 0, e); - } - } else { - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i, e); - } - }; - }; - var l = a.length; - for(var i = ((l + 1 | 0) / 3 | 0) - 1 | 0; i >= 0; --i){ - trickle(l, i, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i)); - } - for(var i$1 = l - 1 | 0; i$1 >= 2; --i$1){ - var e = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i$1); - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, i$1, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, 0)); - trickleup(bubble(i$1, 0), e); - } - if (l > 1) { - var e$1 = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, 1); - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, 1, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, 0)); - return __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](a, 0, e$1); - } else { - return 0; - } -} - -function stable_sort(cmp, a) { - var merge = function (src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs) { - var src1r = src1ofs + src1len | 0; - var src2r = src2ofs + src2len | 0; - var _i1 = src1ofs; - var _s1 = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, src1ofs); - var _i2 = src2ofs; - var _s2 = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](src2, src2ofs); - var _d = dstofs; - while(true) { - var d = _d; - var s2 = _s2; - var i2 = _i2; - var s1 = _s1; - var i1 = _i1; - if (__WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, s1, s2) <= 0) { - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](dst, d, s1); - var i1$1 = i1 + 1 | 0; - if (i1$1 < src1r) { - _d = d + 1 | 0; - _s1 = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, i1$1); - _i1 = i1$1; - continue ; - - } else { - return blit(src2, i2, dst, d + 1 | 0, src2r - i2 | 0); - } - } else { - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](dst, d, s2); - var i2$1 = i2 + 1 | 0; - if (i2$1 < src2r) { - _d = d + 1 | 0; - _s2 = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](src2, i2$1); - _i2 = i2$1; - continue ; - - } else { - return blit(a, i1, dst, d + 1 | 0, src1r - i1 | 0); - } - } - }; - }; - var isortto = function (srcofs, dst, dstofs, len) { - for(var i = 0 ,i_finish = len - 1 | 0; i <= i_finish; ++i){ - var e = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, srcofs + i | 0); - var j = (dstofs + i | 0) - 1 | 0; - while(j >= dstofs && __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](cmp, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](dst, j), e) > 0) { - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](dst, j + 1 | 0, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](dst, j)); - j = j - 1 | 0; - }; - __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["e" /* caml_array_set */](dst, j + 1 | 0, e); - } - return /* () */0; - }; - var sortto = function (srcofs, dst, dstofs, len) { - if (len <= 5) { - return isortto(srcofs, dst, dstofs, len); - } else { - var l1 = len / 2 | 0; - var l2 = len - l1 | 0; - sortto(srcofs + l1 | 0, dst, dstofs + l1 | 0, l2); - sortto(srcofs, a, srcofs + l2 | 0, l1); - return merge(srcofs + l2 | 0, l1, dst, dstofs + l1 | 0, l2, dst, dstofs); - } - }; - var l = a.length; - if (l <= 5) { - return isortto(0, a, 0, l); - } else { - var l1 = l / 2 | 0; - var l2 = l - l1 | 0; - var t = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["b" /* caml_make_vect */](l2, __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["d" /* caml_array_get */](a, 0)); - sortto(l1, t, 0, l2); - sortto(0, a, l2, l1); - return merge(l2, l1, t, 0, l2, a, 0); - } -} - -var create_matrix = make_matrix; - -var concat = __WEBPACK_IMPORTED_MODULE_2__caml_array_js__["f" /* caml_array_concat */]; - -var fast_sort = stable_sort; - - -/* No side effect */ - - -/***/ }), -/* 42 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return make; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return init; }); -/* unused harmony export empty */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return copy; }); -/* unused harmony export of_string */ -/* unused harmony export to_string */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return sub; }); -/* unused harmony export sub_string */ -/* unused harmony export extend */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return fill; }); -/* unused harmony export blit */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return blit_string; }); -/* unused harmony export concat */ -/* unused harmony export cat */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return iter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return iteri; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return map; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return mapi; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return trim; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return escaped; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return index; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return rindex; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return index_from; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return rindex_from; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return contains; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return contains_from; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return rcontains_from; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return uppercase; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return lowercase; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return capitalize; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return uncapitalize; }); -/* unused harmony export compare */ -/* unused harmony export unsafe_to_string */ -/* unused harmony export unsafe_of_string */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__char_js__ = __webpack_require__(49); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__list_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_obj_js__ = __webpack_require__(20); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__caml_int32_js__ = __webpack_require__(9); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__caml_string_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__caml_primitive_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - - - - - - -function make(n, c) { - var s = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](n); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["g" /* caml_fill_string */](s, 0, n, c); - return s; -} - -function init(n, f) { - var s = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](n); - for(var i = 0 ,i_finish = n - 1 | 0; i <= i_finish; ++i){ - s[i] = __WEBPACK_IMPORTED_MODULE_2__curry_js__["b" /* _1 */](f, i); - } - return s; -} - -var empty = []; - -function copy(s) { - var len = s.length; - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](len); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s, 0, r, 0, len); - return r; -} - -function to_string(b) { - return __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["c" /* bytes_to_string */](copy(b)); -} - -function of_string(s) { - return copy(__WEBPACK_IMPORTED_MODULE_5__caml_string_js__["e" /* bytes_of_string */](s)); -} - -function sub(s, ofs, len) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.sub / Bytes.sub" - ]; - } else { - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](len); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s, ofs, r, 0, len); - return r; - } -} - -function sub_string(b, ofs, len) { - return __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["c" /* bytes_to_string */](sub(b, ofs, len)); -} - -function extend(s, left, right) { - var len = (s.length + left | 0) + right | 0; - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](len); - var match = left < 0 ? /* tuple */[ - -left | 0, - 0 - ] : /* tuple */[ - 0, - left - ]; - var dstoff = match[1]; - var srcoff = match[0]; - var cpylen = __WEBPACK_IMPORTED_MODULE_6__caml_primitive_js__["e" /* caml_int_min */](s.length - srcoff | 0, len - dstoff | 0); - if (cpylen > 0) { - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s, srcoff, r, dstoff, cpylen); - } - return r; -} - -function fill(s, ofs, len, c) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.fill / Bytes.fill" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["g" /* caml_fill_string */](s, ofs, len, c); - } -} - -function blit(s1, ofs1, s2, ofs2, len) { - if (len < 0 || ofs1 < 0 || ofs1 > (s1.length - len | 0) || ofs2 < 0 || ofs2 > (s2.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Bytes.blit" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s1, ofs1, s2, ofs2, len); - } -} - -function blit_string(s1, ofs1, s2, ofs2, len) { - if (len < 0 || ofs1 < 0 || ofs1 > (s1.length - len | 0) || ofs2 < 0 || ofs2 > (s2.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.blit / Bytes.blit_string" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["f" /* caml_blit_string */](s1, ofs1, s2, ofs2, len); - } -} - -function iter(f, a) { - for(var i = 0 ,i_finish = a.length - 1 | 0; i <= i_finish; ++i){ - __WEBPACK_IMPORTED_MODULE_2__curry_js__["b" /* _1 */](f, a[i]); - } - return /* () */0; -} - -function iteri(f, a) { - for(var i = 0 ,i_finish = a.length - 1 | 0; i <= i_finish; ++i){ - __WEBPACK_IMPORTED_MODULE_2__curry_js__["d" /* _2 */](f, i, a[i]); - } - return /* () */0; -} - -function concat(sep, l) { - if (l) { - var hd = l[0]; - var num = [0]; - var len = [0]; - __WEBPACK_IMPORTED_MODULE_1__list_js__["b" /* iter */]((function (s) { - num[0] = num[0] + 1 | 0; - len[0] = len[0] + s.length | 0; - return /* () */0; - }), l); - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](len[0] + __WEBPACK_IMPORTED_MODULE_4__caml_int32_js__["a" /* imul */](sep.length, num[0] - 1 | 0) | 0); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](hd, 0, r, 0, hd.length); - var pos = [hd.length]; - __WEBPACK_IMPORTED_MODULE_1__list_js__["b" /* iter */]((function (s) { - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](sep, 0, r, pos[0], sep.length); - pos[0] = pos[0] + sep.length | 0; - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s, 0, r, pos[0], s.length); - pos[0] = pos[0] + s.length | 0; - return /* () */0; - }), l[1]); - return r; - } else { - return empty; - } -} - -function cat(s1, s2) { - var l1 = s1.length; - var l2 = s2.length; - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](l1 + l2 | 0); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s1, 0, r, 0, l1); - __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["d" /* caml_blit_bytes */](s2, 0, r, l1, l2); - return r; -} - -function is_space(param) { - var switcher = param - 9 | 0; - if (switcher > 4 || switcher < 0) { - if (switcher !== 23) { - return /* false */0; - } else { - return /* true */1; - } - } else if (switcher !== 2) { - return /* true */1; - } else { - return /* false */0; - } -} - -function trim(s) { - var len = s.length; - var i = 0; - while(i < len && is_space(s[i])) { - i = i + 1 | 0; - }; - var j = len - 1 | 0; - while(j >= i && is_space(s[j])) { - j = j - 1 | 0; - }; - if (j >= i) { - return sub(s, i, (j - i | 0) + 1 | 0); - } else { - return empty; - } -} - -function escaped(s) { - var n = 0; - for(var i = 0 ,i_finish = s.length - 1 | 0; i <= i_finish; ++i){ - var match = s[i]; - var tmp; - if (match >= 32) { - var switcher = match - 34 | 0; - tmp = switcher > 58 || switcher < 0 ? ( - switcher >= 93 ? 4 : 1 - ) : ( - switcher > 57 || switcher < 1 ? 2 : 1 - ); - } else { - tmp = match >= 11 ? ( - match !== 13 ? 4 : 2 - ) : ( - match >= 8 ? 2 : 4 - ); - } - n = n + tmp | 0; - } - if (n === s.length) { - return copy(s); - } else { - var s$prime = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](n); - n = 0; - for(var i$1 = 0 ,i_finish$1 = s.length - 1 | 0; i$1 <= i_finish$1; ++i$1){ - var c = s[i$1]; - var exit = 0; - if (c >= 35) { - if (c !== 92) { - if (c >= 127) { - exit = 1; - } else { - s$prime[n] = c; - } - } else { - exit = 2; - } - } else if (c >= 32) { - if (c >= 34) { - exit = 2; - } else { - s$prime[n] = c; - } - } else if (c >= 14) { - exit = 1; - } else { - switch (c) { - case 8 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = /* "b" */98; - break; - case 9 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = /* "t" */116; - break; - case 10 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = /* "n" */110; - break; - case 0 : - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - case 11 : - case 12 : - exit = 1; - break; - case 13 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = /* "r" */114; - break; - - } - } - switch (exit) { - case 1 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = 48 + (c / 100 | 0) | 0; - n = n + 1 | 0; - s$prime[n] = 48 + (c / 10 | 0) % 10 | 0; - n = n + 1 | 0; - s$prime[n] = 48 + c % 10 | 0; - break; - case 2 : - s$prime[n] = /* "\\" */92; - n = n + 1 | 0; - s$prime[n] = c; - break; - - } - n = n + 1 | 0; - } - return s$prime; - } -} - -function map(f, s) { - var l = s.length; - if (l === 0) { - return s; - } else { - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](l); - for(var i = 0 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ - r[i] = __WEBPACK_IMPORTED_MODULE_2__curry_js__["b" /* _1 */](f, s[i]); - } - return r; - } -} - -function mapi(f, s) { - var l = s.length; - if (l === 0) { - return s; - } else { - var r = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["b" /* caml_create_string */](l); - for(var i = 0 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ - r[i] = __WEBPACK_IMPORTED_MODULE_2__curry_js__["d" /* _2 */](f, i, s[i]); - } - return r; - } -} - -function uppercase(s) { - return map(__WEBPACK_IMPORTED_MODULE_0__char_js__["a" /* uppercase */], s); -} - -function lowercase(s) { - return map(__WEBPACK_IMPORTED_MODULE_0__char_js__["b" /* lowercase */], s); -} - -function apply1(f, s) { - if (s.length === 0) { - return s; - } else { - var r = copy(s); - r[0] = __WEBPACK_IMPORTED_MODULE_2__curry_js__["b" /* _1 */](f, s[0]); - return r; - } -} - -function capitalize(s) { - return apply1(__WEBPACK_IMPORTED_MODULE_0__char_js__["a" /* uppercase */], s); -} - -function uncapitalize(s) { - return apply1(__WEBPACK_IMPORTED_MODULE_0__char_js__["b" /* lowercase */], s); -} - -function index_rec(s, lim, _i, c) { - while(true) { - var i = _i; - if (i >= lim) { - throw __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["c" /* not_found */]; - } else if (s[i] === c) { - return i; - } else { - _i = i + 1 | 0; - continue ; - - } - }; -} - -function index(s, c) { - return index_rec(s, s.length, 0, c); -} - -function index_from(s, i, c) { - var l = s.length; - if (i < 0 || i > l) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.index_from / Bytes.index_from" - ]; - } else { - return index_rec(s, l, i, c); - } -} - -function rindex_rec(s, _i, c) { - while(true) { - var i = _i; - if (i < 0) { - throw __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["c" /* not_found */]; - } else if (s[i] === c) { - return i; - } else { - _i = i - 1 | 0; - continue ; - - } - }; -} - -function rindex(s, c) { - return rindex_rec(s, s.length - 1 | 0, c); -} - -function rindex_from(s, i, c) { - if (i < -1 || i >= s.length) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.rindex_from / Bytes.rindex_from" - ]; - } else { - return rindex_rec(s, i, c); - } -} - -function contains_from(s, i, c) { - var l = s.length; - if (i < 0 || i > l) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.contains_from / Bytes.contains_from" - ]; - } else { - try { - index_rec(s, l, i, c); - return /* true */1; - } - catch (exn){ - if (exn === __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["c" /* not_found */]) { - return /* false */0; - } else { - throw exn; - } - } - } -} - -function contains(s, c) { - return contains_from(s, 0, c); -} - -function rcontains_from(s, i, c) { - if (i < 0 || i >= s.length) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "String.rcontains_from / Bytes.rcontains_from" - ]; - } else { - try { - rindex_rec(s, i, c); - return /* true */1; - } - catch (exn){ - if (exn === __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["c" /* not_found */]) { - return /* false */0; - } else { - throw exn; - } - } - } -} - -var compare = __WEBPACK_IMPORTED_MODULE_3__caml_obj_js__["b" /* caml_compare */]; - -var unsafe_to_string = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["c" /* bytes_to_string */]; - -var unsafe_of_string = __WEBPACK_IMPORTED_MODULE_5__caml_string_js__["e" /* bytes_of_string */]; - - -/* No side effect */ - - -/***/ }), -/* 43 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return caml_format_float; }); -/* unused harmony export caml_format_int */ -/* unused harmony export caml_nativeint_format */ -/* unused harmony export caml_int32_format */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return caml_float_of_string; }); -/* unused harmony export caml_int64_format */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return caml_int_of_string; }); -/* unused harmony export caml_int32_of_string */ -/* unused harmony export caml_int64_of_string */ -/* unused harmony export caml_nativeint_of_string */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_int32_js__ = __webpack_require__(9); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__ = __webpack_require__(44); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_utils_js__ = __webpack_require__(21); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - - - -function caml_failwith(s) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - s - ]; -} - -function parse_digit(c) { - if (c >= 65) { - if (c >= 97) { - if (c >= 123) { - return -1; - } else { - return c - 87 | 0; - } - } else if (c >= 91) { - return -1; - } else { - return c - 55 | 0; - } - } else if (c > 57 || c < 48) { - return -1; - } else { - return c - /* "0" */48 | 0; - } -} - -function int_of_string_base(param) { - switch (param) { - case 0 : - return 8; - case 1 : - return 16; - case 2 : - return 10; - case 3 : - return 2; - - } -} - -function parse_sign_and_base(s) { - var sign = 1; - var base = /* Dec */2; - var i = 0; - if (s[i] === "-") { - sign = -1; - i = i + 1 | 0; - } - var match = s.charCodeAt(i); - var match$1 = s.charCodeAt(i + 1 | 0); - if (match === 48) { - if (match$1 >= 89) { - if (match$1 !== 98) { - if (match$1 !== 111) { - if (match$1 === 120) { - base = /* Hex */1; - i = i + 2 | 0; - } - - } else { - base = /* Oct */0; - i = i + 2 | 0; - } - } else { - base = /* Bin */3; - i = i + 2 | 0; - } - } else if (match$1 !== 66) { - if (match$1 !== 79) { - if (match$1 >= 88) { - base = /* Hex */1; - i = i + 2 | 0; - } - - } else { - base = /* Oct */0; - i = i + 2 | 0; - } - } else { - base = /* Bin */3; - i = i + 2 | 0; - } - } - return /* tuple */[ - i, - sign, - base - ]; -} - -function caml_int_of_string(s) { - var match = parse_sign_and_base(s); - var i = match[0]; - var base = int_of_string_base(match[2]); - var threshold = 4294967295; - var len = s.length; - var c = i < len ? s.charCodeAt(i) : /* "\000" */0; - var d = parse_digit(c); - if (d < 0 || d >= base) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int_of_string" - ]; - } - var aux = function (_acc, _k) { - while(true) { - var k = _k; - var acc = _acc; - if (k === len) { - return acc; - } else { - var a = s.charCodeAt(k); - if (a === /* "_" */95) { - _k = k + 1 | 0; - continue ; - - } else { - var v = parse_digit(a); - if (v < 0 || v >= base) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int_of_string" - ]; - } else { - var acc$1 = base * acc + v; - if (acc$1 > threshold) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int_of_string" - ]; - } else { - _k = k + 1 | 0; - _acc = acc$1; - continue ; - - } - } - } - } - }; - }; - var res = match[1] * aux(d, i + 1 | 0); - var or_res = res | 0; - if (base === 10 && res !== or_res) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int_of_string" - ]; - } - return or_res; -} - -function caml_int64_of_string(s) { - var match = parse_sign_and_base(s); - var hbase = match[2]; - var i = match[0]; - var base = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["a" /* of_int32 */](int_of_string_base(hbase)); - var sign = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["a" /* of_int32 */](match[1]); - var threshold; - switch (hbase) { - case 0 : - threshold = /* int64 */[ - /* hi */536870911, - /* lo */4294967295 - ]; - break; - case 1 : - threshold = /* int64 */[ - /* hi */268435455, - /* lo */4294967295 - ]; - break; - case 2 : - threshold = /* int64 */[ - /* hi */429496729, - /* lo */2576980377 - ]; - break; - case 3 : - threshold = /* int64 */[ - /* hi */2147483647, - /* lo */4294967295 - ]; - break; - - } - var len = s.length; - var c = i < len ? s.charCodeAt(i) : /* "\000" */0; - var d = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["a" /* of_int32 */](parse_digit(c)); - if (__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["b" /* lt */](d, /* int64 */[ - /* hi */0, - /* lo */0 - ]) || __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["c" /* ge */](d, base)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int64_of_string" - ]; - } - var aux = function (_acc, _k) { - while(true) { - var k = _k; - var acc = _acc; - if (k === len) { - return acc; - } else { - var a = s.charCodeAt(k); - if (a === /* "_" */95) { - _k = k + 1 | 0; - continue ; - - } else { - var v = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["a" /* of_int32 */](parse_digit(a)); - if (__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["b" /* lt */](v, /* int64 */[ - /* hi */0, - /* lo */0 - ]) || __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["c" /* ge */](v, base) || __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["d" /* gt */](acc, threshold)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int64_of_string" - ]; - } else { - var acc$1 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["e" /* add */](__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["f" /* mul */](base, acc), v); - _k = k + 1 | 0; - _acc = acc$1; - continue ; - - } - } - } - }; - }; - var res = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["f" /* mul */](sign, aux(d, i + 1 | 0)); - var or_res = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["g" /* or_ */](res, /* int64 */[ - /* hi */0, - /* lo */0 - ]); - if (__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["h" /* eq */](base, /* int64 */[ - /* hi */0, - /* lo */10 - ]) && __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["i" /* neq */](res, or_res)) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["b" /* failure */], - "int64_of_string" - ]; - } - return or_res; -} - -function int_of_base(param) { - switch (param) { - case 0 : - return 8; - case 1 : - return 16; - case 2 : - return 10; - - } -} - -function lowercase(c) { - if (c >= /* "A" */65 && c <= /* "Z" */90 || c >= /* "\192" */192 && c <= /* "\214" */214 || c >= /* "\216" */216 && c <= /* "\222" */222) { - return c + 32 | 0; - } else { - return c; - } -} - -function parse_format(fmt) { - var len = fmt.length; - if (len > 31) { - throw [ - __WEBPACK_IMPORTED_MODULE_4__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "format_int: format too long" - ]; - } - var f = /* record */[ - /* justify */"+", - /* signstyle */"-", - /* filter */" ", - /* alternate : false */0, - /* base : Dec */2, - /* signedconv : false */0, - /* width */0, - /* uppercase : false */0, - /* sign */1, - /* prec */-1, - /* conv */"f" - ]; - var _i = 0; - while(true) { - var i = _i; - if (i >= len) { - return f; - } else { - var c = fmt.charCodeAt(i); - var exit = 0; - if (c >= 69) { - if (c >= 88) { - if (c >= 121) { - exit = 1; - } else { - switch (c - 88 | 0) { - case 0 : - f[/* base */4] = /* Hex */1; - f[/* uppercase */7] = /* true */1; - _i = i + 1 | 0; - continue ; - case 13 : - case 14 : - case 15 : - exit = 5; - break; - case 12 : - case 17 : - exit = 4; - break; - case 23 : - f[/* base */4] = /* Oct */0; - _i = i + 1 | 0; - continue ; - case 29 : - f[/* base */4] = /* Dec */2; - _i = i + 1 | 0; - continue ; - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - case 8 : - case 9 : - case 10 : - case 11 : - case 16 : - case 18 : - case 19 : - case 20 : - case 21 : - case 22 : - case 24 : - case 25 : - case 26 : - case 27 : - case 28 : - case 30 : - case 31 : - exit = 1; - break; - case 32 : - f[/* base */4] = /* Hex */1; - _i = i + 1 | 0; - continue ; - - } - } - } else if (c >= 72) { - exit = 1; - } else { - f[/* signedconv */5] = /* true */1; - f[/* uppercase */7] = /* true */1; - f[/* conv */10] = String.fromCharCode(lowercase(c)); - _i = i + 1 | 0; - continue ; - - } - } else { - var switcher = c - 32 | 0; - if (switcher > 25 || switcher < 0) { - exit = 1; - } else { - switch (switcher) { - case 3 : - f[/* alternate */3] = /* true */1; - _i = i + 1 | 0; - continue ; - case 0 : - case 11 : - exit = 2; - break; - case 13 : - f[/* justify */0] = "-"; - _i = i + 1 | 0; - continue ; - case 14 : - f[/* prec */9] = 0; - var j = i + 1 | 0; - while((function(j){ - return function () { - var w = fmt.charCodeAt(j) - /* "0" */48 | 0; - return +(w >= 0 && w <= 9); - } - }(j))()) { - f[/* prec */9] = (__WEBPACK_IMPORTED_MODULE_1__caml_int32_js__["a" /* imul */](f[/* prec */9], 10) + fmt.charCodeAt(j) | 0) - /* "0" */48 | 0; - j = j + 1 | 0; - }; - _i = j; - continue ; - case 1 : - case 2 : - case 4 : - case 5 : - case 6 : - case 7 : - case 8 : - case 9 : - case 10 : - case 12 : - case 15 : - exit = 1; - break; - case 16 : - f[/* filter */2] = "0"; - _i = i + 1 | 0; - continue ; - case 17 : - case 18 : - case 19 : - case 20 : - case 21 : - case 22 : - case 23 : - case 24 : - case 25 : - exit = 3; - break; - - } - } - } - switch (exit) { - case 1 : - _i = i + 1 | 0; - continue ; - case 2 : - f[/* signstyle */1] = String.fromCharCode(c); - _i = i + 1 | 0; - continue ; - case 3 : - f[/* width */6] = 0; - var j$1 = i; - while((function(j$1){ - return function () { - var w = fmt.charCodeAt(j$1) - /* "0" */48 | 0; - return +(w >= 0 && w <= 9); - } - }(j$1))()) { - f[/* width */6] = (__WEBPACK_IMPORTED_MODULE_1__caml_int32_js__["a" /* imul */](f[/* width */6], 10) + fmt.charCodeAt(j$1) | 0) - /* "0" */48 | 0; - j$1 = j$1 + 1 | 0; - }; - _i = j$1; - continue ; - case 4 : - f[/* signedconv */5] = /* true */1; - f[/* base */4] = /* Dec */2; - _i = i + 1 | 0; - continue ; - case 5 : - f[/* signedconv */5] = /* true */1; - f[/* conv */10] = String.fromCharCode(c); - _i = i + 1 | 0; - continue ; - - } - } - }; -} - -function finish_formatting(param, rawbuffer) { - var justify = param[/* justify */0]; - var signstyle = param[/* signstyle */1]; - var filter = param[/* filter */2]; - var alternate = param[/* alternate */3]; - var base = param[/* base */4]; - var signedconv = param[/* signedconv */5]; - var width = param[/* width */6]; - var uppercase = param[/* uppercase */7]; - var sign = param[/* sign */8]; - var len = rawbuffer.length; - if (signedconv && (sign < 0 || signstyle !== "-")) { - len = len + 1 | 0; - } - if (alternate) { - if (base === /* Oct */0) { - len = len + 1 | 0; - } else if (base === /* Hex */1) { - len = len + 2 | 0; - } - - } - var buffer = ""; - if (justify === "+" && filter === " ") { - for(var i = len ,i_finish = width - 1 | 0; i <= i_finish; ++i){ - buffer = buffer + filter; - } - } - if (signedconv) { - if (sign < 0) { - buffer = buffer + "-"; - } else if (signstyle !== "-") { - buffer = buffer + signstyle; - } - - } - if (alternate && base === /* Oct */0) { - buffer = buffer + "0"; - } - if (alternate && base === /* Hex */1) { - buffer = buffer + "0x"; - } - if (justify === "+" && filter === "0") { - for(var i$1 = len ,i_finish$1 = width - 1 | 0; i$1 <= i_finish$1; ++i$1){ - buffer = buffer + filter; - } - } - buffer = uppercase ? buffer + rawbuffer.toUpperCase() : buffer + rawbuffer; - if (justify === "-") { - for(var i$2 = len ,i_finish$2 = width - 1 | 0; i$2 <= i_finish$2; ++i$2){ - buffer = buffer + " "; - } - } - return buffer; -} - -function caml_format_int(fmt, i) { - if (fmt === "%d") { - return String(i); - } else { - var f = parse_format(fmt); - var f$1 = f; - var i$1 = i; - var i$2 = i$1 < 0 ? ( - f$1[/* signedconv */5] ? (f$1[/* sign */8] = -1, -i$1) : (i$1 >>> 0) - ) : i$1; - var s = i$2.toString(int_of_base(f$1[/* base */4])); - if (f$1[/* prec */9] >= 0) { - f$1[/* filter */2] = " "; - var n = f$1[/* prec */9] - s.length | 0; - if (n > 0) { - s = __WEBPACK_IMPORTED_MODULE_3__caml_utils_js__["a" /* repeat */](n, "0") + s; - } - - } - return finish_formatting(f$1, s); - } -} - -function caml_int64_format(fmt, x) { - var f = parse_format(fmt); - var x$1 = f[/* signedconv */5] && __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["b" /* lt */](x, /* int64 */[ - /* hi */0, - /* lo */0 - ]) ? (f[/* sign */8] = -1, __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["j" /* neg */](x)) : x; - var s = ""; - var match = f[/* base */4]; - switch (match) { - case 0 : - var wbase = /* int64 */[ - /* hi */0, - /* lo */8 - ]; - var cvtbl = "01234567"; - if (__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["b" /* lt */](x$1, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var y = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["k" /* discard_sign */](x$1); - var match$1 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](y, wbase); - var quotient = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["e" /* add */](/* int64 */[ - /* hi */268435456, - /* lo */0 - ], match$1[0]); - var modulus = match$1[1]; - s = String.fromCharCode(cvtbl.charCodeAt(modulus[1] | 0)) + s; - while(__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["i" /* neq */](quotient, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var match$2 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](quotient, wbase); - quotient = match$2[0]; - modulus = match$2[1]; - s = String.fromCharCode(cvtbl.charCodeAt(modulus[1] | 0)) + s; - }; - } else { - var match$3 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](x$1, wbase); - var quotient$1 = match$3[0]; - var modulus$1 = match$3[1]; - s = String.fromCharCode(cvtbl.charCodeAt(modulus$1[1] | 0)) + s; - while(__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["i" /* neq */](quotient$1, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var match$4 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](quotient$1, wbase); - quotient$1 = match$4[0]; - modulus$1 = match$4[1]; - s = String.fromCharCode(cvtbl.charCodeAt(modulus$1[1] | 0)) + s; - }; - } - break; - case 1 : - s = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["m" /* to_hex */](x$1) + s; - break; - case 2 : - var wbase$1 = /* int64 */[ - /* hi */0, - /* lo */10 - ]; - var cvtbl$1 = "0123456789"; - if (__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["b" /* lt */](x$1, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var y$1 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["k" /* discard_sign */](x$1); - var match$5 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](y$1, wbase$1); - var match$6 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["e" /* add */](/* int64 */[ - /* hi */0, - /* lo */8 - ], match$5[1]), wbase$1); - var quotient$2 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["e" /* add */](__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["e" /* add */](/* int64 */[ - /* hi */214748364, - /* lo */3435973836 - ], match$5[0]), match$6[0]); - var modulus$2 = match$6[1]; - s = String.fromCharCode(cvtbl$1.charCodeAt(modulus$2[1] | 0)) + s; - while(__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["i" /* neq */](quotient$2, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var match$7 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](quotient$2, wbase$1); - quotient$2 = match$7[0]; - modulus$2 = match$7[1]; - s = String.fromCharCode(cvtbl$1.charCodeAt(modulus$2[1] | 0)) + s; - }; - } else { - var match$8 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](x$1, wbase$1); - var quotient$3 = match$8[0]; - var modulus$3 = match$8[1]; - s = String.fromCharCode(cvtbl$1.charCodeAt(modulus$3[1] | 0)) + s; - while(__WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["i" /* neq */](quotient$3, /* int64 */[ - /* hi */0, - /* lo */0 - ])) { - var match$9 = __WEBPACK_IMPORTED_MODULE_2__caml_int64_js__["l" /* div_mod */](quotient$3, wbase$1); - quotient$3 = match$9[0]; - modulus$3 = match$9[1]; - s = String.fromCharCode(cvtbl$1.charCodeAt(modulus$3[1] | 0)) + s; - }; - } - break; - - } - if (f[/* prec */9] >= 0) { - f[/* filter */2] = " "; - var n = f[/* prec */9] - s.length | 0; - if (n > 0) { - s = __WEBPACK_IMPORTED_MODULE_3__caml_utils_js__["a" /* repeat */](n, "0") + s; - } - - } - return finish_formatting(f, s); -} - -function caml_format_float(fmt, x) { - var f = parse_format(fmt); - var prec = f[/* prec */9] < 0 ? 6 : f[/* prec */9]; - var x$1 = x < 0 ? (f[/* sign */8] = -1, -x) : x; - var s = ""; - if (isNaN(x$1)) { - s = "nan"; - f[/* filter */2] = " "; - } else if (isFinite(x$1)) { - var match = f[/* conv */10]; - switch (match) { - case "e" : - s = x$1.toExponential(prec); - var i = s.length; - if (s[i - 3 | 0] === "e") { - s = s.slice(0, i - 1 | 0) + ("0" + s.slice(i - 1 | 0)); - } - break; - case "f" : - s = x$1.toFixed(prec); - break; - case "g" : - var prec$1 = prec !== 0 ? prec : 1; - s = x$1.toExponential(prec$1 - 1 | 0); - var j = s.indexOf("e"); - var exp = Number(s.slice(j + 1 | 0)) | 0; - if (exp < -4 || x$1 >= 1e21 || x$1.toFixed().length > prec$1) { - var i$1 = j - 1 | 0; - while(s[i$1] === "0") { - i$1 = i$1 - 1 | 0; - }; - if (s[i$1] === ".") { - i$1 = i$1 - 1 | 0; - } - s = s.slice(0, i$1 + 1 | 0) + s.slice(j); - var i$2 = s.length; - if (s[i$2 - 3 | 0] === "e") { - s = s.slice(0, i$2 - 1 | 0) + ("0" + s.slice(i$2 - 1 | 0)); - } - - } else { - var p = prec$1; - if (exp < 0) { - p = p - (exp + 1 | 0) | 0; - s = x$1.toFixed(p); - } else { - while((function () { - s = x$1.toFixed(p); - return +(s.length > (prec$1 + 1 | 0)); - })()) { - p = p - 1 | 0; - }; - } - if (p !== 0) { - var k = s.length - 1 | 0; - while(s[k] === "0") { - k = k - 1 | 0; - }; - if (s[k] === ".") { - k = k - 1 | 0; - } - s = s.slice(0, k + 1 | 0); - } - - } - break; - default: - - } - } else { - s = "inf"; - f[/* filter */2] = " "; - } - return finish_formatting(f, s); -} - -var float_of_string = ( - function (s, caml_failwith) { - var res = +s; - if ((s.length > 0) && (res === res)) - return res; - s = s.replace(/_/g, ""); - res = +s; - if (((s.length > 0) && (res === res)) || /^[+-]?nan$/i.test(s)) { - return res; - } - ; - if (/^ *0x[0-9a-f_]+p[+-]?[0-9_]+/i.test(s)) { - var pidx = s.indexOf('p'); - pidx = (pidx == -1) ? s.indexOf('P') : pidx; - var exp = +s.substring(pidx + 1); - res = +s.substring(0, pidx); - return res * Math.pow(2, exp); - } - if (/^\+?inf(inity)?$/i.test(s)) - return Infinity; - if (/^-inf(inity)?$/i.test(s)) - return -Infinity; - caml_failwith("float_of_string"); -} - -); - -function caml_float_of_string(s) { - return __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](float_of_string, s, caml_failwith); -} - -var caml_nativeint_format = caml_format_int; - -var caml_int32_format = caml_format_int; - -var caml_int32_of_string = caml_int_of_string; - -var caml_nativeint_of_string = caml_int_of_string; - - -/* float_of_string Not a pure module */ - - -/***/ }), -/* 44 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export min_int */ -/* unused harmony export max_int */ -/* unused harmony export one */ -/* unused harmony export zero */ -/* unused harmony export not */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return of_int32; }); -/* unused harmony export to_int32 */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return add; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return neg; }); -/* unused harmony export sub */ -/* unused harmony export lsl_ */ -/* unused harmony export lsr_ */ -/* unused harmony export asr_ */ -/* unused harmony export is_zero */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return mul; }); -/* unused harmony export xor */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return or_; }); -/* unused harmony export and_ */ -/* unused harmony export swap */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ge; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return eq; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return neq; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return lt; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return gt; }); -/* unused harmony export le */ -/* unused harmony export equal_null */ -/* unused harmony export equal_undefined */ -/* unused harmony export equal_nullable */ -/* unused harmony export min */ -/* unused harmony export max */ -/* unused harmony export to_float */ -/* unused harmony export of_float */ -/* unused harmony export div */ -/* unused harmony export mod_ */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return div_mod; }); -/* unused harmony export compare */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return to_hex; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return discard_sign; }); -/* unused harmony export float_of_bits */ -/* unused harmony export bits_of_float */ -/* unused harmony export get64 */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_int32_js__ = __webpack_require__(9); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_utils_js__ = __webpack_require__(21); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_primitive_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - - - -var min_int = /* record */[ - /* hi */-2147483648, - /* lo */0 -]; - -var max_int = /* record */[ - /* hi */2147483647, - /* lo */1 -]; - -var one = /* record */[ - /* hi */0, - /* lo */1 -]; - -var zero = /* record */[ - /* hi */0, - /* lo */0 -]; - -var neg_one = /* record */[ - /* hi */-1, - /* lo */4294967295 -]; - -function neg_signed(x) { - return +((x & 2147483648) !== 0); -} - -function add(param, param$1) { - var other_low_ = param$1[/* lo */1]; - var this_low_ = param[/* lo */1]; - var lo = this_low_ + other_low_ & 4294967295; - var overflow = neg_signed(this_low_) && (neg_signed(other_low_) || !neg_signed(lo)) || neg_signed(other_low_) && !neg_signed(lo) ? 1 : 0; - var hi = param[/* hi */0] + param$1[/* hi */0] + overflow & 4294967295; - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; -} - -function not(param) { - var hi = param[/* hi */0] ^ -1; - var lo = param[/* lo */1] ^ -1; - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; -} - -function eq(x, y) { - if (x[/* hi */0] === y[/* hi */0]) { - return +(x[/* lo */1] === y[/* lo */1]); - } else { - return /* false */0; - } -} - -function equal_null(x, y) { - if (y !== null) { - return eq(x, y); - } else { - return /* false */0; - } -} - -function equal_undefined(x, y) { - if (y !== undefined) { - return eq(x, y); - } else { - return /* false */0; - } -} - -function equal_nullable(x, y) { - if (y == null) { - return /* false */0; - } else { - return eq(x, y); - } -} - -function neg(x) { - if (eq(x, min_int)) { - return min_int; - } else { - return add(not(x), one); - } -} - -function sub(x, y) { - return add(x, neg(y)); -} - -function lsl_(x, numBits) { - if (numBits === 0) { - return x; - } else { - var lo = x[/* lo */1]; - if (numBits >= 32) { - return /* record */[ - /* hi */(lo << (numBits - 32 | 0)), - /* lo */0 - ]; - } else { - var hi = (lo >>> (32 - numBits | 0)) | (x[/* hi */0] << numBits); - return /* record */[ - /* hi */hi, - /* lo */((lo << numBits) >>> 0) - ]; - } - } -} - -function lsr_(x, numBits) { - if (numBits === 0) { - return x; - } else { - var hi = x[/* hi */0]; - var offset = numBits - 32 | 0; - if (offset === 0) { - return /* record */[ - /* hi */0, - /* lo */(hi >>> 0) - ]; - } else if (offset > 0) { - var lo = (hi >>> offset); - return /* record */[ - /* hi */0, - /* lo */(lo >>> 0) - ]; - } else { - var hi$1 = (hi >>> numBits); - var lo$1 = (hi << (-offset | 0)) | (x[/* lo */1] >>> numBits); - return /* record */[ - /* hi */hi$1, - /* lo */(lo$1 >>> 0) - ]; - } - } -} - -function asr_(x, numBits) { - if (numBits === 0) { - return x; - } else { - var hi = x[/* hi */0]; - if (numBits < 32) { - var hi$1 = (hi >> numBits); - var lo = (hi << (32 - numBits | 0)) | (x[/* lo */1] >>> numBits); - return /* record */[ - /* hi */hi$1, - /* lo */(lo >>> 0) - ]; - } else { - var lo$1 = (hi >> (numBits - 32 | 0)); - return /* record */[ - /* hi */hi >= 0 ? 0 : -1, - /* lo */(lo$1 >>> 0) - ]; - } - } -} - -function is_zero(param) { - if (param[/* hi */0] !== 0 || param[/* lo */1] !== 0) { - return /* false */0; - } else { - return /* true */1; - } -} - -function mul(_this, _other) { - while(true) { - var other = _other; - var $$this = _this; - var exit = 0; - var lo; - var this_hi = $$this[/* hi */0]; - var exit$1 = 0; - var exit$2 = 0; - var exit$3 = 0; - if (this_hi !== 0 || $$this[/* lo */1] !== 0) { - exit$3 = 4; - } else { - return zero; - } - if (exit$3 === 4) { - if (other[/* hi */0] !== 0 || other[/* lo */1] !== 0) { - exit$2 = 3; - } else { - return zero; - } - } - if (exit$2 === 3) { - if (this_hi !== -2147483648 || $$this[/* lo */1] !== 0) { - exit$1 = 2; - } else { - lo = other[/* lo */1]; - exit = 1; - } - } - if (exit$1 === 2) { - var other_hi = other[/* hi */0]; - var lo$1 = $$this[/* lo */1]; - var exit$4 = 0; - if (other_hi !== -2147483648 || other[/* lo */1] !== 0) { - exit$4 = 3; - } else { - lo = lo$1; - exit = 1; - } - if (exit$4 === 3) { - var other_lo = other[/* lo */1]; - if (this_hi < 0) { - if (other_hi < 0) { - _other = neg(other); - _this = neg($$this); - continue ; - - } else { - return neg(mul(neg($$this), other)); - } - } else if (other_hi < 0) { - return neg(mul($$this, neg(other))); - } else { - var a48 = (this_hi >>> 16); - var a32 = this_hi & 65535; - var a16 = (lo$1 >>> 16); - var a00 = lo$1 & 65535; - var b48 = (other_hi >>> 16); - var b32 = other_hi & 65535; - var b16 = (other_lo >>> 16); - var b00 = other_lo & 65535; - var c48 = 0; - var c32 = 0; - var c16 = 0; - var c00 = a00 * b00; - c16 = (c00 >>> 16) + a16 * b00; - c32 = (c16 >>> 16); - c16 = (c16 & 65535) + a00 * b16; - c32 = c32 + (c16 >>> 16) + a32 * b00; - c48 = (c32 >>> 16); - c32 = (c32 & 65535) + a16 * b16; - c48 += (c32 >>> 16); - c32 = (c32 & 65535) + a00 * b32; - c48 += (c32 >>> 16); - c32 = c32 & 65535; - c48 = c48 + (a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48) & 65535; - var hi = c32 | (c48 << 16); - var lo$2 = c00 & 65535 | ((c16 & 65535) << 16); - return /* record */[ - /* hi */hi, - /* lo */(lo$2 >>> 0) - ]; - } - } - - } - if (exit === 1) { - if ((lo & 1) === 0) { - return zero; - } else { - return min_int; - } - } - - }; -} - -function swap(param) { - var hi = __WEBPACK_IMPORTED_MODULE_0__caml_int32_js__["b" /* caml_int32_bswap */](param[/* lo */1]); - var lo = __WEBPACK_IMPORTED_MODULE_0__caml_int32_js__["b" /* caml_int32_bswap */](param[/* hi */0]); - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; -} - -function xor(param, param$1) { - return /* record */[ - /* hi */param[/* hi */0] ^ param$1[/* hi */0], - /* lo */((param[/* lo */1] ^ param$1[/* lo */1]) >>> 0) - ]; -} - -function or_(param, param$1) { - return /* record */[ - /* hi */param[/* hi */0] | param$1[/* hi */0], - /* lo */((param[/* lo */1] | param$1[/* lo */1]) >>> 0) - ]; -} - -function and_(param, param$1) { - return /* record */[ - /* hi */param[/* hi */0] & param$1[/* hi */0], - /* lo */((param[/* lo */1] & param$1[/* lo */1]) >>> 0) - ]; -} - -function ge(param, param$1) { - var other_hi = param$1[/* hi */0]; - var hi = param[/* hi */0]; - if (hi > other_hi) { - return /* true */1; - } else if (hi < other_hi) { - return /* false */0; - } else { - return +(param[/* lo */1] >= param$1[/* lo */1]); - } -} - -function neq(x, y) { - return 1 - eq(x, y); -} - -function lt(x, y) { - return 1 - ge(x, y); -} - -function gt(x, y) { - if (x[/* hi */0] > y[/* hi */0]) { - return /* true */1; - } else if (x[/* hi */0] < y[/* hi */0]) { - return /* false */0; - } else { - return +(x[/* lo */1] > y[/* lo */1]); - } -} - -function le(x, y) { - return 1 - gt(x, y); -} - -function min(x, y) { - if (ge(x, y)) { - return y; - } else { - return x; - } -} - -function max(x, y) { - if (gt(x, y)) { - return x; - } else { - return y; - } -} - -function to_float(param) { - return param[/* hi */0] * (0x100000000) + param[/* lo */1]; -} - -var two_ptr_32_dbl = Math.pow(2, 32); - -var two_ptr_63_dbl = Math.pow(2, 63); - -var neg_two_ptr_63 = -Math.pow(2, 63); - -function of_float(x) { - if (isNaN(x) || !isFinite(x)) { - return zero; - } else if (x <= neg_two_ptr_63) { - return min_int; - } else if (x + 1 >= two_ptr_63_dbl) { - return max_int; - } else if (x < 0) { - return neg(of_float(-x)); - } else { - var hi = x / two_ptr_32_dbl | 0; - var lo = x % two_ptr_32_dbl | 0; - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; - } -} - -function div(_self, _other) { - while(true) { - var other = _other; - var self = _self; - var self_hi = self[/* hi */0]; - var exit = 0; - var exit$1 = 0; - if (other[/* hi */0] !== 0 || other[/* lo */1] !== 0) { - exit$1 = 2; - } else { - throw __WEBPACK_IMPORTED_MODULE_3__caml_builtin_exceptions_js__["f" /* division_by_zero */]; - } - if (exit$1 === 2) { - if (self_hi !== -2147483648) { - if (self_hi !== 0 || self[/* lo */1] !== 0) { - exit = 1; - } else { - return zero; - } - } else if (self[/* lo */1] !== 0) { - exit = 1; - } else if (eq(other, one) || eq(other, neg_one)) { - return self; - } else if (eq(other, min_int)) { - return one; - } else { - var other_hi = other[/* hi */0]; - var half_this = asr_(self, 1); - var approx = lsl_(div(half_this, other), 1); - var exit$2 = 0; - if (approx[/* hi */0] !== 0 || approx[/* lo */1] !== 0) { - exit$2 = 3; - } else if (other_hi < 0) { - return one; - } else { - return neg(one); - } - if (exit$2 === 3) { - var y = mul(other, approx); - var rem = add(self, neg(y)); - return add(approx, div(rem, other)); - } - - } - } - if (exit === 1) { - var other_hi$1 = other[/* hi */0]; - var exit$3 = 0; - if (other_hi$1 !== -2147483648 || other[/* lo */1] !== 0) { - exit$3 = 2; - } else { - return zero; - } - if (exit$3 === 2) { - if (self_hi < 0) { - if (other_hi$1 < 0) { - _other = neg(other); - _self = neg(self); - continue ; - - } else { - return neg(div(neg(self), other)); - } - } else if (other_hi$1 < 0) { - return neg(div(self, neg(other))); - } else { - var res = zero; - var rem$1 = self; - while(ge(rem$1, other)) { - var approx$1 = __WEBPACK_IMPORTED_MODULE_2__caml_primitive_js__["c" /* caml_float_max */](1, Math.floor(to_float(rem$1) / to_float(other))); - var log2 = Math.ceil(Math.log(approx$1) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - var approxRes = of_float(approx$1); - var approxRem = mul(approxRes, other); - while(approxRem[/* hi */0] < 0 || gt(approxRem, rem$1)) { - approx$1 -= delta; - approxRes = of_float(approx$1); - approxRem = mul(approxRes, other); - }; - if (is_zero(approxRes)) { - approxRes = one; - } - res = add(res, approxRes); - rem$1 = add(rem$1, neg(approxRem)); - }; - return res; - } - } - - } - - }; -} - -function mod_(self, other) { - var y = mul(div(self, other), other); - return add(self, neg(y)); -} - -function div_mod(self, other) { - var quotient = div(self, other); - var y = mul(quotient, other); - return /* tuple */[ - quotient, - add(self, neg(y)) - ]; -} - -function compare(self, other) { - var v = __WEBPACK_IMPORTED_MODULE_2__caml_primitive_js__["d" /* caml_nativeint_compare */](self[/* hi */0], other[/* hi */0]); - if (v === 0) { - return __WEBPACK_IMPORTED_MODULE_2__caml_primitive_js__["d" /* caml_nativeint_compare */](self[/* lo */1], other[/* lo */1]); - } else { - return v; - } -} - -function of_int32(lo) { - return /* record */[ - /* hi */lo < 0 ? -1 : 0, - /* lo */(lo >>> 0) - ]; -} - -function to_int32(x) { - return x[/* lo */1] | 0; -} - -function to_hex(x) { - var aux = function (v) { - return (v >>> 0).toString(16); - }; - var match = x[/* hi */0]; - var match$1 = x[/* lo */1]; - var exit = 0; - if (match !== 0 || match$1 !== 0) { - exit = 1; - } else { - return "0"; - } - if (exit === 1) { - if (match$1 !== 0) { - if (match !== 0) { - var lo = aux(x[/* lo */1]); - var pad = 8 - lo.length | 0; - if (pad <= 0) { - return aux(x[/* hi */0]) + lo; - } else { - return aux(x[/* hi */0]) + (__WEBPACK_IMPORTED_MODULE_1__caml_utils_js__["a" /* repeat */](pad, "0") + lo); - } - } else { - return aux(x[/* lo */1]); - } - } else { - return aux(x[/* hi */0]) + "00000000"; - } - } - -} - -function discard_sign(x) { - return /* record */[ - /* hi */2147483647 & x[/* hi */0], - /* lo */x[/* lo */1] - ]; -} - -function float_of_bits(x) { - var int32 = new Int32Array(/* array */[ - x[/* lo */1], - x[/* hi */0] - ]); - return new Float64Array(int32.buffer)[0]; -} - -function bits_of_float(x) { - var u = new Float64Array(/* float array */[x]); - var int32 = new Int32Array(u.buffer); - var x$1 = int32[1]; - var hi = x$1; - var x$2 = int32[0]; - var lo = x$2; - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; -} - -function get64(s, i) { - var hi = (s.charCodeAt(i + 4 | 0) << 32) | (s.charCodeAt(i + 5 | 0) << 40) | (s.charCodeAt(i + 6 | 0) << 48) | (s.charCodeAt(i + 7 | 0) << 56); - var lo = s.charCodeAt(i) | (s.charCodeAt(i + 1 | 0) << 8) | (s.charCodeAt(i + 2 | 0) << 16) | (s.charCodeAt(i + 3 | 0) << 24); - return /* record */[ - /* hi */hi, - /* lo */(lo >>> 0) - ]; -} - - -/* two_ptr_32_dbl Not a pure module */ - - -/***/ }), -/* 45 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/* unused harmony export $caret */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return stdin; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return stdout; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stderr; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return caml_ml_open_descriptor_in; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return caml_ml_open_descriptor_out; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return caml_ml_flush; }); -/* unused harmony export node_std_output */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return caml_ml_output; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return caml_ml_output_char; }); -/* unused harmony export caml_ml_input */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return caml_ml_input_char; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return caml_ml_out_channels_list; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - -function $caret(prim, prim$1) { - return prim + prim$1; -} - -var stdout = /* record */[ - /* buffer */"", - /* output */(function (_, s) { - var v = s.length - 1 | 0; - if (( (typeof process !== "undefined") && process.stdout && process.stdout.write)) { - return ( process.stdout.write )(s); - } else if (s[v] === "\n") { - console.log(s.slice(0, v)); - return /* () */0; - } else { - console.log(s); - return /* () */0; - } - }) -]; - -var stderr = /* record */[ - /* buffer */"", - /* output */(function (_, s) { - var v = s.length - 1 | 0; - if (s[v] === "\n") { - console.log(s.slice(0, v)); - return /* () */0; - } else { - console.log(s); - return /* () */0; - } - }) -]; - -function caml_ml_open_descriptor_in() { - throw [ - __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__["b" /* failure */], - "caml_ml_open_descriptor_in not implemented" - ]; -} - -function caml_ml_open_descriptor_out() { - throw [ - __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__["b" /* failure */], - "caml_ml_open_descriptor_out not implemented" - ]; -} - -function caml_ml_flush(oc) { - if (oc[/* buffer */0] !== "") { - __WEBPACK_IMPORTED_MODULE_0__curry_js__["d" /* _2 */](oc[/* output */1], oc, oc[/* buffer */0]); - oc[/* buffer */0] = ""; - return /* () */0; - } else { - return 0; - } -} - -var node_std_output = (function (s){ - return (typeof process !== "undefined") && process.stdout && (process.stdout.write(s), true); - } -); - -function caml_ml_output(oc, str, offset, len) { - var str$1 = offset === 0 && len === str.length ? str : str.slice(offset, len); - if (( (typeof process !== "undefined") && process.stdout && process.stdout.write ) && oc === stdout) { - return ( process.stdout.write )(str$1); - } else { - var id = str$1.lastIndexOf("\n"); - if (id < 0) { - oc[/* buffer */0] = oc[/* buffer */0] + str$1; - return /* () */0; - } else { - oc[/* buffer */0] = oc[/* buffer */0] + str$1.slice(0, id + 1 | 0); - caml_ml_flush(oc); - oc[/* buffer */0] = oc[/* buffer */0] + str$1.slice(id + 1 | 0); - return /* () */0; - } - } -} - -function caml_ml_output_char(oc, $$char) { - return caml_ml_output(oc, String.fromCharCode($$char), 0, 1); -} - -function caml_ml_input(_, _$1, _$2, _$3) { - throw [ - __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__["b" /* failure */], - "caml_ml_input ic not implemented" - ]; -} - -function caml_ml_input_char() { - throw [ - __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__["b" /* failure */], - "caml_ml_input_char not implemnted" - ]; -} - -function caml_ml_out_channels_list() { - return /* :: */[ - stdout, - /* :: */[ - stderr, - /* [] */0 - ] - ]; -} - -var stdin = undefined; - - -/* node_std_output Not a pure module */ - -/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(3))) - -/***/ }), -/* 46 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return not_implemented; }); - - - -var not_implemented = (function (s){ throw new Error(s)}); - - -/* not_implemented Not a pure module */ - - -/***/ }), -/* 47 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/* unused harmony export caml_sys_getenv */ -/* unused harmony export caml_sys_time */ -/* unused harmony export caml_sys_random_seed */ -/* unused harmony export caml_sys_system_command */ -/* unused harmony export caml_sys_getcwd */ -/* unused harmony export caml_sys_get_argv */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return caml_sys_exit; }); -/* unused harmony export caml_sys_is_directory */ -/* unused harmony export caml_sys_file_exists */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - -function caml_sys_getenv(s) { - var match = typeof (process) === "undefined" ? undefined : (process); - if (match !== undefined) { - var match$1 = match.env[s]; - if (match$1 !== undefined) { - return match$1; - } else { - throw __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["c" /* not_found */]; - } - } else { - throw __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["c" /* not_found */]; - } -} - -function caml_sys_time() { - var match = typeof (process) === "undefined" ? undefined : (process); - if (match !== undefined) { - return match.uptime(); - } else { - return -1; - } -} - -function caml_sys_random_seed() { - return /* array */[((Date.now() | 0) ^ 4294967295) * Math.random() | 0]; -} - -function caml_sys_system_command() { - return 127; -} - -function caml_sys_getcwd() { - var match = typeof (process) === "undefined" ? undefined : (process); - if (match !== undefined) { - return match.cwd(); - } else { - return "/"; - } -} - -function caml_sys_get_argv() { - var match = typeof (process) === "undefined" ? undefined : (process); - if (match !== undefined) { - if (match.argv == null) { - return /* tuple */[ - "", - /* array */[""] - ]; - } else { - return /* tuple */[ - match.argv[0], - match.argv - ]; - } - } else { - return /* tuple */[ - "", - /* array */[""] - ]; - } -} - -function caml_sys_exit(exit_code) { - var match = typeof (process) === "undefined" ? undefined : (process); - if (match !== undefined) { - return match.exit(exit_code); - } else { - return /* () */0; - } -} - -function caml_sys_is_directory() { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["b" /* failure */], - "caml_sys_is_directory not implemented" - ]; -} - -function caml_sys_file_exists() { - throw [ - __WEBPACK_IMPORTED_MODULE_0__caml_builtin_exceptions_js__["b" /* failure */], - "caml_sys_file_exists not implemented" - ]; -} - - -/* No side effect */ - -/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(3))) - -/***/ }), -/* 48 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export concat_fmtty */ -/* unused harmony export erase_rel */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concat_fmt; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__block_js__ = __webpack_require__(8); - - - - -function erase_rel(param) { - if (typeof param === "number") { - return /* End_of_fmtty */0; - } else { - switch (param.tag | 0) { - case 0 : - return /* Char_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](0, [erase_rel(param[0])]); - case 1 : - return /* String_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](1, [erase_rel(param[0])]); - case 2 : - return /* Int_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](2, [erase_rel(param[0])]); - case 3 : - return /* Int32_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](3, [erase_rel(param[0])]); - case 4 : - return /* Nativeint_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](4, [erase_rel(param[0])]); - case 5 : - return /* Int64_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](5, [erase_rel(param[0])]); - case 6 : - return /* Float_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](6, [erase_rel(param[0])]); - case 7 : - return /* Bool_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](7, [erase_rel(param[0])]); - case 8 : - return /* Format_arg_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](8, [ - param[0], - erase_rel(param[1]) - ]); - case 9 : - var ty1 = param[0]; - return /* Format_subst_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](9, [ - ty1, - ty1, - erase_rel(param[2]) - ]); - case 10 : - return /* Alpha_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](10, [erase_rel(param[0])]); - case 11 : - return /* Theta_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](11, [erase_rel(param[0])]); - case 12 : - return /* Any_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](12, [erase_rel(param[0])]); - case 13 : - return /* Reader_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](13, [erase_rel(param[0])]); - case 14 : - return /* Ignored_reader_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](14, [erase_rel(param[0])]); - - } - } -} - -function concat_fmtty(fmtty1, fmtty2) { - if (typeof fmtty1 === "number") { - return fmtty2; - } else { - switch (fmtty1.tag | 0) { - case 0 : - return /* Char_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](0, [concat_fmtty(fmtty1[0], fmtty2)]); - case 1 : - return /* String_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](1, [concat_fmtty(fmtty1[0], fmtty2)]); - case 2 : - return /* Int_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](2, [concat_fmtty(fmtty1[0], fmtty2)]); - case 3 : - return /* Int32_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](3, [concat_fmtty(fmtty1[0], fmtty2)]); - case 4 : - return /* Nativeint_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](4, [concat_fmtty(fmtty1[0], fmtty2)]); - case 5 : - return /* Int64_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](5, [concat_fmtty(fmtty1[0], fmtty2)]); - case 6 : - return /* Float_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](6, [concat_fmtty(fmtty1[0], fmtty2)]); - case 7 : - return /* Bool_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](7, [concat_fmtty(fmtty1[0], fmtty2)]); - case 8 : - return /* Format_arg_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](8, [ - fmtty1[0], - concat_fmtty(fmtty1[1], fmtty2) - ]); - case 9 : - return /* Format_subst_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](9, [ - fmtty1[0], - fmtty1[1], - concat_fmtty(fmtty1[2], fmtty2) - ]); - case 10 : - return /* Alpha_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](10, [concat_fmtty(fmtty1[0], fmtty2)]); - case 11 : - return /* Theta_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](11, [concat_fmtty(fmtty1[0], fmtty2)]); - case 12 : - return /* Any_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](12, [concat_fmtty(fmtty1[0], fmtty2)]); - case 13 : - return /* Reader_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](13, [concat_fmtty(fmtty1[0], fmtty2)]); - case 14 : - return /* Ignored_reader_ty */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](14, [concat_fmtty(fmtty1[0], fmtty2)]); - - } - } -} - -function concat_fmt(fmt1, fmt2) { - if (typeof fmt1 === "number") { - return fmt2; - } else { - switch (fmt1.tag | 0) { - case 0 : - return /* Char */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](0, [concat_fmt(fmt1[0], fmt2)]); - case 1 : - return /* Caml_char */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](1, [concat_fmt(fmt1[0], fmt2)]); - case 2 : - return /* String */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](2, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 3 : - return /* Caml_string */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](3, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 4 : - return /* Int */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](4, [ - fmt1[0], - fmt1[1], - fmt1[2], - concat_fmt(fmt1[3], fmt2) - ]); - case 5 : - return /* Int32 */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](5, [ - fmt1[0], - fmt1[1], - fmt1[2], - concat_fmt(fmt1[3], fmt2) - ]); - case 6 : - return /* Nativeint */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](6, [ - fmt1[0], - fmt1[1], - fmt1[2], - concat_fmt(fmt1[3], fmt2) - ]); - case 7 : - return /* Int64 */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](7, [ - fmt1[0], - fmt1[1], - fmt1[2], - concat_fmt(fmt1[3], fmt2) - ]); - case 8 : - return /* Float */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](8, [ - fmt1[0], - fmt1[1], - fmt1[2], - concat_fmt(fmt1[3], fmt2) - ]); - case 9 : - return /* Bool */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](9, [concat_fmt(fmt1[0], fmt2)]); - case 10 : - return /* Flush */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](10, [concat_fmt(fmt1[0], fmt2)]); - case 11 : - return /* String_literal */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](11, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 12 : - return /* Char_literal */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](12, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 13 : - return /* Format_arg */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](13, [ - fmt1[0], - fmt1[1], - concat_fmt(fmt1[2], fmt2) - ]); - case 14 : - return /* Format_subst */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](14, [ - fmt1[0], - fmt1[1], - concat_fmt(fmt1[2], fmt2) - ]); - case 15 : - return /* Alpha */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](15, [concat_fmt(fmt1[0], fmt2)]); - case 16 : - return /* Theta */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](16, [concat_fmt(fmt1[0], fmt2)]); - case 17 : - return /* Formatting_lit */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](17, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 18 : - return /* Formatting_gen */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](18, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 19 : - return /* Reader */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](19, [concat_fmt(fmt1[0], fmt2)]); - case 20 : - return /* Scan_char_set */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](20, [ - fmt1[0], - fmt1[1], - concat_fmt(fmt1[2], fmt2) - ]); - case 21 : - return /* Scan_get_counter */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](21, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 22 : - return /* Scan_next_char */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](22, [concat_fmt(fmt1[0], fmt2)]); - case 23 : - return /* Ignored_param */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](23, [ - fmt1[0], - concat_fmt(fmt1[1], fmt2) - ]); - case 24 : - return /* Custom */__WEBPACK_IMPORTED_MODULE_0__block_js__["a" /* __ */](24, [ - fmt1[0], - fmt1[1], - concat_fmt(fmt1[2], fmt2) - ]); - - } - } -} - - -/* No side effect */ - - -/***/ }), -/* 49 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export chr */ -/* unused harmony export escaped */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return lowercase; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return uppercase; }); -/* unused harmony export compare */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_string_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__ = __webpack_require__(0); - - - - - -function chr(n) { - if (n < 0 || n > 255) { - throw [ - __WEBPACK_IMPORTED_MODULE_1__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "Char.chr" - ]; - } else { - return n; - } -} - -function escaped(c) { - var exit = 0; - if (c >= 40) { - if (c !== 92) { - exit = c >= 127 ? 1 : 2; - } else { - return "\\\\"; - } - } else if (c >= 32) { - if (c >= 39) { - return "\\'"; - } else { - exit = 2; - } - } else if (c >= 14) { - exit = 1; - } else { - switch (c) { - case 8 : - return "\\b"; - case 9 : - return "\\t"; - case 10 : - return "\\n"; - case 0 : - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - case 11 : - case 12 : - exit = 1; - break; - case 13 : - return "\\r"; - - } - } - switch (exit) { - case 1 : - var s = __WEBPACK_IMPORTED_MODULE_0__caml_string_js__["b" /* caml_create_string */](4); - s[0] = /* "\\" */92; - s[1] = 48 + (c / 100 | 0) | 0; - s[2] = 48 + (c / 10 | 0) % 10 | 0; - s[3] = 48 + c % 10 | 0; - return __WEBPACK_IMPORTED_MODULE_0__caml_string_js__["c" /* bytes_to_string */](s); - case 2 : - var s$1 = __WEBPACK_IMPORTED_MODULE_0__caml_string_js__["b" /* caml_create_string */](1); - s$1[0] = c; - return __WEBPACK_IMPORTED_MODULE_0__caml_string_js__["c" /* bytes_to_string */](s$1); - - } -} - -function lowercase(c) { - if (c >= /* "A" */65 && c <= /* "Z" */90 || c >= /* "\192" */192 && c <= /* "\214" */214 || c >= /* "\216" */216 && c <= /* "\222" */222) { - return c + 32 | 0; - } else { - return c; - } -} - -function uppercase(c) { - if (c >= /* "a" */97 && c <= /* "z" */122 || c >= /* "\224" */224 && c <= /* "\246" */246 || c >= /* "\248" */248 && c <= /* "\254" */254) { - return c - 32 | 0; - } else { - return c; - } -} - -function compare(c1, c2) { - return c1 - c2 | 0; -} - - -/* No side effect */ - - -/***/ }), -/* 50 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return to_js_boolean; }); - - - -function to_js_boolean(b) { - if (b) { - return true; - } else { - return false; - } -} - - -/* No side effect */ - - -/***/ }), -/* 51 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export $$Error */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return internalToOCamlException; }); -/* unused harmony export raiseError */ -/* unused harmony export raiseEvalError */ -/* unused harmony export raiseRangeError */ -/* unused harmony export raiseReferenceError */ -/* unused harmony export raiseSyntaxError */ -/* unused harmony export raiseTypeError */ -/* unused harmony export raiseUriError */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__caml_exceptions_js__ = __webpack_require__(5); - - - - -var $$Error = __WEBPACK_IMPORTED_MODULE_0__caml_exceptions_js__["a" /* create */]("Js_exn.Error"); - -function internalToOCamlException(e) { - if (__WEBPACK_IMPORTED_MODULE_0__caml_exceptions_js__["b" /* isCamlExceptionOrOpenVariant */](e)) { - return e; - } else { - return [ - $$Error, - e - ]; - } -} - -function raiseError(str) { - throw new Error(str); -} - -function raiseEvalError(str) { - throw new EvalError(str); -} - -function raiseRangeError(str) { - throw new RangeError(str); -} - -function raiseReferenceError(str) { - throw new ReferenceError(str); -} - -function raiseSyntaxError(str) { - throw new SyntaxError(str); -} - -function raiseTypeError(str) { - throw new TypeError(str); -} - -function raiseUriError(str) { - throw new URIError(str); -} - - -/* No side effect */ - - -/***/ }), -/* 52 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export some */ -/* unused harmony export isSome */ -/* unused harmony export isSomeValue */ -/* unused harmony export isNone */ -/* unused harmony export getExn */ -/* unused harmony export equal */ -/* unused harmony export andThen */ -/* unused harmony export map */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getWithDefault; }); -/* unused harmony export $$default */ -/* unused harmony export default */ -/* unused harmony export filter */ -/* unused harmony export firstSome */ - - - -function some(x) { - return /* Some */[x]; -} - -function isSome(param) { - if (param) { - return /* true */1; - } else { - return /* false */0; - } -} - -function isSomeValue(eq, v, x) { - if (x) { - return eq(v, x[0]); - } else { - return /* false */0; - } -} - -function isNone(param) { - if (param) { - return /* false */0; - } else { - return /* true */1; - } -} - -function getExn(x) { - if (x) { - return x[0]; - } else { - throw new Error("getExn"); - } -} - -function equal(eq, a, b) { - if (a) { - if (b) { - return eq(a[0], b[0]); - } else { - return /* false */0; - } - } else { - return +(b === /* None */0); - } -} - -function andThen(f, x) { - if (x) { - return f(x[0]); - } else { - return /* None */0; - } -} - -function map(f, x) { - if (x) { - return /* Some */[f(x[0])]; - } else { - return /* None */0; - } -} - -function getWithDefault(a, x) { - if (x) { - return x[0]; - } else { - return a; - } -} - -function filter(f, x) { - if (x) { - var x$1 = x[0]; - if (f(x$1)) { - return /* Some */[x$1]; - } else { - return /* None */0; - } - } else { - return /* None */0; - } -} - -function firstSome(a, b) { - if (a) { - return a; - } else if (b) { - return b; - } else { - return /* None */0; - } -} - -var $$default = getWithDefault; - - -/* No side effect */ - - -/***/ }), -/* 53 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export is_nil_undef */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return null_undefined_to_opt; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return undefined_to_opt; }); -/* unused harmony export null_to_opt */ -/* unused harmony export option_get */ -/* unused harmony export option_get_unwrap */ - - - -function is_nil_undef(x) { - if (x === null) { - return /* true */1; - } else { - return +(x === undefined); - } -} - -function null_undefined_to_opt(x) { - if (x === null || x === undefined) { - return /* None */0; - } else { - return /* Some */[x]; - } -} - -function undefined_to_opt(x) { - if (x === undefined) { - return /* None */0; - } else { - return /* Some */[x]; - } -} - -function null_to_opt(x) { - if (x === null) { - return /* None */0; - } else { - return /* Some */[x]; - } -} - -function option_get(x) { - if (x) { - return x[0]; - } else { - return undefined; - } -} - -function option_get_unwrap(x) { - if (x) { - return x[0][1]; - } else { - return undefined; - } -} - - -/* No side effect */ - - -/***/ }), -/* 54 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export test */ -/* unused harmony export testAny */ -/* unused harmony export getExn */ -/* unused harmony export bind */ -/* unused harmony export iter */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return fromOption; }); -/* unused harmony export from_opt */ - - - -function test(x) { - return +(x === undefined); -} - -function testAny(x) { - return +(x === undefined); -} - -function getExn(f) { - if (f !== undefined) { - return f; - } else { - throw new Error("Js.Undefined.getExn"); - } -} - -function bind(x, f) { - if (x !== undefined) { - return f(x); - } else { - return undefined; - } -} - -function iter(x, f) { - if (x !== undefined) { - return f(x); - } else { - return /* () */0; - } -} - -function fromOption(x) { - if (x) { - return x[0]; - } else { - return undefined; - } -} - -var from_opt = fromOption; - - -/* No side effect */ - - -/***/ }), -/* 55 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export invalid_arg */ -/* unused harmony export failwith */ -/* unused harmony export Exit */ -/* unused harmony export abs */ -/* unused harmony export max_int */ -/* unused harmony export min_int */ -/* unused harmony export lnot */ -/* unused harmony export epsilon_float */ -/* unused harmony export char_of_int */ -/* unused harmony export string_of_bool */ -/* unused harmony export bool_of_string */ -/* unused harmony export string_of_float */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return $at; }); -/* unused harmony export stdin */ -/* unused harmony export stdout */ -/* unused harmony export stderr */ -/* unused harmony export print_char */ -/* unused harmony export print_string */ -/* unused harmony export print_bytes */ -/* unused harmony export print_int */ -/* unused harmony export print_float */ -/* unused harmony export print_newline */ -/* unused harmony export prerr_char */ -/* unused harmony export prerr_string */ -/* unused harmony export prerr_bytes */ -/* unused harmony export prerr_int */ -/* unused harmony export prerr_float */ -/* unused harmony export prerr_newline */ -/* unused harmony export read_line */ -/* unused harmony export read_int */ -/* unused harmony export read_float */ -/* unused harmony export open_out */ -/* unused harmony export open_out_bin */ -/* unused harmony export open_out_gen */ -/* unused harmony export flush */ -/* unused harmony export flush_all */ -/* unused harmony export output_char */ -/* unused harmony export output_string */ -/* unused harmony export output_bytes */ -/* unused harmony export output */ -/* unused harmony export output_substring */ -/* unused harmony export output_byte */ -/* unused harmony export output_binary_int */ -/* unused harmony export output_value */ -/* unused harmony export seek_out */ -/* unused harmony export pos_out */ -/* unused harmony export out_channel_length */ -/* unused harmony export close_out */ -/* unused harmony export close_out_noerr */ -/* unused harmony export set_binary_mode_out */ -/* unused harmony export open_in */ -/* unused harmony export open_in_bin */ -/* unused harmony export open_in_gen */ -/* unused harmony export input_char */ -/* unused harmony export input_line */ -/* unused harmony export input */ -/* unused harmony export really_input */ -/* unused harmony export really_input_string */ -/* unused harmony export input_byte */ -/* unused harmony export input_binary_int */ -/* unused harmony export input_value */ -/* unused harmony export seek_in */ -/* unused harmony export pos_in */ -/* unused harmony export in_channel_length */ -/* unused harmony export close_in */ -/* unused harmony export close_in_noerr */ -/* unused harmony export set_binary_mode_in */ -/* unused harmony export LargeFile */ -/* unused harmony export string_of_format */ -/* unused harmony export $caret$caret */ -/* unused harmony export exit */ -/* unused harmony export at_exit */ -/* unused harmony export valid_float_lexem */ -/* unused harmony export unsafe_really_input */ -/* unused harmony export do_at_exit */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__curry_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__caml_io_js__ = __webpack_require__(45); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_sys_js__ = __webpack_require__(47); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_format_js__ = __webpack_require__(43); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__caml_string_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__caml_exceptions_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__ = __webpack_require__(46); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__camlinternalFormatBasics_js__ = __webpack_require__(48); - - - - - - - - - - - - -function failwith(s) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["b" /* failure */], - s - ]; -} - -function invalid_arg(s) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - s - ]; -} - -var Exit = __WEBPACK_IMPORTED_MODULE_5__caml_exceptions_js__["a" /* create */]("Pervasives.Exit"); - -function abs(x) { - if (x >= 0) { - return x; - } else { - return -x | 0; - } -} - -function lnot(x) { - return x ^ -1; -} - -var min_int = -2147483648; - -function char_of_int(n) { - if (n < 0 || n > 255) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "char_of_int" - ]; - } else { - return n; - } -} - -function string_of_bool(b) { - if (b) { - return "true"; - } else { - return "false"; - } -} - -function bool_of_string(param) { - switch (param) { - case "false" : - return /* false */0; - case "true" : - return /* true */1; - default: - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "bool_of_string" - ]; - } -} - -function valid_float_lexem(s) { - var l = s.length; - var _i = 0; - while(true) { - var i = _i; - if (i >= l) { - return s + "."; - } else { - var match = __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["a" /* get */](s, i); - if (match >= 48) { - if (match >= 58) { - return s; - } else { - _i = i + 1 | 0; - continue ; - - } - } else if (match !== 45) { - return s; - } else { - _i = i + 1 | 0; - continue ; - - } - } - }; -} - -function string_of_float(f) { - return valid_float_lexem(__WEBPACK_IMPORTED_MODULE_3__caml_format_js__["a" /* caml_format_float */]("%.12g", f)); -} - -function $at(l1, l2) { - if (l1) { - return /* :: */[ - l1[0], - $at(l1[1], l2) - ]; - } else { - return l2; - } -} - -var stdin = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["a" /* stdin */]; - -var stdout = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["b" /* stdout */]; - -var stderr = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["c" /* stderr */]; - -function open_out_gen(_, _$1, _$2) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["d" /* caml_ml_open_descriptor_out */](__WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_sys_open not implemented by bucklescript yet\n")); -} - -function open_out(name) { - return open_out_gen(/* :: */[ - /* Open_wronly */1, - /* :: */[ - /* Open_creat */3, - /* :: */[ - /* Open_trunc */4, - /* :: */[ - /* Open_text */7, - /* [] */0 - ] - ] - ] - ], 438, name); -} - -function open_out_bin(name) { - return open_out_gen(/* :: */[ - /* Open_wronly */1, - /* :: */[ - /* Open_creat */3, - /* :: */[ - /* Open_trunc */4, - /* :: */[ - /* Open_binary */6, - /* [] */0 - ] - ] - ] - ], 438, name); -} - -function flush_all() { - var _param = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["e" /* caml_ml_out_channels_list */](/* () */0); - while(true) { - var param = _param; - if (param) { - try { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](param[0]); - } - catch (exn){ - - } - _param = param[1]; - continue ; - - } else { - return /* () */0; - } - }; -} - -function output_bytes(oc, s) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["g" /* caml_ml_output */](oc, s, 0, s.length); -} - -function output_string(oc, s) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["g" /* caml_ml_output */](oc, s, 0, s.length); -} - -function output(oc, s, ofs, len) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "output" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["g" /* caml_ml_output */](oc, s, ofs, len); - } -} - -function output_substring(oc, s, ofs, len) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "output_substring" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["g" /* caml_ml_output */](oc, s, ofs, len); - } -} - -function output_value(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_output_value not implemented by bucklescript yet\n"); -} - -function close_out(oc) { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](oc); - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_close_channel not implemented by bucklescript yet\n"); -} - -function close_out_noerr(oc) { - try { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](oc); - } - catch (exn){ - - } - try { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_close_channel not implemented by bucklescript yet\n"); - } - catch (exn$1){ - return /* () */0; - } -} - -function open_in_gen(_, _$1, _$2) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["h" /* caml_ml_open_descriptor_in */](__WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_sys_open not implemented by bucklescript yet\n")); -} - -function open_in(name) { - return open_in_gen(/* :: */[ - /* Open_rdonly */0, - /* :: */[ - /* Open_text */7, - /* [] */0 - ] - ], 0, name); -} - -function open_in_bin(name) { - return open_in_gen(/* :: */[ - /* Open_rdonly */0, - /* :: */[ - /* Open_binary */6, - /* [] */0 - ] - ], 0, name); -} - -function input(_, s, ofs, len) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "input" - ]; - } else { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input not implemented by bucklescript yet\n"); - } -} - -function unsafe_really_input(_, _$1, _ofs, _len) { - while(true) { - var len = _len; - var ofs = _ofs; - if (len <= 0) { - return /* () */0; - } else { - var r = __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input not implemented by bucklescript yet\n"); - if (r === 0) { - throw __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["e" /* end_of_file */]; - } else { - _len = len - r | 0; - _ofs = ofs + r | 0; - continue ; - - } - } - }; -} - -function really_input(ic, s, ofs, len) { - if (ofs < 0 || len < 0 || ofs > (s.length - len | 0)) { - throw [ - __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["a" /* invalid_argument */], - "really_input" - ]; - } else { - return unsafe_really_input(ic, s, ofs, len); - } -} - -function really_input_string(ic, len) { - var s = __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["b" /* caml_create_string */](len); - really_input(ic, s, 0, len); - return __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["c" /* bytes_to_string */](s); -} - -function input_line(chan) { - var build_result = function (buf, _pos, _param) { - while(true) { - var param = _param; - var pos = _pos; - if (param) { - var hd = param[0]; - var len = hd.length; - __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["d" /* caml_blit_bytes */](hd, 0, buf, pos - len | 0, len); - _param = param[1]; - _pos = pos - len | 0; - continue ; - - } else { - return buf; - } - }; - }; - var scan = function (_accu, _len) { - while(true) { - var len = _len; - var accu = _accu; - var n = __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input_scan_line not implemented by bucklescript yet\n"); - if (n === 0) { - if (accu) { - return build_result(__WEBPACK_IMPORTED_MODULE_4__caml_string_js__["b" /* caml_create_string */](len), len, accu); - } else { - throw __WEBPACK_IMPORTED_MODULE_7__caml_builtin_exceptions_js__["e" /* end_of_file */]; - } - } else if (n > 0) { - var res = __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["b" /* caml_create_string */](n - 1 | 0); - __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input not implemented by bucklescript yet\n"); - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["i" /* caml_ml_input_char */](chan); - if (accu) { - var len$1 = (len + n | 0) - 1 | 0; - return build_result(__WEBPACK_IMPORTED_MODULE_4__caml_string_js__["b" /* caml_create_string */](len$1), len$1, /* :: */[ - res, - accu - ]); - } else { - return res; - } - } else { - var beg = __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["b" /* caml_create_string */](-n | 0); - __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input not implemented by bucklescript yet\n"); - _len = len - n | 0; - _accu = /* :: */[ - beg, - accu - ]; - continue ; - - } - }; - }; - return __WEBPACK_IMPORTED_MODULE_4__caml_string_js__["c" /* bytes_to_string */](scan(/* [] */0, 0)); -} - -function close_in_noerr() { - try { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_close_channel not implemented by bucklescript yet\n"); - } - catch (exn){ - return /* () */0; - } -} - -function print_char(c) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */](stdout, c); -} - -function print_string(s) { - return output_string(stdout, s); -} - -function print_bytes(s) { - return output_bytes(stdout, s); -} - -function print_int(i) { - return output_string(stdout, String(i)); -} - -function print_float(f) { - return output_string(stdout, valid_float_lexem(__WEBPACK_IMPORTED_MODULE_3__caml_format_js__["a" /* caml_format_float */]("%.12g", f))); -} - -function print_newline() { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */](stdout, /* "\n" */10); - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](stdout); -} - -function prerr_char(c) { - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */](stderr, c); -} - -function prerr_string(s) { - return output_string(stderr, s); -} - -function prerr_bytes(s) { - return output_bytes(stderr, s); -} - -function prerr_int(i) { - return output_string(stderr, String(i)); -} - -function prerr_float(f) { - return output_string(stderr, valid_float_lexem(__WEBPACK_IMPORTED_MODULE_3__caml_format_js__["a" /* caml_format_float */]("%.12g", f))); -} - -function prerr_newline() { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */](stderr, /* "\n" */10); - return __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](stderr); -} - -function read_line() { - __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](stdout); - return input_line(stdin); -} - -function read_int() { - return __WEBPACK_IMPORTED_MODULE_3__caml_format_js__["b" /* caml_int_of_string */]((__WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](stdout), input_line(stdin))); -} - -function read_float() { - return __WEBPACK_IMPORTED_MODULE_3__caml_format_js__["c" /* caml_float_of_string */]((__WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */](stdout), input_line(stdin))); -} - -function string_of_format(param) { - return param[1]; -} - -function $caret$caret(param, param$1) { - return /* Format */[ - __WEBPACK_IMPORTED_MODULE_8__camlinternalFormatBasics_js__["a" /* concat_fmt */](param[0], param$1[0]), - param[1] + ("%," + param$1[1]) - ]; -} - -var exit_function = [flush_all]; - -function at_exit(f) { - var g = exit_function[0]; - exit_function[0] = (function () { - __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](f, /* () */0); - return __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](g, /* () */0); - }); - return /* () */0; -} - -function do_at_exit() { - return __WEBPACK_IMPORTED_MODULE_0__curry_js__["b" /* _1 */](exit_function[0], /* () */0); -} - -function exit(retcode) { - do_at_exit(/* () */0); - return __WEBPACK_IMPORTED_MODULE_2__caml_sys_js__["a" /* caml_sys_exit */](retcode); -} - -var max_int = 2147483647; - -var epsilon_float = 2.220446049250313e-16; - -var flush = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["f" /* caml_ml_flush */]; - -var output_char = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */]; - -var output_byte = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["j" /* caml_ml_output_char */]; - -function output_binary_int(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_output_int not implemented by bucklescript yet\n"); -} - -function seek_out(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_seek_out not implemented by bucklescript yet\n"); -} - -function pos_out() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_pos_out not implemented by bucklescript yet\n"); -} - -function out_channel_length() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_channel_size not implemented by bucklescript yet\n"); -} - -function set_binary_mode_out(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_set_binary_mode not implemented by bucklescript yet\n"); -} - -var input_char = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["i" /* caml_ml_input_char */]; - -var input_byte = __WEBPACK_IMPORTED_MODULE_1__caml_io_js__["i" /* caml_ml_input_char */]; - -function input_binary_int() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_input_int not implemented by bucklescript yet\n"); -} - -function input_value() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_input_value not implemented by bucklescript yet\n"); -} - -function seek_in(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_seek_in not implemented by bucklescript yet\n"); -} - -function pos_in() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_pos_in not implemented by bucklescript yet\n"); -} - -function in_channel_length() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_channel_size not implemented by bucklescript yet\n"); -} - -function close_in() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_close_channel not implemented by bucklescript yet\n"); -} - -function set_binary_mode_in(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_set_binary_mode not implemented by bucklescript yet\n"); -} - -function LargeFile_000(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_seek_out_64 not implemented by bucklescript yet\n"); -} - -function LargeFile_001() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_pos_out_64 not implemented by bucklescript yet\n"); -} - -function LargeFile_002() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_channel_size_64 not implemented by bucklescript yet\n"); -} - -function LargeFile_003(_, _$1) { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_seek_in_64 not implemented by bucklescript yet\n"); -} - -function LargeFile_004() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_pos_in_64 not implemented by bucklescript yet\n"); -} - -function LargeFile_005() { - return __WEBPACK_IMPORTED_MODULE_6__caml_missing_polyfill_js__["a" /* not_implemented */]("caml_ml_channel_size_64 not implemented by bucklescript yet\n"); -} - -var LargeFile = [ - LargeFile_000, - LargeFile_001, - LargeFile_002, - LargeFile_003, - LargeFile_004, - LargeFile_005 -]; - - -/* No side effect */ - - -/***/ }), -/* 56 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export make */ -/* unused harmony export init */ -/* unused harmony export copy */ -/* unused harmony export sub */ -/* unused harmony export fill */ -/* unused harmony export blit */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concat; }); -/* unused harmony export iter */ -/* unused harmony export iteri */ -/* unused harmony export map */ -/* unused harmony export mapi */ -/* unused harmony export trim */ -/* unused harmony export escaped */ -/* unused harmony export index */ -/* unused harmony export rindex */ -/* unused harmony export index_from */ -/* unused harmony export rindex_from */ -/* unused harmony export contains */ -/* unused harmony export contains_from */ -/* unused harmony export rcontains_from */ -/* unused harmony export uppercase */ -/* unused harmony export lowercase */ -/* unused harmony export capitalize */ -/* unused harmony export uncapitalize */ -/* unused harmony export compare */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__list_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__bytes_js__ = __webpack_require__(42); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__caml_int32_js__ = __webpack_require__(9); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__caml_string_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__caml_primitive_js__ = __webpack_require__(10); - - - - - - - - -function make(n, c) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["a" /* make */](n, c)); -} - -function init(n, f) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["b" /* init */](n, f)); -} - -function copy(s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["c" /* copy */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function sub(s, ofs, len) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["d" /* sub */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), ofs, len)); -} - -function concat(sep, l) { - if (l) { - var hd = l[0]; - var num = [0]; - var len = [0]; - __WEBPACK_IMPORTED_MODULE_0__list_js__["b" /* iter */]((function (s) { - num[0] = num[0] + 1 | 0; - len[0] = len[0] + s.length | 0; - return /* () */0; - }), l); - var r = __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["b" /* caml_create_string */](len[0] + __WEBPACK_IMPORTED_MODULE_2__caml_int32_js__["a" /* imul */](sep.length, num[0] - 1 | 0) | 0); - __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["f" /* caml_blit_string */](hd, 0, r, 0, hd.length); - var pos = [hd.length]; - __WEBPACK_IMPORTED_MODULE_0__list_js__["b" /* iter */]((function (s) { - __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["f" /* caml_blit_string */](sep, 0, r, pos[0], sep.length); - pos[0] = pos[0] + sep.length | 0; - __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["f" /* caml_blit_string */](s, 0, r, pos[0], s.length); - pos[0] = pos[0] + s.length | 0; - return /* () */0; - }), l[1]); - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](r); - } else { - return ""; - } -} - -function iter(f, s) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["e" /* iter */](f, __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s)); -} - -function iteri(f, s) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["f" /* iteri */](f, __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s)); -} - -function map(f, s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["g" /* map */](f, __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function mapi(f, s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["h" /* mapi */](f, __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function is_space(param) { - var switcher = param - 9 | 0; - if (switcher > 4 || switcher < 0) { - if (switcher !== 23) { - return /* false */0; - } else { - return /* true */1; - } - } else if (switcher !== 2) { - return /* true */1; - } else { - return /* false */0; - } -} - -function trim(s) { - if (s === "" || !(is_space(s.charCodeAt(0)) || is_space(s.charCodeAt(s.length - 1 | 0)))) { - return s; - } else { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["i" /* trim */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); - } -} - -function escaped(s) { - var needs_escape = function (_i) { - while(true) { - var i = _i; - if (i >= s.length) { - return /* false */0; - } else { - var match = s.charCodeAt(i); - if (match >= 32) { - var switcher = match - 34 | 0; - if (switcher > 58 || switcher < 0) { - if (switcher >= 93) { - return /* true */1; - } else { - _i = i + 1 | 0; - continue ; - - } - } else if (switcher > 57 || switcher < 1) { - return /* true */1; - } else { - _i = i + 1 | 0; - continue ; - - } - } else { - return /* true */1; - } - } - }; - }; - if (needs_escape(0)) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["j" /* escaped */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); - } else { - return s; - } -} - -function index(s, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["k" /* index */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), c); -} - -function rindex(s, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["l" /* rindex */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), c); -} - -function index_from(s, i, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["m" /* index_from */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), i, c); -} - -function rindex_from(s, i, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["n" /* rindex_from */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), i, c); -} - -function contains(s, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["o" /* contains */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), c); -} - -function contains_from(s, i, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["p" /* contains_from */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), i, c); -} - -function rcontains_from(s, i, c) { - return __WEBPACK_IMPORTED_MODULE_1__bytes_js__["q" /* rcontains_from */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s), i, c); -} - -function uppercase(s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["r" /* uppercase */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function lowercase(s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["s" /* lowercase */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function capitalize(s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["t" /* capitalize */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -function uncapitalize(s) { - return __WEBPACK_IMPORTED_MODULE_3__caml_string_js__["c" /* bytes_to_string */](__WEBPACK_IMPORTED_MODULE_1__bytes_js__["u" /* uncapitalize */](__WEBPACK_IMPORTED_MODULE_3__caml_string_js__["e" /* bytes_of_string */](s))); -} - -var compare = __WEBPACK_IMPORTED_MODULE_4__caml_primitive_js__["a" /* caml_string_compare */]; - -var fill = __WEBPACK_IMPORTED_MODULE_1__bytes_js__["v" /* fill */]; - -var blit = __WEBPACK_IMPORTED_MODULE_1__bytes_js__["w" /* blit_string */]; - - -/* No side effect */ - - -/***/ }), -/* 57 */ -/***/ (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__(15)); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -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]/; - - // Tokenizer - - var keywords = function(){ - function kw(type) {return {type: type, style: "keyword"};} - var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); - var operator = kw("operator"), atom = {type: "atom", style: "atom"}; - - return { - "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, - "debugger": kw("debugger"), "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 - }; - }(); - - 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 == "\\"; - } - } - - // 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.eat("="); - 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 != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("=") - } else if (/[<>*+\-]/.test(ch)) { - stream.eat(ch) - if (ch == ">") stream.eat(ch) - } - } - 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) - } - if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) - return ret("async", "keyword", word) - } - return ret("variable", "variable", word) - } - } - - 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"); - } - - function tokenQuasi(stream, state) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - - 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; - - 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 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; - } - - // Parser - - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; - - 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; - } - - 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; - } - } - - 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; - - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = true; - - 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; - } - } - } - - // Combinator utils - - 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 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}; - } - } - - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" - } - - // Combinators - - 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 expect(wanted) { - function exp(type) { - if (type == wanted) return cont(); - else if (wanted == ";") return pass(); - else return cont(exp); - }; - return exp; - } - - 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 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type == "debugger") return cont(expect(";")); - 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); - } - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); - if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); } - if (type == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword" - return cont(statement) - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword" - if (value == "enum") return cont(enumdef); - else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";")); - else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) - } else if (isTS && value == "namespace") { - cx.marked = "keyword" - return cont(pushlex("form"), expression, block, poplex) - } else if (isTS && value == "abstract") { - cx.marked = "keyword" - return cont(statement) - } else { - return cont(pushlex("stat"), maybelabel); - } - } - 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 == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type == "async") return cont(statement) - if (value == "@") return cont(expression, statement) - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function expression(type, value) { - return expressionInner(type, value, false); - } - function expressionNoComma(type, value) { - return expressionInner(type, value, true); - } - function parenExpr(type) { - if (type != "(") return pass() - return cont(pushlex(")"), expression, expect(")"), poplex) - } - function expressionInner(type, value, 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); - } - - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef, maybeop); - if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } - if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); - 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)); - if (type == "import") return cont(expression); - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - - 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 (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) - return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, 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); - 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) - } - } - 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 if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) - 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); - 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 (isTS && isModifier(value)) { - cx.marked = "keyword" - return cont(objprop) - } else if (type == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } 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 mayberettype(type) { - if (isTS && type == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) - else return cont(typeexpr) - } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword" - return cont() - } - } - function typeexpr(type, value) { - if (value == "keyof" || value == "typeof") { - cx.marked = "keyword" - return cont(value == "keyof" ? typeexpr : expressionNoComma) - } - if (type == "variable" || value == "void") { - cx.marked = "type" - return cont(afterType) - } - 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) - if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) - } - 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) - } else if (type == "[") { - return cont(expression, maybetype, expect("]"), typeprop) - } - } - function typearg(type, value) { - if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) - if (type == ":") return cont(typeexpr) - return pass(typeexpr) - } - function afterType(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - if (value == "|" || type == "." || value == "&") return cont(typeexpr) - if (type == "[") return cont(expect("]"), afterType) - if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault) - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr) - } - function vardef(_, value) { - if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type, value) { - if (isTS && isModifier(value)) { cx.marked = "keyword"; 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, value) { - if (value == "await") return cont(forspec); - 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, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) - } - function funarg(type, value) { - if (value == "@") cont(expression, funarg) - if (type == "spread") return cont(funarg); - if (isTS && isModifier(value)) { cx.marked = "keyword"; 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(typeparam, ">"), poplex, classNameAfter) - if (value == "extends" || value == "implements" || (isTS && type == ",")) { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type, value) { - if (type == "async" || - (type == "variable" && - (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && - 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, maybetype, 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(); - if (type == "(") return pass(expression); - 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 enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) - } - function enummember() { - return pass(pattern, maybeAssign); - } - - 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 [bcd]|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(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 : "*/", - blockCommentContinue: 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 }); - -}); - - -/***/ }), -/* 58 */ -/***/ (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__(15)); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode('mllike', function(_config, parserConfig) { - var words = { - 'as': 'keyword', - 'do': 'keyword', - 'else': 'keyword', - 'end': 'keyword', - 'exception': 'keyword', - 'fun': 'keyword', - 'functor': 'keyword', - 'if': 'keyword', - 'in': 'keyword', - 'include': 'keyword', - 'let': 'keyword', - 'of': 'keyword', - 'open': 'keyword', - 'rec': 'keyword', - 'struct': 'keyword', - 'then': 'keyword', - 'type': 'keyword', - 'val': 'keyword', - 'while': 'keyword', - 'with': 'keyword' - }; - - var extraWords = parserConfig.extraWords || {}; - for (var prop in extraWords) { - if (extraWords.hasOwnProperty(prop)) { - words[prop] = parserConfig.extraWords[prop]; - } - } - - function tokenBase(stream, state) { - var ch = stream.next(); - - if (ch === '"') { - state.tokenize = tokenString; - return state.tokenize(stream, state); - } - if (ch === '{') { - if (stream.eat('|')) { - state.longString = true; - state.tokenize = tokenLongString; - return state.tokenize(stream, state); - } - } - if (ch === '(') { - if (stream.eat('*')) { - state.commentLevel++; - state.tokenize = tokenComment; - return state.tokenize(stream, state); - } - } - if (ch === '~' || ch === '?') { - stream.eatWhile(/\w/); - return 'variable-2'; - } - if (ch === '`') { - stream.eatWhile(/\w/); - return 'quote'; - } - if (ch === '/' && parserConfig.slashComments && stream.eat('/')) { - stream.skipToEnd(); - return 'comment'; - } - if (/\d/.test(ch)) { - if (ch === '0' && stream.eat(/[bB]/)) { - stream.eatWhile(/[01]/); - } if (ch === '0' && stream.eat(/[xX]/)) { - stream.eatWhile(/[0-9a-fA-F]/) - } if (ch === '0' && stream.eat(/[oO]/)) { - stream.eatWhile(/[0-7]/); - } else { - stream.eatWhile(/[\d_]/); - if (stream.eat('.')) { - stream.eatWhile(/[\d]/); - } - if (stream.eat(/[eE]/)) { - stream.eatWhile(/[\d\-+]/); - } - } - return 'number'; - } - if ( /[+\-*&%=<>!?|@\.~:]/.test(ch)) { - return 'operator'; - } - if (/[\w\xa1-\uffff]/.test(ch)) { - stream.eatWhile(/[\w\xa1-\uffff]/); - var cur = stream.current(); - return words.hasOwnProperty(cur) ? words[cur] : 'variable'; - } - return null - } - - function tokenString(stream, state) { - var next, end = false, escaped = false; - while ((next = stream.next()) != null) { - if (next === '"' && !escaped) { - end = true; - break; - } - escaped = !escaped && next === '\\'; - } - if (end && !escaped) { - state.tokenize = tokenBase; - } - return 'string'; - }; - - function tokenComment(stream, state) { - var prev, next; - while(state.commentLevel > 0 && (next = stream.next()) != null) { - if (prev === '(' && next === '*') state.commentLevel++; - if (prev === '*' && next === ')') state.commentLevel--; - prev = next; - } - if (state.commentLevel <= 0) { - state.tokenize = tokenBase; - } - return 'comment'; - } - - function tokenLongString(stream, state) { - var prev, next; - while (state.longString && (next = stream.next()) != null) { - if (prev === '|' && next === '}') state.longString = false; - prev = next; - } - if (!state.longString) { - state.tokenize = tokenBase; - } - return 'string'; - } - - return { - startState: function() {return {tokenize: tokenBase, commentLevel: 0, longString: false};}, - token: function(stream, state) { - if (stream.eatSpace()) return null; - return state.tokenize(stream, state); - }, - - blockCommentStart: "(*", - blockCommentEnd: "*)", - lineComment: parserConfig.slashComments ? "//" : null - }; -}); - -CodeMirror.defineMIME('text/x-ocaml', { - name: 'mllike', - extraWords: { - 'and': 'keyword', - 'assert': 'keyword', - 'begin': 'keyword', - 'class': 'keyword', - 'constraint': 'keyword', - 'done': 'keyword', - 'downto': 'keyword', - 'external': 'keyword', - 'function': 'keyword', - 'initializer': 'keyword', - 'lazy': 'keyword', - 'match': 'keyword', - 'method': 'keyword', - 'module': 'keyword', - 'mutable': 'keyword', - 'new': 'keyword', - 'nonrec': 'keyword', - 'object': 'keyword', - 'private': 'keyword', - 'sig': 'keyword', - 'to': 'keyword', - 'try': 'keyword', - 'value': 'keyword', - 'virtual': 'keyword', - 'when': 'keyword', - - // builtins - 'raise': 'builtin', - 'failwith': 'builtin', - 'true': 'builtin', - 'false': 'builtin', - - // Pervasives builtins - 'asr': 'builtin', - 'land': 'builtin', - 'lor': 'builtin', - 'lsl': 'builtin', - 'lsr': 'builtin', - 'lxor': 'builtin', - 'mod': 'builtin', - 'or': 'builtin', - - // More Pervasives - 'raise_notrace': 'builtin', - 'trace': 'builtin', - 'exit': 'builtin', - 'print_string': 'builtin', - 'print_endline': 'builtin', - - 'int': 'type', - 'float': 'type', - 'bool': 'type', - 'char': 'type', - 'string': 'type', - 'unit': 'type', - - // Modules - 'List': 'builtin' - } -}); - -CodeMirror.defineMIME('text/x-fsharp', { - name: 'mllike', - extraWords: { - 'abstract': 'keyword', - 'assert': 'keyword', - 'base': 'keyword', - 'begin': 'keyword', - 'class': 'keyword', - 'default': 'keyword', - 'delegate': 'keyword', - 'do!': 'keyword', - 'done': 'keyword', - 'downcast': 'keyword', - 'downto': 'keyword', - 'elif': 'keyword', - 'extern': 'keyword', - 'finally': 'keyword', - 'for': 'keyword', - 'function': 'keyword', - 'global': 'keyword', - 'inherit': 'keyword', - 'inline': 'keyword', - 'interface': 'keyword', - 'internal': 'keyword', - 'lazy': 'keyword', - 'let!': 'keyword', - 'match': 'keyword', - 'member': 'keyword', - 'module': 'keyword', - 'mutable': 'keyword', - 'namespace': 'keyword', - 'new': 'keyword', - 'null': 'keyword', - 'override': 'keyword', - 'private': 'keyword', - 'public': 'keyword', - 'return!': 'keyword', - 'return': 'keyword', - 'select': 'keyword', - 'static': 'keyword', - 'to': 'keyword', - 'try': 'keyword', - 'upcast': 'keyword', - 'use!': 'keyword', - 'use': 'keyword', - 'void': 'keyword', - 'when': 'keyword', - 'yield!': 'keyword', - 'yield': 'keyword', - - // Reserved words - 'atomic': 'keyword', - 'break': 'keyword', - 'checked': 'keyword', - 'component': 'keyword', - 'const': 'keyword', - 'constraint': 'keyword', - 'constructor': 'keyword', - 'continue': 'keyword', - 'eager': 'keyword', - 'event': 'keyword', - 'external': 'keyword', - 'fixed': 'keyword', - 'method': 'keyword', - 'mixin': 'keyword', - 'object': 'keyword', - 'parallel': 'keyword', - 'process': 'keyword', - 'protected': 'keyword', - 'pure': 'keyword', - 'sealed': 'keyword', - 'tailcall': 'keyword', - 'trait': 'keyword', - 'virtual': 'keyword', - 'volatile': 'keyword', - - // builtins - 'List': 'builtin', - 'Seq': 'builtin', - 'Map': 'builtin', - 'Set': 'builtin', - 'Option': 'builtin', - 'int': 'builtin', - 'string': 'builtin', - 'not': 'builtin', - 'true': 'builtin', - 'false': 'builtin', - - 'raise': 'builtin', - 'failwith': 'builtin' - }, - slashComments: true -}); - - -CodeMirror.defineMIME('text/x-sml', { - name: 'mllike', - extraWords: { - 'abstype': 'keyword', - 'and': 'keyword', - 'andalso': 'keyword', - 'case': 'keyword', - 'datatype': 'keyword', - 'fn': 'keyword', - 'handle': 'keyword', - 'infix': 'keyword', - 'infixr': 'keyword', - 'local': 'keyword', - 'nonfix': 'keyword', - 'op': 'keyword', - 'orelse': 'keyword', - 'raise': 'keyword', - 'withtype': 'keyword', - 'eqtype': 'keyword', - 'sharing': 'keyword', - 'sig': 'keyword', - 'signature': 'keyword', - 'structure': 'keyword', - 'where': 'keyword', - 'true': 'keyword', - 'false': 'keyword', - - // types - 'int': 'builtin', - 'real': 'builtin', - 'string': 'builtin', - 'char': 'builtin', - 'bool': 'builtin' - }, - slashComments: true -}); - -}); - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var deselectCurrent = __webpack_require__(86); - -var defaultMessage = 'Copy to clipboard: #{key}, Enter'; - -function format(message) { - var copyKey = (/mac os x/i.test(navigator.userAgent) ? '⌘' : 'Ctrl') + '+C'; - return message.replace(/#{\s*key\s*}/g, copyKey); -} - -function copy(text, options) { - var debug, message, reselectPrevious, range, selection, mark, success = false; - if (!options) { options = {}; } - debug = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - - range = document.createRange(); - selection = document.getSelection(); - - mark = document.createElement('span'); - mark.textContent = text; - // reset user styles for span element - mark.style.all = 'unset'; - // prevents scrolling to the end of the page - mark.style.position = 'fixed'; - mark.style.top = 0; - mark.style.clip = 'rect(0, 0, 0, 0)'; - // used to preserve spaces and line breaks - mark.style.whiteSpace = 'pre'; - // do not inherit user-select (it may be `none`) - mark.style.webkitUserSelect = 'text'; - mark.style.MozUserSelect = 'text'; - mark.style.msUserSelect = 'text'; - mark.style.userSelect = 'text'; - - document.body.appendChild(mark); - - range.selectNode(mark); - selection.addRange(range); - - var successful = document.execCommand('copy'); - if (!successful) { - throw new Error('copy command was unsuccessful'); - } - success = true; - } catch (err) { - debug && console.error('unable to copy using execCommand: ', err); - debug && console.warn('trying IE specific stuff'); - try { - window.clipboardData.setData('text', text); - success = true; - } catch (err) { - debug && console.error('unable to copy using clipboardData: ', err); - debug && console.error('falling back to prompt'); - message = format('message' in options ? options.message : defaultMessage); - window.prompt(message, text); - } - } finally { - if (selection) { - if (typeof selection.removeRange == 'function') { - selection.removeRange(range); - } else { - selection.removeAllRanges(); - } - } - - if (mark) { - document.body.removeChild(mark); - } - reselectPrevious(); - } - - return success; -} - -module.exports = copy; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 _hyphenPattern = /-(.)/g; - -/** - * Camelcases a hyphenated string, for example: - * - * > camelize('background-color') - * < "backgroundColor" - * - * @param {string} string - * @return {string} - */ -function camelize(string) { - return string.replace(_hyphenPattern, function (_, character) { - return character.toUpperCase(); - }); -} - -module.exports = camelize; - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 camelize = __webpack_require__(60); - -var msPattern = /^-ms-/; - -/** - * Camelcases a hyphenated CSS property name, for example: - * - * > camelizeStyleName('background-color') - * < "backgroundColor" - * > camelizeStyleName('-moz-transition') - * < "MozTransition" - * > camelizeStyleName('-ms-transition') - * < "msTransition" - * - * As Andi Smith suggests - * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix - * is converted to lowercase `ms`. - * - * @param {string} string - * @return {string} - */ -function camelizeStyleName(string) { - return camelize(string.replace(msPattern, 'ms-')); -} - -module.exports = camelizeStyleName; - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -"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; - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 hyphenate = __webpack_require__(62); - -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; - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 - */ - -/** - * @param {*} object The object to check. - * @return {boolean} Whether or not the object is a DOM node. - */ -function isNode(object) { - var doc = object ? object.ownerDocument || object : document; - var defaultView = doc.defaultView || window; - return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); -} - -module.exports = isNode; - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"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 isNode = __webpack_require__(64); - -/** - * @param {*} object The object to check. - * @return {boolean} Whether or not the object is a DOM text node. - */ -function isTextNode(object) { - return isNode(object) && object.nodeType == 3; -} - -module.exports = isTextNode; - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "codemirror.css"; - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "ocamlDoc.css"; - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "oceanic-next.css"; - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "logo128.png"; - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "logo19.png"; - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "logo19_gray.png"; - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "logo38.png"; - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "logo38_gray.png"; - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__.p + "popup.html"; - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -"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. - */ - - - -var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; - -module.exports = ReactPropTypesSecret; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { - -var _extends = Object.assign || function(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; -}; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { - return typeof obj; -} : function(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; - -var __extends = undefined && undefined.__extends || function() { - var extendStatics = Object.setPrototypeOf || { - __proto__: [] - } - instanceof Array && function(d, b) { - d.__proto__ = b; - } || function(d, b) { - for (var p in b) { - if (b.hasOwnProperty(p)) d[p] = b[p]; - } - }; - return function(d, b) { - extendStatics(d, b); - - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -}(); -Object.defineProperty(exports, '__esModule', { - value: true -}); -var React = __webpack_require__(2); -var SERVER_RENDERED = typeof navigator === 'undefined' || global['PREVENT_CODEMIRROR_RENDER'] === true; -var cm; -if (!SERVER_RENDERED) { - cm = __webpack_require__(15); -} -var Helper = function() { - function Helper() {} - Helper.equals = function(x, y) { - var _this = this; - var ok = Object.keys, - tx = typeof x === 'undefined' ? 'undefined' : _typeof(x), - ty = typeof y === 'undefined' ? 'undefined' : _typeof(y); - return x && y && tx === 'object' && tx === ty ? ok(x).length === ok(y).length && ok(x).every(function(key) { - return _this.equals(x[key], y[key]); - }) : x === y; - }; - return Helper; -}(); -var Shared = function() { - function Shared(editor, props) { - this.editor = editor; - this.props = props; - } - Shared.prototype.delegateCursor = function(position, scroll, focus) { - var doc = this.editor.getDoc(); - if (focus) { - this.editor.focus(); - } - scroll ? doc.setCursor(position) : doc.setCursor(position, null, { - scroll: false - }); - }; - Shared.prototype.delegateScroll = function(coordinates) { - this.editor.scrollTo(coordinates.x, coordinates.y); - }; - Shared.prototype.delegateSelection = function(ranges, focus) { - this.editor.setSelections(ranges); - if (focus) { - this.editor.focus(); - } - }; - Shared.prototype.apply = function(props) { - if (props && props.selection && props.selection.ranges) { - this.delegateSelection(props.selection.ranges, props.selection.focus || false); - } - if (props && props.cursor) { - this.delegateCursor(props.cursor, props.autoScroll || false, props.autoFocus || false); - } - if (props && props.scroll) { - this.delegateScroll(props.scroll); - } - }; - Shared.prototype.applyNext = function(props, next, preserved) { - if (props && props.selection && props.selection.ranges) { - if (next && next.selection && next.selection.ranges && !Helper.equals(props.selection.ranges, next.selection.ranges)) { - this.delegateSelection(next.selection.ranges, next.selection.focus || false); - } - } - if (props && props.cursor) { - if (next && next.cursor && !Helper.equals(props.cursor, next.cursor)) { - this.delegateCursor(preserved.cursor || next.cursor, next.autoScroll || false, next.autoCursor || false); - } - } - if (props && props.scroll) { - if (next && next.scroll && !Helper.equals(props.scroll, next.scroll)) { - this.delegateScroll(next.scroll); - } - } - }; - Shared.prototype.applyUserDefined = function(props, preserved) { - if (preserved && preserved.cursor) { - this.delegateCursor(preserved.cursor, props.autoScroll || false, props.autoFocus || false); - } - }; - Shared.prototype.wire = function(props) { - var _this = this; - Object.keys(props || {}).filter(function(p) { - return (/^on/.test(p)); - }).forEach(function(prop) { - switch (prop) { - case 'onBlur': - { - _this.editor.on('blur', function(cm, event) { - _this.props.onBlur(_this.editor, event); - }); - } - break; - case 'onContextMenu': - { - _this.editor.on('contextmenu', function(cm, event) { - _this.props.onContextMenu(_this.editor, event); - }); - break; - } - case 'onCopy': - { - _this.editor.on('copy', function(cm, event) { - _this.props.onCopy(_this.editor, event); - }); - break; - } - case 'onCursor': - { - _this.editor.on('cursorActivity', function(cm) { - _this.props.onCursor(_this.editor, _this.editor.getCursor()); - }); - } - break; - case 'onCursorActivity': - { - _this.editor.on('cursorActivity', function(cm) { - _this.props.onCursorActivity(_this.editor); - }); - } - break; - case 'onCut': - { - _this.editor.on('cut', function(cm) { - _this.props.onCut(_this.editor, event); - }); - break; - } - case 'onDblClick': - { - _this.editor.on('dblclick', function(cm) { - _this.props.onDblClick(_this.editor, event); - }); - break; - } - case 'onDragEnter': - { - _this.editor.on('dragenter', function(cm, event) { - _this.props.onDragEnter(_this.editor, event); - }); - } - break; - case 'onDragLeave': - { - _this.editor.on('dragleave', function(cm) { - _this.props.onDragLeave(_this.editor, event); - }); - break; - } - case 'onDragOver': - { - _this.editor.on('dragover', function(cm, event) { - _this.props.onDragOver(_this.editor, event); - }); - } - break; - case 'onDragStart': - { - _this.editor.on('dragstart', function(cm) { - _this.props.onDragStart(_this.editor, event); - }); - break; - } - case 'onDrop': - { - _this.editor.on('drop', function(cm, event) { - _this.props.onDrop(_this.editor, event); - }); - } - break; - case 'onFocus': - { - _this.editor.on('focus', function(cm, event) { - _this.props.onFocus(_this.editor, event); - }); - } - break; - case 'onGutterClick': - { - _this.editor.on('gutterClick', function(cm, lineNumber, gutter, event) { - _this.props.onGutterClick(_this.editor, lineNumber, gutter, event); - }); - } - break; - case 'onKeyDown': - { - _this.editor.on('keydown', function(cm, event) { - _this.props.onKeyDown(_this.editor, event); - }); - } - break; - case 'onKeyPress': - { - _this.editor.on('keypress', function(cm, event) { - _this.props.onKeyPress(_this.editor, event); - }); - } - break; - case 'onKeyUp': - { - _this.editor.on('keyup', function(cm, event) { - _this.props.onKeyUp(_this.editor, event); - }); - } - break; - case 'onMouseDown': - { - _this.editor.on('mousedown', function(cm) { - _this.props.onMouseDown(_this.editor, event); - }); - break; - } - case 'onPaste': - { - _this.editor.on('paste', function(cm) { - _this.props.onPaste(_this.editor, event); - }); - break; - } - case 'onScroll': - { - _this.editor.on('scroll', function(cm) { - _this.props.onScroll(_this.editor, _this.editor.getScrollInfo()); - }); - } - break; - case 'onSelection': - { - _this.editor.on('beforeSelectionChange', function(cm, data) { - _this.props.onSelection(_this.editor, data); - }); - } - break; - case 'onTouchStart': - { - _this.editor.on('touchstart', function(cm) { - _this.props.onTouchStart(_this.editor, event); - }); - break; - } - case 'onUpdate': - { - _this.editor.on('update', function(cm) { - _this.props.onUpdate(_this.editor); - }); - } - break; - case 'onViewportChange': - { - _this.editor.on('viewportChange', function(cm, from, to) { - _this.props.onViewportChange(_this.editor, from, to); - }); - } - break; - } - }); - }; - return Shared; -}(); -var Controlled = function(_super) { - __extends(Controlled, _super); - - function Controlled(props) { - var _this = _super.call(this, props) || this; - if (SERVER_RENDERED) return _this; - _this.applied = false; - _this.appliedNext = false; - _this.appliedUserDefined = false; - _this.deferred = null; - _this.emulating = false; - _this.hydrated = false; - _this.initCb = function() { - if (_this.props.editorDidConfigure) { - _this.props.editorDidConfigure(_this.editor); - } - }; - _this.mounted = false; - return _this; - } - Controlled.prototype.hydrate = function(props) { - var _this = this; - var userDefinedOptions = _extends({}, cm.defaults, this.editor.options, props.options || {}); - var optionDelta = Object.keys(userDefinedOptions).some(function(key) { - return _this.editor.getOption(key) !== userDefinedOptions[key]; - }); - if (optionDelta) { - Object.keys(userDefinedOptions).forEach(function(key) { - if (props.options.hasOwnProperty(key)) { - if (_this.editor.getOption(key) !== userDefinedOptions[key]) { - _this.editor.setOption(key, userDefinedOptions[key]); - _this.mirror.setOption(key, userDefinedOptions[key]); - } - } - }); - } - if (!this.hydrated) { - if (!this.mounted) { - this.initChange(props.value || ''); - } else { - if (this.deferred) { - this.resolveChange(); - } else { - this.initChange(props.value || ''); - } - } - } - this.hydrated = true; - }; - Controlled.prototype.initChange = function(value) { - this.emulating = true; - var lastLine = this.editor.lastLine(); - var lastChar = this.editor.getLine(this.editor.lastLine()).length; - this.editor.replaceRange(value || '', { - line: 0, - ch: 0 - }, { - line: lastLine, - ch: lastChar - }); - this.mirror.setValue(value); - this.editor.clearHistory(); - this.mirror.clearHistory(); - this.emulating = false; - }; - Controlled.prototype.resolveChange = function() { - this.emulating = true; - if (this.deferred.origin === 'undo') { - this.editor.undo(); - } else if (this.deferred.origin === 'redo') { - this.editor.redo(); - } else { - this.editor.replaceRange(this.deferred.text, this.deferred.from, this.deferred.to, this.deferred.origin); - } - this.emulating = false; - this.deferred = null; - }; - Controlled.prototype.mirrorChange = function(deferred) { - if (deferred.origin === 'undo') { - this.editor.setHistory(this.mirror.getHistory()); - this.mirror.undo(); - } else if (deferred.origin === 'redo') { - this.editor.setHistory(this.mirror.getHistory()); - this.mirror.redo(); - } else { - this.mirror.replaceRange(deferred.text, deferred.from, deferred.to, deferred.origin); - } - return this.mirror.getValue(); - }; - Controlled.prototype.componentWillMount = function() { - if (SERVER_RENDERED) return; - if (this.props.editorWillMount) { - this.props.editorWillMount(); - } - }; - Controlled.prototype.componentDidMount = function() { - var _this = this; - if (SERVER_RENDERED) return; - if (this.props.defineMode) { - if (this.props.defineMode.name && this.props.defineMode.fn) { - cm.defineMode(this.props.defineMode.name, this.props.defineMode.fn); - } - } - this.editor = cm(this.ref); - this.shared = new Shared(this.editor, this.props); - this.mirror = cm(function() {}); - this.editor.on('electricInput', function() { - _this.mirror.setHistory(_this.editor.getHistory()); - }); - this.editor.on('cursorActivity', function() { - _this.mirror.setCursor(_this.editor.getCursor()); - }); - this.editor.on('beforeChange', function(cm, data) { - if (_this.emulating) { - return; - } - data.cancel(); - _this.deferred = data; - var phantomChange = _this.mirrorChange(_this.deferred); - if (_this.props.onBeforeChange) _this.props.onBeforeChange(_this.editor, _this.deferred, phantomChange); - }); - this.editor.on('change', function(cm, data) { - if (!_this.mounted) { - return; - } - if (_this.props.onChange) { - _this.props.onChange(_this.editor, data, _this.editor.getValue()); - } - }); - this.hydrate(this.props); - this.shared.apply(this.props); - this.applied = true; - this.mounted = true; - this.shared.wire(this.props); - if (this.props.editorDidMount) { - this.props.editorDidMount(this.editor, this.editor.getValue(), this.initCb); - } - }; - Controlled.prototype.componentWillReceiveProps = function(nextProps) { - if (SERVER_RENDERED) return; - var preserved = { - cursor: null - }; - if (nextProps.value !== this.props.value) { - this.hydrated = false; - } - if (!this.props.autoCursor && this.props.autoCursor !== undefined) { - preserved.cursor = this.editor.getCursor(); - } - this.hydrate(nextProps); - if (!this.appliedNext) { - this.shared.applyNext(this.props, nextProps, preserved); - this.appliedNext = true; - } - this.shared.applyUserDefined(this.props, preserved); - this.appliedUserDefined = true; - }; - Controlled.prototype.componentWillUnmount = function() { - if (SERVER_RENDERED) return; - if (this.props.editorWillUnmount) { - this.props.editorWillUnmount(cm); - } - }; - Controlled.prototype.shouldComponentUpdate = function(nextProps, nextState) { - return !SERVER_RENDERED; - }; - Controlled.prototype.render = function() { - var _this = this; - if (SERVER_RENDERED) return null; - var className = this.props.className ? 'react-codemirror2 ' + this.props.className : 'react-codemirror2'; - return React.createElement('div', { - className: className, - ref: function ref(self) { - return _this.ref = self; - } - }); - }; - return Controlled; -}(React.Component); -exports.Controlled = Controlled; -var UnControlled = function(_super) { - __extends(UnControlled, _super); - - function UnControlled(props) { - var _this = _super.call(this, props) || this; - if (SERVER_RENDERED) return _this; - _this.applied = false; - _this.appliedUserDefined = false; - _this.continueChange = false; - _this.detached = false; - _this.hydrated = false; - _this.initCb = function() { - if (_this.props.editorDidConfigure) { - _this.props.editorDidConfigure(_this.editor); - } - }; - _this.mounted = false; - _this.onBeforeChangeCb = function() { - _this.continueChange = true; - }; - return _this; - } - UnControlled.prototype.hydrate = function(props) { - var _this = this; - var userDefinedOptions = _extends({}, cm.defaults, this.editor.options, props.options || {}); - var optionDelta = Object.keys(userDefinedOptions).some(function(key) { - return _this.editor.getOption(key) !== userDefinedOptions[key]; - }); - if (optionDelta) { - Object.keys(userDefinedOptions).forEach(function(key) { - if (props.options.hasOwnProperty(key)) { - if (_this.editor.getOption(key) !== userDefinedOptions[key]) { - _this.editor.setOption(key, userDefinedOptions[key]); - } - } - }); - } - if (!this.hydrated) { - var lastLine = this.editor.lastLine(); - var lastChar = this.editor.getLine(this.editor.lastLine()).length; - this.editor.replaceRange(props.value || '', { - line: 0, - ch: 0 - }, { - line: lastLine, - ch: lastChar - }); - } - this.hydrated = true; - }; - UnControlled.prototype.componentWillMount = function() { - if (SERVER_RENDERED) return; - if (this.props.editorWillMount) { - this.props.editorWillMount(); - } - }; - UnControlled.prototype.componentDidMount = function() { - var _this = this; - if (SERVER_RENDERED) return; - this.detached = this.props.detach === true; - if (this.props.defineMode) { - if (this.props.defineMode.name && this.props.defineMode.fn) { - cm.defineMode(this.props.defineMode.name, this.props.defineMode.fn); - } - } - this.editor = cm(this.ref); - this.shared = new Shared(this.editor, this.props); - this.editor.on('beforeChange', function(cm, data) { - if (_this.props.onBeforeChange) { - _this.props.onBeforeChange(_this.editor, data, _this.editor.getValue(), _this.onBeforeChangeCb); - } - }); - this.editor.on('change', function(cm, data) { - if (!_this.mounted || !_this.props.onChange) { - return; - } - if (_this.props.onBeforeChange) { - if (_this.continueChange) { - _this.props.onChange(_this.editor, data, _this.editor.getValue()); - } - } else { - _this.props.onChange(_this.editor, data, _this.editor.getValue()); - } - }); - this.hydrate(this.props); - this.shared.apply(this.props); - this.applied = true; - this.mounted = true; - this.shared.wire(this.props); - this.editor.clearHistory(); - if (this.props.editorDidMount) { - this.props.editorDidMount(this.editor, this.editor.getValue(), this.initCb); - } - }; - UnControlled.prototype.componentWillReceiveProps = function(nextProps) { - if (this.detached && nextProps.detach === false) { - this.detached = false; - if (this.props.editorDidAttach) { - this.props.editorDidAttach(this.editor); - } - } - if (!this.detached && nextProps.detach === true) { - this.detached = true; - if (this.props.editorDidDetach) { - this.props.editorDidDetach(this.editor); - } - } - if (SERVER_RENDERED || this.detached) return; - var preserved = { - cursor: null - }; - if (nextProps.value !== this.props.value) { - this.hydrated = false; - this.applied = false; - this.appliedUserDefined = false; - } - if (!this.props.autoCursor && this.props.autoCursor !== undefined) { - preserved.cursor = this.editor.getCursor(); - } - this.hydrate(nextProps); - if (!this.applied) { - this.shared.apply(this.props); - this.applied = true; - } - if (!this.appliedUserDefined) { - this.shared.applyUserDefined(this.props, preserved); - this.appliedUserDefined = true; - } - }; - UnControlled.prototype.componentWillUnmount = function() { - if (SERVER_RENDERED) return; - if (this.props.editorWillUnmount) { - this.props.editorWillUnmount(cm); - } - }; - UnControlled.prototype.shouldComponentUpdate = function(nextProps, nextState) { - var update = true; - if (SERVER_RENDERED) update = false; - if (this.detached) update = false; - return update; - }; - UnControlled.prototype.render = function() { - var _this = this; - if (SERVER_RENDERED) return null; - var className = this.props.className ? 'react-codemirror2 ' + this.props.className : 'react-codemirror2'; - return React.createElement('div', { - className: className, - ref: function ref(self) { - return _this.ref = self; - } - }); - }; - return UnControlled; -}(React.Component); -exports.UnControlled = UnControlled; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(87))) - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.CopyToClipboard = undefined; - -var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - -var _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__(2); - -var _react2 = _interopRequireDefault(_react); - -var _copyToClipboard = __webpack_require__(59); - -var _copyToClipboard2 = _interopRequireDefault(_copyToClipboard); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } - -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 CopyToClipboard = exports.CopyToClipboard = function (_React$PureComponent) { - _inherits(CopyToClipboard, _React$PureComponent); - - function CopyToClipboard() { - var _ref; - - var _temp, _this, _ret; - - _classCallCheck(this, CopyToClipboard); - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = CopyToClipboard.__proto__ || Object.getPrototypeOf(CopyToClipboard)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (event) { - var _this$props = _this.props, - text = _this$props.text, - onCopy = _this$props.onCopy, - children = _this$props.children, - options = _this$props.options; - - - var elem = _react2.default.Children.only(children); - - var result = (0, _copyToClipboard2.default)(text, options); - - if (onCopy) { - onCopy(text, result); - } - - // Bypass onClick if it was present - if (elem && elem.props && typeof elem.props.onClick === 'function') { - elem.props.onClick(event); - } - }, _temp), _possibleConstructorReturn(_this, _ret); - } - - _createClass(CopyToClipboard, [{ - key: 'render', - value: function render() { - var _props = this.props, - _text = _props.text, - _onCopy = _props.onCopy, - _options = _props.options, - children = _props.children, - props = _objectWithoutProperties(_props, ['text', 'onCopy', 'options', 'children']); - - var elem = _react2.default.Children.only(children); - - return _react2.default.cloneElement(elem, _extends({}, props, { onClick: this.onClick })); - } - }]); - - return CopyToClipboard; -}(_react2.default.PureComponent); - -CopyToClipboard.defaultProps = { - onCopy: undefined, - options: undefined -}; - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _require = __webpack_require__(77), - CopyToClipboard = _require.CopyToClipboard; - -CopyToClipboard.CopyToClipboard = CopyToClipboard; -module.exports = CopyToClipboard; - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/** @license React v16.3.2 - * react-dom.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. - */ - - - - - -if (process.env.NODE_ENV !== "production") { - (function() { -'use strict'; - -var invariant = __webpack_require__(7); -var React = __webpack_require__(2); -var warning = __webpack_require__(16); -var ExecutionEnvironment = __webpack_require__(22); -var _assign = __webpack_require__(14); -var emptyFunction = __webpack_require__(6); -var checkPropTypes = __webpack_require__(26); -var getActiveElement = __webpack_require__(24); -var shallowEqual = __webpack_require__(25); -var containsNode = __webpack_require__(23); -var emptyObject = __webpack_require__(13); -var hyphenateStyleName = __webpack_require__(63); -var camelizeStyleName = __webpack_require__(61); - -// Relying on the `invariant()` implementation lets us -// have preserve the format and params in the www builds. - -!React ? invariant(false, 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.') : void 0; - -var invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) { - this._hasCaughtError = false; - this._caughtError = null; - var funcArgs = Array.prototype.slice.call(arguments, 3); - try { - func.apply(context, funcArgs); - } catch (error) { - this._caughtError = error; - this._hasCaughtError = true; - } -}; - -{ - // In DEV mode, we swap out invokeGuardedCallback for a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // untintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // a global event handler. But because the error happens in a different - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - - // Check that the browser supports the APIs we need to implement our special - // DEV version of invokeGuardedCallback - if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { - var fakeNode = document.createElement('react'); - - var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) { - // If document doesn't exist we know for sure we will crash in this method - // when we call document.createEvent(). However this can cause confusing - // errors: https://github.com/facebookincubator/create-react-app/issues/3482 - // So we preemptively throw with a better message instead. - !(typeof document !== 'undefined') ? invariant(false, 'The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.') : void 0; - var evt = document.createEvent('Event'); - - // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - var didError = true; - - // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - var funcArgs = Array.prototype.slice.call(arguments, 3); - function callCallback() { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - func.apply(context, funcArgs); - didError = false; - } - - // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. - var didSetError = false; - var isCrossOriginError = false; - - function onError(event) { - error = event.error; - didSetError = true; - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - } - - // Create a fake event type. - var evtType = 'react-' + (name ? name : 'invokeguardedcallback'); - - // Attach our event handlers - window.addEventListener('error', onError); - fakeNode.addEventListener(evtType, callCallback, false); - - // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); - } else if (isCrossOriginError) { - error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); - } - this._hasCaughtError = true; - this._caughtError = error; - } else { - this._hasCaughtError = false; - this._caughtError = null; - } - - // Remove our event listeners - window.removeEventListener('error', onError); - }; - - invokeGuardedCallback = invokeGuardedCallbackDev; - } -} - -var invokeGuardedCallback$1 = invokeGuardedCallback; - -var ReactErrorUtils = { - // Used by Fiber to simulate a try-catch. - _caughtError: null, - _hasCaughtError: false, - - // Used by event system to capture/rethrow the first error. - _rethrowError: null, - _hasRethrowError: false, - - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - invokeGuardedCallback: function (name, func, context, a, b, c, d, e, f) { - invokeGuardedCallback$1.apply(ReactErrorUtils, arguments); - }, - - /** - * Same as invokeGuardedCallback, but instead of returning an error, it stores - * it in a global so it can be rethrown by `rethrowCaughtError` later. - * TODO: See if _caughtError and _rethrowError can be unified. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - invokeGuardedCallbackAndCatchFirstError: function (name, func, context, a, b, c, d, e, f) { - ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); - if (ReactErrorUtils.hasCaughtError()) { - var error = ReactErrorUtils.clearCaughtError(); - if (!ReactErrorUtils._hasRethrowError) { - ReactErrorUtils._hasRethrowError = true; - ReactErrorUtils._rethrowError = error; - } - } - }, - - /** - * During execution of guarded functions we will capture the first error which - * we will rethrow to be handled by the top level error handler. - */ - rethrowCaughtError: function () { - return rethrowCaughtError.apply(ReactErrorUtils, arguments); - }, - - hasCaughtError: function () { - return ReactErrorUtils._hasCaughtError; - }, - - clearCaughtError: function () { - if (ReactErrorUtils._hasCaughtError) { - var error = ReactErrorUtils._caughtError; - ReactErrorUtils._caughtError = null; - ReactErrorUtils._hasCaughtError = false; - return error; - } else { - invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.'); - } - } -}; - -var rethrowCaughtError = function () { - if (ReactErrorUtils._hasRethrowError) { - var error = ReactErrorUtils._rethrowError; - ReactErrorUtils._rethrowError = null; - ReactErrorUtils._hasRethrowError = false; - throw error; - } -}; - -/** - * 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) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; - if (plugins[pluginIndex]) { - continue; - } - !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; - plugins[pluginIndex] = pluginModule; - var publishedEvents = pluginModule.eventTypes; - for (var eventName in publishedEvents) { - !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', 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) { - !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; - 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. - * - * @param {string} registrationName Registration name to add. - * @param {object} PluginModule Plugin publishing the event. - * @private - */ -function publishRegistrationName(registrationName, pluginModule, eventName) { - !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; - registrationNameModules[registrationName] = pluginModule; - registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; - - { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - - if (registrationName === 'onDoubleClick') { - possibleRegistrationNames.ondblclick = registrationName; - } - } -} - -/** - * Registers plugins so that they can extract and dispatch events. - * - * @see {EventPluginHub} - */ - -/** - * Ordered list of injected plugins. - */ -var plugins = []; - -/** - * Mapping from event name to dispatch config - */ -var eventNameDispatchConfigs = {}; - -/** - * Mapping from registration name to plugin module - */ -var registrationNameModules = {}; - -/** - * Mapping from registration name to event name - */ -var registrationNameDependencies = {}; - -/** - * Mapping from lowercase registration names to the properly cased version, - * used to warn in the case of missing event handlers. Available - * only in true. - * @type {Object} - */ -var possibleRegistrationNames = {}; -// Trust the developer to only use possibleRegistrationNames in true - -/** - * 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} - */ -function injectEventPluginOrder(injectedEventPluginOrder) { - !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : 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} - */ -function injectEventPluginsByName(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] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; - namesToPlugins[pluginName] = pluginModule; - isOrderingDirty = true; - } - } - if (isOrderingDirty) { - recomputePluginOrdering(); - } -} - -var EventPluginRegistry = Object.freeze({ - plugins: plugins, - eventNameDispatchConfigs: eventNameDispatchConfigs, - registrationNameModules: registrationNameModules, - registrationNameDependencies: registrationNameDependencies, - possibleRegistrationNames: possibleRegistrationNames, - injectEventPluginOrder: injectEventPluginOrder, - injectEventPluginsByName: injectEventPluginsByName -}); - -var getFiberCurrentPropsFromNode = null; -var getInstanceFromNode = null; -var getNodeFromInstance = null; - -var injection$1 = { - injectComponentTree: function (Injected) { - getFiberCurrentPropsFromNode = Injected.getFiberCurrentPropsFromNode; - getInstanceFromNode = Injected.getInstanceFromNode; - getNodeFromInstance = Injected.getNodeFromInstance; - - { - !(getNodeFromInstance && getInstanceFromNode) ? warning(false, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; - } - } -}; - - - - - - -var validateEventDispatches = void 0; -{ - 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; - - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warning(false, '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 = getNodeFromInstance(inst); - ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, 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; - { - 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; -} - -/** - * @see executeDispatchesInOrderStopAtTrueImpl - */ - - -/** - * 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. - */ - - -/** - * @param {SyntheticEvent} event - * @return {boolean} True iff number of dispatches accumulated is greater than 0. - */ - -/** - * 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) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : 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]; -} - -/** - * @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). - * @param {function} cb Callback invoked with each element or a collection. - * @param {?} [scope] Scope used as `this` in a callback. - */ -function forEachAccumulated(arr, cb, scope) { - if (Array.isArray(arr)) { - arr.forEach(cb, scope); - } else if (arr) { - cb.call(scope, arr); - } -} - -/** - * 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) { - 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); -}; - -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 - */ - -/** - * Methods for injecting dependencies. - */ -var injection = { - /** - * @param {array} InjectedEventPluginOrder - * @public - */ - injectEventPluginOrder: injectEventPluginOrder, - - /** - * @param {object} injectedNamesToPlugins Map from names to plugin modules. - */ - injectEventPluginsByName: injectEventPluginsByName -}; - -/** - * @param {object} inst The instance, which is the source of events. - * @param {string} registrationName Name of listener (e.g. `onClick`). - * @return {?function} The stored callback. - */ -function getListener(inst, registrationName) { - var listener = void 0; - - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not - // live here; needs to be moved to a better place soon - var stateNode = inst.stateNode; - if (!stateNode) { - // Work in progress (ex: onload events in incremental mode). - return null; - } - var props = getFiberCurrentPropsFromNode(stateNode); - if (!props) { - // Work in progress. - return null; - } - listener = props[registrationName]; - if (shouldPreventMouseEvent(registrationName, inst.type, props)) { - return null; - } - !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0; - return listener; -} - -/** - * Allows registered plugins an opportunity to extract events from top-level - * native browser events. - * - * @return {*} An accumulation of synthetic events. - * @internal - */ -function extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var events = null; - 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; -} - -function runEventsInBatch(events, simulated) { - if (events !== null) { - eventQueue = accumulateInto(eventQueue, events); - } - - // 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 (!processingEventQueue) { - return; - } - - if (simulated) { - forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); - } else { - forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - } - !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0; - // This would be a good time to rethrow if any of the event handlers threw. - ReactErrorUtils.rethrowCaughtError(); -} - -function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); - runEventsInBatch(events, false); -} - -var EventPluginHub = Object.freeze({ - injection: injection, - getListener: getListener, - runEventsInBatch: runEventsInBatch, - runExtractedEventsInBatch: runExtractedEventsInBatch -}); - -var IndeterminateComponent = 0; // Before we know whether it is functional or class -var FunctionalComponent = 1; -var ClassComponent = 2; -var HostRoot = 3; // Root of a host tree. Could be nested inside another node. -var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. -var HostComponent = 5; -var HostText = 6; -var CallComponent = 7; -var CallHandlerPhase = 8; -var ReturnComponent = 9; -var Fragment = 10; -var Mode = 11; -var ContextConsumer = 12; -var ContextProvider = 13; -var ForwardRef = 14; - -var randomKey = Math.random().toString(36).slice(2); -var internalInstanceKey = '__reactInternalInstance$' + randomKey; -var internalEventHandlersKey = '__reactEventHandlers$' + randomKey; - -function precacheFiberNode$1(hostInst, node) { - node[internalInstanceKey] = hostInst; -} - -/** - * Given a DOM node, return the closest ReactDOMComponent or - * ReactDOMTextComponent instance ancestor. - */ -function getClosestInstanceFromNode(node) { - if (node[internalInstanceKey]) { - return node[internalInstanceKey]; - } - - while (!node[internalInstanceKey]) { - 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 inst = node[internalInstanceKey]; - if (inst.tag === HostComponent || inst.tag === HostText) { - // In Fiber, this will always be the deepest root. - return inst; - } - - return null; -} - -/** - * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent - * instance, or null if the node was not rendered by this React. - */ -function getInstanceFromNode$1(node) { - var inst = node[internalInstanceKey]; - if (inst) { - if (inst.tag === HostComponent || inst.tag === HostText) { - return inst; - } else { - return null; - } - } - return null; -} - -/** - * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding - * DOM node. - */ -function getNodeFromInstance$1(inst) { - if (inst.tag === HostComponent || inst.tag === HostText) { - // In Fiber this, is just the state node right now. We assume it will be - // a host component or host text. - return inst.stateNode; - } - - // Without this first invariant, passing a non-DOM-component triggers the next - // invariant for a missing parent, which is super confusing. - invariant(false, 'getNodeFromInstance: Invalid argument.'); -} - -function getFiberCurrentPropsFromNode$1(node) { - return node[internalEventHandlersKey] || null; -} - -function updateFiberProps$1(node, props) { - node[internalEventHandlersKey] = props; -} - -var ReactDOMComponentTree = Object.freeze({ - precacheFiberNode: precacheFiberNode$1, - getClosestInstanceFromNode: getClosestInstanceFromNode, - getInstanceFromNode: getInstanceFromNode$1, - getNodeFromInstance: getNodeFromInstance$1, - getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode$1, - updateFiberProps: updateFiberProps$1 -}); - -function getParent(inst) { - do { - inst = inst['return']; - // TODO: If this is a HostRoot we might want to bail out. - // That is depending on if we want nested subtrees (layers) to bubble - // events to their parent. We could also go through parentNode on the - // host node but that wouldn't work for React Native and doesn't let us - // do the portal feature. - } while (inst && inst.tag !== HostComponent); - if (inst) { - return inst; - } - return null; -} - -/** - * Return the lowest common ancestor of A and B, or null if they are in - * different trees. - */ -function getLowestCommonAncestor(instA, instB) { - var depthA = 0; - for (var tempA = instA; tempA; tempA = getParent(tempA)) { - depthA++; - } - var depthB = 0; - for (var tempB = instB; tempB; tempB = getParent(tempB)) { - depthB++; - } - - // If A is deeper, crawl up. - while (depthA - depthB > 0) { - instA = getParent(instA); - depthA--; - } - - // If B is deeper, crawl up. - while (depthB - depthA > 0) { - instB = getParent(instB); - depthB--; - } - - // Walk in lockstep until we find a match. - var depth = depthA; - while (depth--) { - if (instA === instB || instA === instB.alternate) { - return instA; - } - instA = getParent(instA); - instB = getParent(instB); - } - return null; -} - -/** - * Return if A is an ancestor of B. - */ - - -/** - * Return the parent instance of the passed-in instance. - */ -function getParentInstance(inst) { - return getParent(inst); -} - -/** - * Simulates the traversal of a two-phase, capture/bubble event dispatch. - */ -function traverseTwoPhase(inst, fn, arg) { - var path = []; - while (inst) { - path.push(inst); - inst = getParent(inst); - } - var i = void 0; - for (i = path.length; i-- > 0;) { - fn(path[i], 'captured', arg); - } - for (i = 0; i < path.length; i++) { - fn(path[i], 'bubbled', arg); - } -} - -/** - * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that - * should would receive a `mouseEnter` or `mouseLeave` event. - * - * Does not invoke the callback on the nearest common ancestor because nothing - * "entered" or "left" that element. - */ -function traverseEnterLeave(from, to, fn, argFrom, argTo) { - var common = from && to ? getLowestCommonAncestor(from, to) : null; - var pathFrom = []; - while (true) { - if (!from) { - break; - } - if (from === common) { - break; - } - var alternate = from.alternate; - if (alternate !== null && alternate === common) { - break; - } - pathFrom.push(from); - from = getParent(from); - } - var pathTo = []; - while (true) { - if (!to) { - break; - } - if (to === common) { - break; - } - var _alternate = to.alternate; - if (_alternate !== null && _alternate === common) { - break; - } - pathTo.push(to); - to = getParent(to); - } - for (var i = 0; i < pathFrom.length; i++) { - fn(pathFrom[i], 'bubbled', argFrom); - } - for (var _i = pathTo.length; _i-- > 0;) { - fn(pathTo[_i], 'captured', argTo); - } -} - -/** - * 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); -} - -/** - * 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 even a - * single one. - */ - -/** - * 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) { - { - !inst ? warning(false, '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) { - 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 ? getParentInstance(targetInst) : null; - 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 (inst && 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) { - traverseEnterLeave(from, to, accumulateDispatches, leave, enter); -} - -function accumulateDirectDispatches(events) { - forEachAccumulated(events, accumulateDirectDispatchesSingle); -} - -var EventPropagators = Object.freeze({ - accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, - accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, - accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches, - accumulateDirectDispatches: accumulateDirectDispatches -}); - -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; -} - -/** - * This helper object 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. - * - * - */ -var compositionState = { - _root: null, - _startText: null, - _fallbackText: null -}; - -function initialize(nativeEventTarget) { - compositionState._root = nativeEventTarget; - compositionState._startText = getText(); - return true; -} - -function reset() { - compositionState._root = null; - compositionState._startText = null; - compositionState._fallbackText = null; -} - -function getData() { - if (compositionState._fallbackText) { - return compositionState._fallbackText; - } - - var start = void 0; - var startValue = compositionState._startText; - var startLength = startValue.length; - var end = void 0; - var endValue = getText(); - var endLength = endValue.length; - - for (start = 0; start < startLength; start++) { - if (startValue[start] !== endValue[start]) { - break; - } - } - - var minEnd = startLength - start; - for (end = 1; end <= minEnd; end++) { - if (startValue[startLength - end] !== endValue[endLength - end]) { - break; - } - } - - var sliceTail = end > 1 ? 1 - end : undefined; - compositionState._fallbackText = endValue.slice(start, sliceTail); - return compositionState._fallbackText; -} - -function getText() { - if ('value' in compositionState._root) { - return compositionState._root.value; - } - return compositionState._root[getTextContentAccessor()]; -} - -/* eslint valid-typeof: 0 */ - -var didWarnForAddedNewProperty = false; -var EVENT_POOL_SIZE = 10; - -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) { - { - // 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; - } - { - 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') { - 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') { - // 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) { - { - Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); - } - } - for (var i = 0; i < shouldBeReleasedProperties.length; i++) { - this[shouldBeReleasedProperties[i]] = null; - } - { - Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); - Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); - Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); - } - } -}); - -SyntheticEvent.Interface = EventInterface; - -/** - * Helper to reduce boilerplate when creating subclasses. - */ -SyntheticEvent.extend = function (Interface) { - var Super = this; - - var E = function () {}; - E.prototype = Super.prototype; - var prototype = new E(); - - function Class() { - return Super.apply(this, arguments); - } - _assign(prototype, Class.prototype); - Class.prototype = prototype; - Class.prototype.constructor = Class; - - Class.Interface = _assign({}, Super.Interface, Interface); - Class.extend = Super.extend; - addEventPoolingTo(Class); - - return Class; -}; - -/** Proxying after everything set on SyntheticEvent - * to resolve Proxy issue on some WebKit browsers - * in which some Event properties are set to undefined (GH#10010) - */ -{ - var isProxySupported = typeof Proxy === 'function' && - // https://github.com/facebook/react/issues/12011 - !Object.isSealed(new Proxy({}, {})); - - 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) { - !(didWarnForAddedNewProperty || target.isPersistent()) ? warning(false, "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 */ - } -} - -addEventPoolingTo(SyntheticEvent); - -/** - * Helper to nullify syntheticEvent instance properties when destructing - * - * @param {String} propName - * @param {?object} getVal - * @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; - !warningCondition ? warning(false, "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; - } -} - -function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { - var EventConstructor = this; - if (EventConstructor.eventPool.length) { - var instance = EventConstructor.eventPool.pop(); - EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); - return instance; - } - return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); -} - -function releasePooledEvent(event) { - var EventConstructor = this; - !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0; - event.destructor(); - if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { - EventConstructor.eventPool.push(event); - } -} - -function addEventPoolingTo(EventConstructor) { - EventConstructor.eventPool = []; - EventConstructor.getPooled = getPooledEvent; - EventConstructor.release = releasePooledEvent; -} - -var SyntheticEvent$1 = SyntheticEvent; - -/** - * @interface Event - * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents - */ -var SyntheticCompositionEvent = SyntheticEvent$1.extend({ - data: null -}); - -/** - * @interface Event - * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 - * /#events-inputevents - */ -var SyntheticInputEvent = SyntheticEvent$1.extend({ - data: null -}); - -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; - -// 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); - -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 status, if any. -var isComposing = false; - -/** - * @return {?object} A SyntheticCompositionEvent. - */ -function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var eventType = void 0; - var fallbackData = void 0; - - if (canUseCompositionEvent) { - eventType = getCompositionEventType(topLevelType); - } else if (!isComposing) { - 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 (!isComposing && eventType === eventTypes.compositionStart) { - isComposing = initialize(nativeEventTarget); - } else if (eventType === eventTypes.compositionEnd) { - if (isComposing) { - fallbackData = 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; - } - } - - accumulateTwoPhaseDispatches(event); - return event; -} - -/** - * @param {TopLevelTypes} topLevelType Record from `BrowserEventConstants`. - * @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 `BrowserEventConstants`. - * @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 (isComposing) { - if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { - var chars = getData(); - reset(); - isComposing = false; - 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 (!isKeypressCommand(nativeEvent)) { - // IE fires the `keypress` event when a user types an emoji via - // Touch keyboard of Windows. In such a case, the `char` property - // holds an emoji character like `\uD83D\uDE0A`. Because its length - // is 2, the property `which` does not represent an emoji correctly. - // In such a case, we directly return the `char` property instead of - // using `which`. - if (nativeEvent.char && nativeEvent.char.length > 1) { - return nativeEvent.char; - } else if (nativeEvent.which) { - return String.fromCharCode(nativeEvent.which); - } - } - return null; - case '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 = void 0; - - 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; - 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) { - var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); - - var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); - - if (composition === null) { - return beforeInput; - } - - if (beforeInput === null) { - return composition; - } - - return [composition, beforeInput]; - } -}; - -// Use to restore controlled state after a change event has fired. - -var fiberHostComponent = null; - -var ReactControlledComponentInjection = { - injectFiberControlledHostComponent: function (hostComponentImpl) { - // The fiber implementation doesn't use dynamic dispatch so we need to - // inject the implementation. - fiberHostComponent = hostComponentImpl; - } -}; - -var restoreTarget = null; -var restoreQueue = null; - -function restoreStateOfTarget(target) { - // We perform this translation at the end of the event loop so that we - // always receive the correct fiber here - var internalInstance = getInstanceFromNode(target); - if (!internalInstance) { - // Unmounted - return; - } - !(fiberHostComponent && typeof fiberHostComponent.restoreControlledState === 'function') ? invariant(false, 'Fiber needs to be injected to handle a fiber target for controlled events. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); - fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); -} - -var injection$2 = ReactControlledComponentInjection; - -function enqueueStateRestore(target) { - if (restoreTarget) { - if (restoreQueue) { - restoreQueue.push(target); - } else { - restoreQueue = [target]; - } - } else { - restoreTarget = target; - } -} - -function needsStateRestore() { - return restoreTarget !== null || restoreQueue !== null; -} - -function restoreStateIfNeeded() { - if (!restoreTarget) { - return; - } - var target = restoreTarget; - var queuedTargets = restoreQueue; - restoreTarget = null; - restoreQueue = null; - - restoreStateOfTarget(target); - if (queuedTargets) { - for (var i = 0; i < queuedTargets.length; i++) { - restoreStateOfTarget(queuedTargets[i]); - } - } -} - -var ReactControlledComponent = Object.freeze({ - injection: injection$2, - enqueueStateRestore: enqueueStateRestore, - needsStateRestore: needsStateRestore, - restoreStateIfNeeded: restoreStateIfNeeded -}); - -// Used as a way to call batchedUpdates when we don't have a reference to -// the renderer. Such as when we're dispatching events or if third party -// libraries need to call batchedUpdates. Eventually, this API will go away when -// everything is batched by default. We'll then have a similar API to opt-out of -// scheduled work and instead do synchronous work. - -// Defaults -var _batchedUpdates = function (fn, bookkeeping) { - return fn(bookkeeping); -}; -var _interactiveUpdates = function (fn, a, b) { - return fn(a, b); -}; -var _flushInteractiveUpdates = function () {}; - -var isBatching = false; -function batchedUpdates(fn, bookkeeping) { - if (isBatching) { - // If we are currently inside another batch, we need to wait until it - // fully completes before restoring state. - return fn(bookkeeping); - } - isBatching = true; - try { - return _batchedUpdates(fn, bookkeeping); - } finally { - // Here we wait until all updates have propagated, which is important - // when using controlled components within layers: - // https://github.com/facebook/react/issues/1698 - // Then we restore state of any controlled component. - isBatching = false; - var controlledComponentsHavePendingUpdates = needsStateRestore(); - if (controlledComponentsHavePendingUpdates) { - // If a controlled event was fired, we may need to restore the state of - // the DOM node back to the controlled value. This is necessary when React - // bails out of the update without touching the DOM. - _flushInteractiveUpdates(); - restoreStateIfNeeded(); - } - } -} - -function interactiveUpdates(fn, a, b) { - return _interactiveUpdates(fn, a, b); -} - - - -var injection$3 = { - injectRenderer: function (renderer) { - _batchedUpdates = renderer.batchedUpdates; - _interactiveUpdates = renderer.interactiveUpdates; - _flushInteractiveUpdates = renderer.flushInteractiveUpdates; - } -}; - -/** - * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary - */ -var supportedInputTypes = { - color: true, - date: true, - datetime: true, - 'datetime-local': true, - email: true, - month: true, - number: true, - password: true, - range: true, - search: true, - tel: true, - text: true, - time: true, - url: true, - week: true -}; - -function isTextInputElement(elem) { - var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); - - if (nodeName === 'input') { - return !!supportedInputTypes[elem.type]; - } - - if (nodeName === 'textarea') { - return true; - } - - return false; -} - -/** - * HTML nodeType values that represent the type of the node - */ - -var ELEMENT_NODE = 1; -var TEXT_NODE = 3; -var COMMENT_NODE = 8; -var DOCUMENT_NODE = 9; -var DOCUMENT_FRAGMENT_NODE = 11; - -/** - * 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 || window; - - // Normalize SVG element events #4963 - if (target.correspondingUseElement) { - target = target.correspondingUseElement; - } - - // Safari may fire events on text nodes (Node.TEXT_NODE is 3). - // @see http://www.quirksmode.org/js/events_properties.html - return target.nodeType === TEXT_NODE ? target.parentNode : target; -} - -/** - * Checks if an event is supported in the current execution environment. - * - * NOTE: This will not work correctly for non-generic events such as `change`, - * `reset`, `load`, `error`, and `select`. - * - * Borrows from Modernizr. - * - * @param {string} eventNameSuffix Event name, e.g. "click". - * @param {?boolean} capture Check if the capture phase is supported. - * @return {boolean} True if the event is supported. - * @internal - * @license Modernizr 3.0.0pre (Custom Build) | MIT - */ -function isEventSupported(eventNameSuffix, capture) { - if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { - return false; - } - - var eventName = 'on' + eventNameSuffix; - var isSupported = eventName in document; - - if (!isSupported) { - var element = document.createElement('div'); - element.setAttribute(eventName, 'return;'); - isSupported = typeof element[eventName] === 'function'; - } - - return isSupported; -} - -function isCheckable(elem) { - var type = elem.type; - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); -} - -function getTracker(node) { - return node._valueTracker; -} - -function detachTracker(node) { - node._valueTracker = null; -} - -function getValueFromNode(node) { - var value = ''; - if (!node) { - return value; - } - - if (isCheckable(node)) { - value = node.checked ? 'true' : 'false'; - } else { - value = node.value; - } - - return value; -} - -function trackValueOnNode(node) { - var valueField = isCheckable(node) ? 'checked' : 'value'; - var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - - var currentValue = '' + node[valueField]; - - // if someone has already defined a value or Safari, then bail - // and don't track value will cause over reporting of changes, - // but it's better then a hard failure - // (needed for certain tests that spyOn input values and Safari) - if (node.hasOwnProperty(valueField) || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { - return; - } - - Object.defineProperty(node, valueField, { - configurable: true, - get: function () { - return descriptor.get.call(this); - }, - set: function (value) { - currentValue = '' + value; - descriptor.set.call(this, value); - } - }); - // We could've passed this the first time - // but it triggers a bug in IE11 and Edge 14/15. - // Calling defineProperty() again should be equivalent. - // https://github.com/facebook/react/issues/11768 - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable - }); - - var tracker = { - getValue: function () { - return currentValue; - }, - setValue: function (value) { - currentValue = '' + value; - }, - stopTracking: function () { - detachTracker(node); - delete node[valueField]; - } - }; - return tracker; -} - -function track(node) { - if (getTracker(node)) { - return; - } - - // TODO: Once it's just Fiber we can move this to node._wrapperState - node._valueTracker = trackValueOnNode(node); -} - -function updateValueIfChanged(node) { - if (!node) { - return false; - } - - var tracker = getTracker(node); - // if there is no tracker at this point it's unlikely - // that trying again will succeed - if (!tracker) { - return true; - } - - var lastValue = tracker.getValue(); - var nextValue = getValueFromNode(node); - if (nextValue !== lastValue) { - tracker.setValue(nextValue); - return true; - } - return false; -} - -var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -var ReactCurrentOwner = ReactInternals.ReactCurrentOwner; -var ReactDebugCurrentFrame = ReactInternals.ReactDebugCurrentFrame; - -var describeComponentFrame = function (name, source, ownerName) { - return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); -}; - -// The Symbol used to tag the ReactElement-like types. If there is no native Symbol -// nor polyfill, then a plain number is used for performance. -var hasSymbol = typeof Symbol === 'function' && Symbol['for']; - -var REACT_ELEMENT_TYPE = hasSymbol ? Symbol['for']('react.element') : 0xeac7; -var REACT_CALL_TYPE = hasSymbol ? Symbol['for']('react.call') : 0xeac8; -var REACT_RETURN_TYPE = hasSymbol ? Symbol['for']('react.return') : 0xeac9; -var REACT_PORTAL_TYPE = hasSymbol ? Symbol['for']('react.portal') : 0xeaca; -var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol['for']('react.fragment') : 0xeacb; -var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol['for']('react.strict_mode') : 0xeacc; -var REACT_PROVIDER_TYPE = hasSymbol ? Symbol['for']('react.provider') : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol['for']('react.context') : 0xeace; -var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol['for']('react.async_mode') : 0xeacf; -var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol['for']('react.forward_ref') : 0xead0; - -var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; -var FAUX_ITERATOR_SYMBOL = '@@iterator'; - -function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable === 'undefined') { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - return null; -} - -function getComponentName(fiber) { - var type = fiber.type; - - if (typeof type === 'function') { - return type.displayName || type.name; - } - if (typeof type === 'string') { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'ReactFragment'; - case REACT_PORTAL_TYPE: - return 'ReactPortal'; - case REACT_CALL_TYPE: - return 'ReactCall'; - case REACT_RETURN_TYPE: - return 'ReactReturn'; - } - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - var functionName = type.render.displayName || type.render.name || ''; - return functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef'; - } - } - return null; -} - -function describeFiber(fiber) { - switch (fiber.tag) { - case IndeterminateComponent: - case FunctionalComponent: - case ClassComponent: - case HostComponent: - var owner = fiber._debugOwner; - var source = fiber._debugSource; - var name = getComponentName(fiber); - var ownerName = null; - if (owner) { - ownerName = getComponentName(owner); - } - return describeComponentFrame(name, source, ownerName); - default: - return ''; - } -} - -// This function can only be called with a work-in-progress fiber and -// only during begin or complete phase. Do not call it under any other -// circumstances. -function getStackAddendumByWorkInProgressFiber(workInProgress) { - var info = ''; - var node = workInProgress; - do { - info += describeFiber(node); - // Otherwise this return pointer might point to the wrong tree: - node = node['return']; - } while (node); - return info; -} - -function getCurrentFiberOwnerName$1() { - { - var fiber = ReactDebugCurrentFiber.current; - if (fiber === null) { - return null; - } - var owner = fiber._debugOwner; - if (owner !== null && typeof owner !== 'undefined') { - return getComponentName(owner); - } - } - return null; -} - -function getCurrentFiberStackAddendum$1() { - { - var fiber = ReactDebugCurrentFiber.current; - if (fiber === null) { - return null; - } - // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - return getStackAddendumByWorkInProgressFiber(fiber); - } - return null; -} - -function resetCurrentFiber() { - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFiber.current = null; - ReactDebugCurrentFiber.phase = null; -} - -function setCurrentFiber(fiber) { - ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackAddendum$1; - ReactDebugCurrentFiber.current = fiber; - ReactDebugCurrentFiber.phase = null; -} - -function setCurrentPhase(phase) { - ReactDebugCurrentFiber.phase = phase; -} - -var ReactDebugCurrentFiber = { - current: null, - phase: null, - resetCurrentFiber: resetCurrentFiber, - setCurrentFiber: setCurrentFiber, - setCurrentPhase: setCurrentPhase, - getCurrentFiberOwnerName: getCurrentFiberOwnerName$1, - getCurrentFiberStackAddendum: getCurrentFiberStackAddendum$1 -}; - -// A reserved attribute. -// It is handled by React separately and shouldn't be written to the DOM. -var RESERVED = 0; - -// A simple string attribute. -// Attributes that aren't in the whitelist are presumed to have this type. -var STRING = 1; - -// A string attribute that accepts booleans in React. In HTML, these are called -// "enumerated" attributes with "true" and "false" as possible values. -// When true, it should be set to a "true" string. -// When false, it should be set to a "false" string. -var BOOLEANISH_STRING = 2; - -// A real boolean attribute. -// When true, it should be present (set either to an empty string or its name). -// When false, it should be omitted. -var BOOLEAN = 3; - -// An attribute that can be used as a flag as well as with a value. -// When true, it should be present (set either to an empty string or its name). -// When false, it should be omitted. -// For any other value, should be present with that value. -var OVERLOADED_BOOLEAN = 4; - -// An attribute that must be numeric or parse as a numeric. -// When falsy, it should be removed. -var NUMERIC = 5; - -// An attribute that must be positive numeric or parse as a positive numeric. -// When falsy, it should be removed. -var POSITIVE_NUMERIC = 6; - -/* eslint-disable max-len */ -var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; -/* eslint-enable max-len */ -var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; - - -var ROOT_ATTRIBUTE_NAME = 'data-reactroot'; -var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); - -var illegalAttributeNameCache = {}; -var validatedAttributeNameCache = {}; - -function isAttributeNameSafe(attributeName) { - if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { - return true; - } - if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { - return false; - } - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - illegalAttributeNameCache[attributeName] = true; - { - warning(false, 'Invalid attribute name: `%s`', attributeName); - } - return false; -} - -function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED; - } - if (isCustomComponentTag) { - return false; - } - if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { - return true; - } - return false; -} - -function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - switch (typeof value) { - case 'function': - // $FlowIssue symbol is perfectly valid here - case 'symbol': - // eslint-disable-line - return true; - case 'boolean': - { - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix = name.toLowerCase().slice(0, 5); - return prefix !== 'data-' && prefix !== 'aria-'; - } - } - default: - return false; - } -} - -function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { - if (value === null || typeof value === 'undefined') { - return true; - } - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { - return true; - } - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value; - case OVERLOADED_BOOLEAN: - return value === false; - case NUMERIC: - return isNaN(value); - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1; - } - } - return false; -} - -function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; -} - -function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; -} - -// When adding attributes to this list, be sure to also add them to -// the `possibleStandardNames` module to ensure casing and incorrect -// name warnings. -var properties = {}; - -// These props are reserved by React. They shouldn't be written to the DOM. -['children', 'dangerouslySetInnerHTML', -// TODO: This prevents the assignment of defaultValue to regular -// elements (not just inputs). Now that ReactDOMInput assigns to the -// defaultValue property -- do we need this? -'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty - name, // attributeName - null); -}); - -// A few React string attributes have a different name. -// This is a mapping from React prop names to the attribute names. -[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { - var name = _ref[0], - attributeName = _ref[1]; - - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, // attributeName - null); -}); - -// These are "enumerated" HTML attributes that accept "true" and "false". -// In React, we let users pass `true` and `false` even though technically -// these aren't boolean attributes (they are coerced to strings). -['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -// These are "enumerated" SVG attributes that accept "true" and "false". -// In React, we let users pass `true` and `false` even though technically -// these aren't boolean attributes (they are coerced to strings). -// Since these are SVG attributes, their attribute names are case-sensitive. -['autoReverse', 'externalResourcesRequired', 'preserveAlpha'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty - name, // attributeName - null); -}); - -// These are HTML boolean attributes. -['allowFullScreen', 'async', -// Note: there is a special case that prevents it from being written to the DOM -// on the client side because the browsers are inconsistent. Instead we call focus(). -'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', -// Microdata -'itemScope'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -// These are the few React props that we set as DOM properties -// rather than attributes. These are all booleans. -['checked', -// Note: `option.selected` is not updated if `select.multiple` is -// disabled with `removeAttribute`. We have special logic for handling this. -'multiple', 'muted', 'selected'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -// These are HTML attributes that are "overloaded booleans": they behave like -// booleans, but can also accept a string value. -['capture', 'download'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -// These are HTML attributes that must be positive numbers. -['cols', 'rows', 'size', 'span'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -// These are HTML attributes that must be numbers. -['rowSpan', 'start'].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty - name.toLowerCase(), // attributeName - null); -}); - -var CAMELIZE = /[\-\:]([a-z])/g; -var capitalize = function (token) { - return token[1].toUpperCase(); -}; - -// This is a list of all SVG attributes that need special casing, namespacing, -// or boolean value assignment. Regular attributes that just accept strings -// and have the same names are omitted, just like in the HTML whitelist. -// Some of these attributes can be hard to find. This list was created by -// scrapping the MDN documentation. -['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height'].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, null); -}); - -// String SVG attributes with the xlink namespace. -['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/1999/xlink'); -}); - -// String SVG attributes with the xml namespace. -['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/XML/1998/namespace'); -}); - -// Special case: this attribute exists both in HTML and SVG. -// Its "tabindex" attribute name is case-sensitive in SVG so we can't just use -// its React `tabIndex` name, like we do for attributes that exist only in HTML. -properties.tabIndex = new PropertyInfoRecord('tabIndex', STRING, false, // mustUseProperty -'tabindex', // attributeName -null); - -/** - * Get the value for a property on a node. Only used in DEV for SSR validation. - * The "expected" argument is used as a hint of what the expected value is. - * Some properties have multiple equivalent values. - */ -function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName; - - return node[propertyName]; - } else { - var attributeName = propertyInfo.attributeName; - - var stringValue = null; - - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName); - if (value === '') { - return true; - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return value; - } - if (value === '' + expected) { - return expected; - } - return value; - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - // We had an attribute but shouldn't have had one, so read it - // for the error message. - return node.getAttribute(attributeName); - } - if (propertyInfo.type === BOOLEAN) { - // If this was a boolean, it doesn't matter what the value is - // the fact that we have it is the same as the expected. - return expected; - } - // Even if this property uses a namespace we use getAttribute - // because we assume its namespaced name is the same as our config. - // To use getAttributeNS we need the local name which we don't have - // in our config atm. - stringValue = node.getAttribute(attributeName); - } - - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue; - } else if (stringValue === '' + expected) { - return expected; - } else { - return stringValue; - } - } - } -} - -/** - * Get the value for a attribute on a node. Only used in DEV for SSR validation. - * The third argument is used as a hint of what the expected value is. Some - * attributes have multiple equivalent values. - */ -function getValueForAttribute(node, name, expected) { - { - if (!isAttributeNameSafe(name)) { - return; - } - if (!node.hasAttribute(name)) { - return expected === undefined ? undefined : null; - } - var value = node.getAttribute(name); - if (value === '' + expected) { - return expected; - } - return value; - } -} - -/** - * Sets the value for a property on a node. - * - * @param {DOMElement} node - * @param {string} name - * @param {*} value - */ -function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name); - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return; - } - if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { - value = null; - } - // If the prop isn't in the special list, treat it as a simple attribute. - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name; - if (value === null) { - node.removeAttribute(_attributeName); - } else { - node.setAttribute(_attributeName, '' + value); - } - } - return; - } - var mustUseProperty = propertyInfo.mustUseProperty; - - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName; - - if (value === null) { - var type = propertyInfo.type; - - node[propertyName] = type === BOOLEAN ? false : ''; - } else { - // Contrary to `setAttribute`, object properties are properly - // `toString`ed by IE8/9. - node[propertyName] = value; - } - return; - } - // The rest are treated as attributes with special cases. - var attributeName = propertyInfo.attributeName, - attributeNamespace = propertyInfo.attributeNamespace; - - if (value === null) { - node.removeAttribute(attributeName); - } else { - var _type = propertyInfo.type; - - var attributeValue = void 0; - if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { - attributeValue = ''; - } else { - // `setAttribute` with objects becomes only `[object]` in IE8/9, - // ('' + value) makes it output the correct toString()-value. - attributeValue = '' + value; - } - if (attributeNamespace) { - node.setAttributeNS(attributeNamespace, attributeName, attributeValue); - } else { - node.setAttribute(attributeName, attributeValue); - } - } -} - -var ReactControlledValuePropTypes = { - checkPropTypes: null -}; - -{ - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - - var propTypes = { - value: function (props, propName, componentName) { - if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { - return null; - } - return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - }, - checked: function (props, propName, componentName) { - if (!props[propName] || props.onChange || props.readOnly || props.disabled) { - return null; - } - return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - } - }; - - /** - * Provide a linked `value` attribute for controlled forms. You should not use - * this outside of the ReactDOM controlled form components. - */ - ReactControlledValuePropTypes.checkPropTypes = function (tagName, props, getStack) { - checkPropTypes(propTypes, props, 'prop', tagName, getStack); - }; -} - -// TODO: direct imports like some-package/src/* are bad. Fix me. -var getCurrentFiberOwnerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName; -var getCurrentFiberStackAddendum = ReactDebugCurrentFiber.getCurrentFiberStackAddendum; - -var didWarnValueDefaultValue = false; -var didWarnCheckedDefaultChecked = false; -var didWarnControlledToUncontrolled = false; -var didWarnUncontrolledToControlled = false; - -function isControlled(props) { - var usesChecked = props.type === 'checkbox' || props.type === 'radio'; - return usesChecked ? props.checked != null : props.value != null; -} - -/** - * Implements an host component that allows setting these optional - * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. - * - * If `checked` or `value` are not supplied (or null/undefined), user actions - * that affect the checked state or value will trigger updates to the element. - * - * If they are supplied (and not null/undefined), the rendered element will not - * trigger updates to the element. Instead, the props must change in order for - * the rendered element to be updated. - * - * The rendered element will be initialized as unchecked (or `defaultChecked`) - * with an empty value (or `defaultValue`). - * - * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html - */ - -function getHostProps(element, props) { - var node = element; - var checked = props.checked; - - var hostProps = _assign({}, props, { - defaultChecked: undefined, - defaultValue: undefined, - value: undefined, - checked: checked != null ? checked : node._wrapperState.initialChecked - }); - - return hostProps; -} - -function initWrapperState(element, props) { - { - ReactControlledValuePropTypes.checkPropTypes('input', props, getCurrentFiberStackAddendum); - - if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { - warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type); - didWarnCheckedDefaultChecked = true; - } - if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { - warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerName() || 'A component', props.type); - didWarnValueDefaultValue = true; - } - } - - var node = element; - var defaultValue = props.defaultValue == null ? '' : props.defaultValue; - - node._wrapperState = { - initialChecked: props.checked != null ? props.checked : props.defaultChecked, - initialValue: getSafeValue(props.value != null ? props.value : defaultValue), - controlled: isControlled(props) - }; -} - -function updateChecked(element, props) { - var node = element; - var checked = props.checked; - if (checked != null) { - setValueForProperty(node, 'checked', checked, false); - } -} - -function updateWrapper(element, props) { - var node = element; - { - var _controlled = isControlled(props); - - if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) { - warning(false, 'A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum()); - didWarnUncontrolledToControlled = true; - } - if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) { - warning(false, 'A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getCurrentFiberStackAddendum()); - didWarnControlledToUncontrolled = true; - } - } - - updateChecked(element, props); - - var value = getSafeValue(props.value); - - if (value != null) { - if (props.type === 'number') { - if (value === 0 && node.value === '' || - // eslint-disable-next-line - node.value != value) { - node.value = '' + value; - } - } else if (node.value !== '' + value) { - node.value = '' + value; - } - } - - if (props.hasOwnProperty('value')) { - setDefaultValue(node, props.type, value); - } else if (props.hasOwnProperty('defaultValue')) { - setDefaultValue(node, props.type, getSafeValue(props.defaultValue)); - } - - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked; - } -} - -function postMountWrapper(element, props) { - var node = element; - - if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { - // Do not assign value if it is already set. This prevents user text input - // from being lost during SSR hydration. - if (node.value === '') { - node.value = '' + node._wrapperState.initialValue; - } - - // value must be assigned before defaultValue. This fixes an issue where the - // visually displayed value of date inputs disappears on mobile Safari and Chrome: - // https://github.com/facebook/react/issues/7233 - node.defaultValue = '' + node._wrapperState.initialValue; - } - - // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug - // this is needed to work around a chrome bug where setting defaultChecked - // will sometimes influence the value of checked (even after detachment). - // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 - // We need to temporarily unset name to avoid disrupting radio button groups. - var name = node.name; - if (name !== '') { - node.name = ''; - } - node.defaultChecked = !node.defaultChecked; - node.defaultChecked = !node.defaultChecked; - if (name !== '') { - node.name = name; - } -} - -function restoreControlledState(element, props) { - var node = element; - updateWrapper(node, props); - updateNamedCousins(node, props); -} - -function updateNamedCousins(rootNode, props) { - var name = props.name; - if (props.type === 'radio' && name != null) { - var queryRoot = rootNode; - - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode; - } - - // If `rootNode.form` was non-null, then we could try `form.elements`, - // but that sometimes behaves strangely in IE8. We could also try using - // `form.getElementsByName`, but that will only return direct children - // and won't include inputs that use the HTML5 `form=` attribute. Since - // the input might not even be in a form. It might not even be in the - // document. Let's just use the local `querySelectorAll` to ensure we don't - // miss anything. - var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); - - for (var i = 0; i < group.length; i++) { - var otherNode = group[i]; - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue; - } - // This will throw if radio buttons rendered by different copies of React - // and the same name are rendered into the same form (same as #1939). - // That's probably okay; we don't support it just as we don't support - // mixing React radio buttons with non-React ones. - var otherProps = getFiberCurrentPropsFromNode$1(otherNode); - !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0; - - // We need update the tracked value on the named cousin since the value - // was changed but the input saw no event or value set - updateValueIfChanged(otherNode); - - // If this is a controlled radio button group, forcing the input that - // was previously checked to update will cause it to be come re-checked - // as appropriate. - updateWrapper(otherNode, otherProps); - } - } -} - -// In Chrome, assigning defaultValue to certain input types triggers input validation. -// For number inputs, the display value loses trailing decimal points. For email inputs, -// Chrome raises "The specified value is not a valid email address". -// -// Here we check to see if the defaultValue has actually changed, avoiding these problems -// when the user is inputting text -// -// https://github.com/facebook/react/issues/7253 -function setDefaultValue(node, type, value) { - if ( - // Focused number inputs synchronize on blur. See ChangeEventPlugin.js - type !== 'number' || node.ownerDocument.activeElement !== node) { - if (value == null) { - node.defaultValue = '' + node._wrapperState.initialValue; - } else if (node.defaultValue !== '' + value) { - node.defaultValue = '' + value; - } - } -} - -function getSafeValue(value) { - switch (typeof value) { - case 'boolean': - case 'number': - case 'object': - case 'string': - case 'undefined': - return value; - default: - // function, symbol are assigned as empty strings - return ''; - } -} - -var eventTypes$1 = { - change: { - phasedRegistrationNames: { - bubbled: 'onChange', - captured: 'onChangeCapture' - }, - dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] - } -}; - -function createAndAccumulateChangeEvent(inst, nativeEvent, target) { - var event = SyntheticEvent$1.getPooled(eventTypes$1.change, inst, nativeEvent, target); - event.type = 'change'; - // Flag this event loop as needing state restore. - enqueueStateRestore(target); - accumulateTwoPhaseDispatches(event); - return event; -} -/** - * For IE shims - */ -var activeElement = null; -var activeElementInst = null; - -/** - * SECTION: handle `change` event - */ -function shouldUseChangeEvent(elem) { - var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); - return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; -} - -function manualDispatchChangeEvent(nativeEvent) { - var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); - - // If change and propertychange bubbled, we'd just bind to it like all the - // other events and have it go through ReactBrowserEventEmitter. Since it - // doesn't, we manually listen for the events and so we have to enqueue and - // process the abstract event manually. - // - // Batching is necessary here in order to ensure that all event handlers run - // before the next rerender (including event handlers attached to ancestor - // elements instead of directly on the input). Without this, controlled - // components don't work properly in conjunction with event bubbling because - // the component is rerendered and the value reverted before all the event - // handlers can run. See https://github.com/facebook/react/issues/708. - batchedUpdates(runEventInBatch, event); -} - -function runEventInBatch(event) { - runEventsInBatch(event, false); -} - -function getInstIfValueChanged(targetInst) { - var targetNode = getNodeFromInstance$1(targetInst); - if (updateValueIfChanged(targetNode)) { - return targetInst; - } -} - -function getTargetInstForChangeEvent(topLevelType, targetInst) { - if (topLevelType === 'topChange') { - return targetInst; - } -} - -/** - * 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. - isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9); -} - -/** - * (For IE <=9) Starts tracking propertychange events on the passed-in element - * and override the value property so that we can distinguish user events from - * value changes in JS. - */ -function startWatchingForValueChange(target, targetInst) { - activeElement = target; - activeElementInst = targetInst; - activeElement.attachEvent('onpropertychange', handlePropertyChange); -} - -/** - * (For IE <=9) Removes the event listeners from the currently-tracked element, - * if any exists. - */ -function stopWatchingForValueChange() { - if (!activeElement) { - return; - } - activeElement.detachEvent('onpropertychange', handlePropertyChange); - activeElement = null; - activeElementInst = null; -} - -/** - * (For IE <=9) Handles a propertychange event, sending a `change` event if - * the value of the active element has changed. - */ -function handlePropertyChange(nativeEvent) { - if (nativeEvent.propertyName !== 'value') { - return; - } - if (getInstIfValueChanged(activeElementInst)) { - manualDispatchChangeEvent(nativeEvent); - } -} - -function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { - if (topLevelType === 'topFocus') { - // In IE9, propertychange fires for most input events but is buggy and - // doesn't fire when text is deleted, but conveniently, selectionchange - // appears to fire in all of the remaining cases so we catch those and - // forward the event if the value has changed - // In either case, we don't want to call the event handler if the value - // is changed from JS so we redefine a setter for `.value` that updates - // our activeElementValue variable, allowing us to ignore those changes - // - // stopWatching() should be a noop here but we call it just in case we - // missed a blur event somehow. - stopWatchingForValueChange(); - startWatchingForValueChange(target, targetInst); - } else if (topLevelType === 'topBlur') { - stopWatchingForValueChange(); - } -} - -// For IE8 and IE9. -function getTargetInstForInputEventPolyfill(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. - return getInstIfValueChanged(activeElementInst); - } -} - -/** - * SECTION: handle `click` event - */ -function shouldUseClickEvent(elem) { - // Use the `click` event to detect changes to checkbox and radio inputs. - // This approach works across all browsers, whereas `change` does not fire - // until `blur` in IE8. - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); -} - -function getTargetInstForClickEvent(topLevelType, targetInst) { - if (topLevelType === 'topClick') { - return getInstIfValueChanged(targetInst); - } -} - -function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) { - if (topLevelType === 'topInput' || topLevelType === 'topChange') { - return getInstIfValueChanged(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 - setDefaultValue(node, 'number', node.value); -} - -/** - * This plugin creates an `onChange` event that normalizes change events - * across form elements. This event fires at a time when it's possible to - * change the element's value without seeing a flicker. - * - * Supported elements are: - * - input (see `isTextInputElement`) - * - textarea - * - select - */ -var ChangeEventPlugin = { - eventTypes: eventTypes$1, - - _isInputEventSupported: isInputEventSupported, - - extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window; - - var getTargetInstFunc = void 0, - handleEventFunc = void 0; - if (shouldUseChangeEvent(targetNode)) { - getTargetInstFunc = getTargetInstForChangeEvent; - } else if (isTextInputElement(targetNode)) { - if (isInputEventSupported) { - getTargetInstFunc = getTargetInstForInputOrChangeEvent; - } else { - getTargetInstFunc = getTargetInstForInputEventPolyfill; - handleEventFunc = handleEventsForInputEventPolyfill; - } - } else if (shouldUseClickEvent(targetNode)) { - getTargetInstFunc = getTargetInstForClickEvent; - } - - if (getTargetInstFunc) { - var inst = getTargetInstFunc(topLevelType, targetInst); - if (inst) { - var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget); - return event; - } - } - - if (handleEventFunc) { - handleEventFunc(topLevelType, targetNode, targetInst); - } - - // When blurring, set the value attribute for number inputs - if (topLevelType === 'topBlur') { - handleControlledInputBlur(targetInst, targetNode); - } - } -}; - -/** - * Module that is injectable into `EventPluginHub`, that specifies a - * deterministic ordering of `EventPlugin`s. A convenient way to reason about - * plugins, without having to package every one of them. This is better than - * having plugins be ordered in the same order that they are injected because - * that ordering would be influenced by the packaging order. - * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that - * preventing default on events is convenient in `SimpleEventPlugin` handlers. - */ -var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; - -var SyntheticUIEvent = SyntheticEvent$1.extend({ - view: null, - detail: null -}); - -/** - * Translation from modifier key to the associated property in the event. - * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers - */ - -var modifierKeyToProp = { - Alt: 'altKey', - Control: 'ctrlKey', - Meta: 'metaKey', - Shift: 'shiftKey' -}; - -// IE8 does not implement getModifierState so we simply map it to the only -// modifier keys exposed by the event itself, does not support Lock-keys. -// Currently, all major browsers except Chrome seems to support Lock-keys. -function modifierStateGetter(keyArg) { - var syntheticEvent = this; - var nativeEvent = syntheticEvent.nativeEvent; - if (nativeEvent.getModifierState) { - return nativeEvent.getModifierState(keyArg); - } - var keyProp = modifierKeyToProp[keyArg]; - return keyProp ? !!nativeEvent[keyProp] : false; -} - -function getEventModifierState(nativeEvent) { - return modifierStateGetter; -} - -/** - * @interface MouseEvent - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var SyntheticMouseEvent = SyntheticUIEvent.extend({ - screenX: null, - screenY: null, - clientX: null, - clientY: null, - pageX: null, - pageY: null, - ctrlKey: null, - shiftKey: null, - altKey: null, - metaKey: null, - getModifierState: getEventModifierState, - button: null, - buttons: null, - relatedTarget: function (event) { - return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); - } -}); - -var eventTypes$2 = { - mouseEnter: { - registrationName: 'onMouseEnter', - dependencies: ['topMouseOut', 'topMouseOver'] - }, - mouseLeave: { - registrationName: 'onMouseLeave', - dependencies: ['topMouseOut', 'topMouseOver'] - } -}; - -var EnterLeaveEventPlugin = { - eventTypes: eventTypes$2, - - /** - * For almost every interaction we care about, there will be both a top-level - * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that - * we do not extract duplicate events. However, moving the mouse into the - * browser from outside will not fire a `mouseout` event. In this case, we use - * the `mouseover` top-level event. - */ - extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { - if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { - return null; - } - if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { - // Must not be a mouse in or mouse out - ignoring. - return null; - } - - var win = void 0; - if (nativeEventTarget.window === nativeEventTarget) { - // `nativeEventTarget` is probably a window object. - win = nativeEventTarget; - } else { - // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. - var doc = nativeEventTarget.ownerDocument; - if (doc) { - win = doc.defaultView || doc.parentWindow; - } else { - win = window; - } - } - - var from = void 0; - var to = void 0; - if (topLevelType === 'topMouseOut') { - from = targetInst; - var related = nativeEvent.relatedTarget || nativeEvent.toElement; - to = related ? getClosestInstanceFromNode(related) : null; - } else { - // Moving to a node from outside the window. - from = null; - to = targetInst; - } - - if (from === to) { - // Nothing pertains to our managed components. - return null; - } - - var fromNode = from == null ? win : getNodeFromInstance$1(from); - var toNode = to == null ? win : getNodeFromInstance$1(to); - - var leave = SyntheticMouseEvent.getPooled(eventTypes$2.mouseLeave, from, nativeEvent, nativeEventTarget); - leave.type = 'mouseleave'; - leave.target = fromNode; - leave.relatedTarget = toNode; - - var enter = SyntheticMouseEvent.getPooled(eventTypes$2.mouseEnter, to, nativeEvent, nativeEventTarget); - enter.type = 'mouseenter'; - enter.target = toNode; - enter.relatedTarget = fromNode; - - accumulateEnterLeaveDispatches(leave, enter, from, to); - - return [leave, enter]; - } -}; - -/** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - -/** - * This API should be called `delete` but we'd have to make sure to always - * transform these to strings for IE support. When this transform is fully - * supported we can rename it. - */ - - -function get(key) { - return key._reactInternalFiber; -} - -function has(key) { - return key._reactInternalFiber !== undefined; -} - -function set(key, value) { - key._reactInternalFiber = value; -} - -// Don't change these two values. They're used by React Dev Tools. -var NoEffect = /* */0; -var PerformedWork = /* */1; - -// You can change the rest (and add more). -var Placement = /* */2; -var Update = /* */4; -var PlacementAndUpdate = /* */6; -var Deletion = /* */8; -var ContentReset = /* */16; -var Callback = /* */32; -var DidCapture = /* */64; -var Ref = /* */128; -var ErrLog = /* */256; -var Snapshot = /* */2048; - -// Union of all host effects -var HostEffectMask = /* */2559; - -var Incomplete = /* */512; -var ShouldCapture = /* */1024; - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; - -function isFiberMountedImpl(fiber) { - var node = fiber; - if (!fiber.alternate) { - // If there is no alternate, this might be a new tree that isn't inserted - // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node['return']) { - node = node['return']; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - } - } else { - while (node['return']) { - node = node['return']; - } - } - if (node.tag === HostRoot) { - // TODO: Check if this was a nested HostRoot when used with - // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree - // that has been unmounted. - return UNMOUNTED; -} - -function isFiberMounted(fiber) { - return isFiberMountedImpl(fiber) === MOUNTED; -} - -function isMounted(component) { - { - var owner = ReactCurrentOwner.current; - if (owner !== null && owner.tag === ClassComponent) { - var ownerFiber = owner; - var instance = ownerFiber.stateNode; - !instance._warnedAboutRefsInRender ? warning(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber) || 'A component') : void 0; - instance._warnedAboutRefsInRender = true; - } - } - - var fiber = get(component); - if (!fiber) { - return false; - } - return isFiberMountedImpl(fiber) === MOUNTED; -} - -function assertIsMounted(fiber) { - !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; -} - -function findCurrentFiberUsingSlowPath(fiber) { - var alternate = fiber.alternate; - if (!alternate) { - // If there is no alternate, then we only need to check if it is mounted. - var state = isFiberMountedImpl(fiber); - !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; - if (state === MOUNTING) { - return null; - } - return fiber; - } - // If we have two possible branches, we'll walk backwards up to the root - // to see what path the root points to. On the way we may hit one of the - // special cases and we'll deal with them. - var a = fiber; - var b = alternate; - while (true) { - var parentA = a['return']; - var parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) { - // We're at the root. - break; - } - - // If both copies of the parent fiber point to the same child, we can - // assume that the child is current. This happens when we bailout on low - // priority: the bailed out fiber's child reuses the current child. - if (parentA.child === parentB.child) { - var child = parentA.child; - while (child) { - if (child === a) { - // We've determined that A is the current branch. - assertIsMounted(parentA); - return fiber; - } - if (child === b) { - // We've determined that B is the current branch. - assertIsMounted(parentA); - return alternate; - } - child = child.sibling; - } - // We should never have an alternate for any mounting node. So the only - // way this could possibly happen is if this was unmounted, if at all. - invariant(false, 'Unable to find node on an unmounted component.'); - } - - if (a['return'] !== b['return']) { - // The return pointer of A and the return pointer of B point to different - // fibers. We assume that return pointers never criss-cross, so A must - // belong to the child set of A.return, and B must belong to the child - // set of B.return. - a = parentA; - b = parentB; - } else { - // The return pointers point to the same fiber. We'll have to use the - // default, slow path: scan the child sets of each parent alternate to see - // which child belongs to which set. - // - // Search parent A's child set - var didFindChild = false; - var _child = parentA.child; - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentA; - b = parentB; - break; - } - if (_child === b) { - didFindChild = true; - b = parentA; - a = parentB; - break; - } - _child = _child.sibling; - } - if (!didFindChild) { - // Search parent B's child set - _child = parentB.child; - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentB; - b = parentA; - break; - } - if (_child === b) { - didFindChild = true; - b = parentB; - a = parentA; - break; - } - _child = _child.sibling; - } - !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0; - } - } - - !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0; - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0; - if (a.stateNode.current === a) { - // We've determined that A is the current branch. - return fiber; - } - // Otherwise B has to be current branch. - return alternate; -} - -function findCurrentHostFiber(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - if (!currentParent) { - return null; - } - - // Next we'll drill down this component to find the first HostComponent/Text. - var node = currentParent; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } else if (node.child) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === currentParent) { - return null; - } - while (!node.sibling) { - if (!node['return'] || node['return'] === currentParent) { - return null; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. - // eslint-disable-next-line no-unreachable - return null; -} - -function findCurrentHostFiberWithNoPortals(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - if (!currentParent) { - return null; - } - - // Next we'll drill down this component to find the first HostComponent/Text. - var node = currentParent; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } else if (node.child && node.tag !== HostPortal) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === currentParent) { - return null; - } - while (!node.sibling) { - if (!node['return'] || node['return'] === currentParent) { - return null; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. - // eslint-disable-next-line no-unreachable - return null; -} - -function addEventBubbleListener(element, eventType, listener) { - element.addEventListener(eventType, listener, false); -} - -function addEventCaptureListener(element, eventType, listener) { - element.addEventListener(eventType, listener, true); -} - -/** - * @interface Event - * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface - * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent - */ -var SyntheticAnimationEvent = SyntheticEvent$1.extend({ - animationName: null, - elapsedTime: null, - pseudoElement: null -}); - -/** - * @interface Event - * @see http://www.w3.org/TR/clipboard-apis/ - */ -var SyntheticClipboardEvent = SyntheticEvent$1.extend({ - clipboardData: function (event) { - return 'clipboardData' in event ? event.clipboardData : window.clipboardData; - } -}); - -/** - * @interface FocusEvent - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var SyntheticFocusEvent = SyntheticUIEvent.extend({ - relatedTarget: null -}); - -/** - * `charCode` represents the actual "character code" and is safe to use with - * `String.fromCharCode`. As such, only keys that correspond to printable - * characters produce a valid `charCode`, the only exception to this is Enter. - * The Tab-key is considered non-printable and does not have a `charCode`, - * presumably because it does not produce a tab-character in browsers. - * - * @param {object} nativeEvent Native browser event. - * @return {number} Normalized `charCode` property. - */ -function getEventCharCode(nativeEvent) { - var charCode = void 0; - var keyCode = nativeEvent.keyCode; - - if ('charCode' in nativeEvent) { - charCode = nativeEvent.charCode; - - // FF does not set `charCode` for the Enter-key, check against `keyCode`. - if (charCode === 0 && keyCode === 13) { - charCode = 13; - } - } else { - // IE8 does not implement `charCode`, but `keyCode` has the correct value. - charCode = keyCode; - } - - // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux) - // report Enter as charCode 10 when ctrl is pressed. - if (charCode === 10) { - charCode = 13; - } - - // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. - // Must not discard the (non-)printable Enter-key. - if (charCode >= 32 || charCode === 13) { - return charCode; - } - - return 0; -} - -/** - * Normalization of deprecated HTML5 `key` values - * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names - */ -var normalizeKey = { - Esc: 'Escape', - Spacebar: ' ', - Left: 'ArrowLeft', - Up: 'ArrowUp', - Right: 'ArrowRight', - Down: 'ArrowDown', - Del: 'Delete', - Win: 'OS', - Menu: 'ContextMenu', - Apps: 'ContextMenu', - Scroll: 'ScrollLock', - MozPrintableKey: 'Unidentified' -}; - -/** - * Translation from legacy `keyCode` to HTML5 `key` - * Only special keys supported, all others depend on keyboard layout or browser - * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names - */ -var translateToKey = { - '8': 'Backspace', - '9': 'Tab', - '12': 'Clear', - '13': 'Enter', - '16': 'Shift', - '17': 'Control', - '18': 'Alt', - '19': 'Pause', - '20': 'CapsLock', - '27': 'Escape', - '32': ' ', - '33': 'PageUp', - '34': 'PageDown', - '35': 'End', - '36': 'Home', - '37': 'ArrowLeft', - '38': 'ArrowUp', - '39': 'ArrowRight', - '40': 'ArrowDown', - '45': 'Insert', - '46': 'Delete', - '112': 'F1', - '113': 'F2', - '114': 'F3', - '115': 'F4', - '116': 'F5', - '117': 'F6', - '118': 'F7', - '119': 'F8', - '120': 'F9', - '121': 'F10', - '122': 'F11', - '123': 'F12', - '144': 'NumLock', - '145': 'ScrollLock', - '224': 'Meta' -}; - -/** - * @param {object} nativeEvent Native browser event. - * @return {string} Normalized `key` property. - */ -function getEventKey(nativeEvent) { - if (nativeEvent.key) { - // Normalize inconsistent values reported by browsers due to - // implementations of a working draft specification. - - // FireFox implements `key` but returns `MozPrintableKey` for all - // printable characters (normalized to `Unidentified`), ignore it. - var key = normalizeKey[nativeEvent.key] || nativeEvent.key; - if (key !== 'Unidentified') { - return key; - } - } - - // Browser does not implement `key`, polyfill as much of it as we can. - if (nativeEvent.type === 'keypress') { - var charCode = getEventCharCode(nativeEvent); - - // The enter-key is technically both printable and non-printable and can - // thus be captured by `keypress`, no other non-printable key should. - return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); - } - if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { - // While user keyboard layout determines the actual meaning of each - // `keyCode` value, almost all function keys have a universal value. - return translateToKey[nativeEvent.keyCode] || 'Unidentified'; - } - return ''; -} - -/** - * @interface KeyboardEvent - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var SyntheticKeyboardEvent = SyntheticUIEvent.extend({ - key: getEventKey, - location: null, - ctrlKey: null, - shiftKey: null, - altKey: null, - metaKey: null, - repeat: null, - locale: null, - getModifierState: getEventModifierState, - // Legacy Interface - charCode: function (event) { - // `charCode` is the result of a KeyPress event and represents the value of - // the actual printable character. - - // KeyPress is deprecated, but its replacement is not yet final and not - // implemented in any major browser. Only KeyPress has charCode. - if (event.type === 'keypress') { - return getEventCharCode(event); - } - return 0; - }, - keyCode: function (event) { - // `keyCode` is the result of a KeyDown/Up event and represents the value of - // physical keyboard key. - - // The actual meaning of the value depends on the users' keyboard layout - // which cannot be detected. Assuming that it is a US keyboard layout - // provides a surprisingly accurate mapping for US and European users. - // Due to this, it is left to the user to implement at this time. - if (event.type === 'keydown' || event.type === 'keyup') { - return event.keyCode; - } - return 0; - }, - which: function (event) { - // `which` is an alias for either `keyCode` or `charCode` depending on the - // type of the event. - if (event.type === 'keypress') { - return getEventCharCode(event); - } - if (event.type === 'keydown' || event.type === 'keyup') { - return event.keyCode; - } - return 0; - } -}); - -/** - * @interface DragEvent - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var SyntheticDragEvent = SyntheticMouseEvent.extend({ - dataTransfer: null -}); - -/** - * @interface TouchEvent - * @see http://www.w3.org/TR/touch-events/ - */ -var SyntheticTouchEvent = SyntheticUIEvent.extend({ - touches: null, - targetTouches: null, - changedTouches: null, - altKey: null, - metaKey: null, - ctrlKey: null, - shiftKey: null, - getModifierState: getEventModifierState -}); - -/** - * @interface Event - * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- - * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent - */ -var SyntheticTransitionEvent = SyntheticEvent$1.extend({ - propertyName: null, - elapsedTime: null, - pseudoElement: null -}); - -/** - * @interface WheelEvent - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var SyntheticWheelEvent = SyntheticMouseEvent.extend({ - deltaX: function (event) { - return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). - 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; - }, - deltaY: function (event) { - return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). - 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). - 'wheelDelta' in event ? -event.wheelDelta : 0; - }, - - deltaZ: null, - - // Browsers without "deltaMode" is reporting in raw wheel delta where one - // notch on the scroll is always +/- 120, roughly equivalent to pixels. - // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or - // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. - deltaMode: null -}); - -/** - * Turns - * ['abort', ...] - * into - * eventTypes = { - * 'abort': { - * phasedRegistrationNames: { - * bubbled: 'onAbort', - * captured: 'onAbortCapture', - * }, - * dependencies: ['topAbort'], - * }, - * ... - * }; - * topLevelEventsToDispatchConfig = { - * 'topAbort': { sameConfig } - * }; - */ -var interactiveEventTypeNames = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'rateChange', 'reset', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange']; -var nonInteractiveEventTypeNames = ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseMove', 'mouseOut', 'mouseOver', 'playing', 'progress', 'scroll', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'toggle', 'touchMove', 'transitionEnd', 'waiting', 'wheel']; - -var eventTypes$4 = {}; -var topLevelEventsToDispatchConfig = {}; - -function addEventTypeNameToConfig(event, isInteractive) { - var capitalizedEvent = event[0].toUpperCase() + event.slice(1); - var onEvent = 'on' + capitalizedEvent; - var topEvent = 'top' + capitalizedEvent; - - var type = { - phasedRegistrationNames: { - bubbled: onEvent, - captured: onEvent + 'Capture' - }, - dependencies: [topEvent], - isInteractive: isInteractive - }; - eventTypes$4[event] = type; - topLevelEventsToDispatchConfig[topEvent] = type; -} - -interactiveEventTypeNames.forEach(function (eventTypeName) { - addEventTypeNameToConfig(eventTypeName, true); -}); -nonInteractiveEventTypeNames.forEach(function (eventTypeName) { - addEventTypeNameToConfig(eventTypeName, false); -}); - -// Only used in DEV for exhaustiveness validation. -var knownHTMLTopLevelTypes = ['topAbort', 'topCancel', 'topCanPlay', 'topCanPlayThrough', 'topClose', 'topDurationChange', 'topEmptied', 'topEncrypted', 'topEnded', 'topError', 'topInput', 'topInvalid', 'topLoad', 'topLoadedData', 'topLoadedMetadata', 'topLoadStart', 'topPause', 'topPlay', 'topPlaying', 'topProgress', 'topRateChange', 'topReset', 'topSeeked', 'topSeeking', 'topStalled', 'topSubmit', 'topSuspend', 'topTimeUpdate', 'topToggle', 'topVolumeChange', 'topWaiting']; - -var SimpleEventPlugin = { - eventTypes: eventTypes$4, - - isInteractiveTopLevelEventType: function (topLevelType) { - var config = topLevelEventsToDispatchConfig[topLevelType]; - return config !== undefined && config.isInteractive === true; - }, - - - extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; - if (!dispatchConfig) { - return null; - } - var EventConstructor = void 0; - switch (topLevelType) { - case 'topKeyPress': - // Firefox creates a keypress event for function keys too. This removes - // the unwanted keypress events. Enter is however both printable and - // non-printable. One would expect Tab to be as well (but it isn't). - if (getEventCharCode(nativeEvent) === 0) { - return null; - } - /* falls through */ - case 'topKeyDown': - case 'topKeyUp': - EventConstructor = SyntheticKeyboardEvent; - break; - case 'topBlur': - case 'topFocus': - EventConstructor = SyntheticFocusEvent; - break; - case 'topClick': - // Firefox creates a click event on right mouse clicks. This removes the - // unwanted click events. - if (nativeEvent.button === 2) { - return null; - } - /* falls through */ - case 'topDoubleClick': - case 'topMouseDown': - case 'topMouseMove': - case 'topMouseUp': - // TODO: Disabled elements should not respond to mouse events - /* falls through */ - case 'topMouseOut': - case 'topMouseOver': - case 'topContextMenu': - EventConstructor = SyntheticMouseEvent; - break; - case 'topDrag': - case 'topDragEnd': - case 'topDragEnter': - case 'topDragExit': - case 'topDragLeave': - case 'topDragOver': - case 'topDragStart': - case 'topDrop': - EventConstructor = SyntheticDragEvent; - break; - case 'topTouchCancel': - case 'topTouchEnd': - case 'topTouchMove': - case 'topTouchStart': - EventConstructor = SyntheticTouchEvent; - break; - case 'topAnimationEnd': - case 'topAnimationIteration': - case 'topAnimationStart': - EventConstructor = SyntheticAnimationEvent; - break; - case 'topTransitionEnd': - EventConstructor = SyntheticTransitionEvent; - break; - case 'topScroll': - EventConstructor = SyntheticUIEvent; - break; - case 'topWheel': - EventConstructor = SyntheticWheelEvent; - break; - case 'topCopy': - case 'topCut': - case 'topPaste': - EventConstructor = SyntheticClipboardEvent; - break; - default: - { - if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) { - warning(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType); - } - } - // HTML Events - // @see http://www.w3.org/TR/html5/index.html#events-0 - EventConstructor = SyntheticEvent$1; - break; - } - var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); - accumulateTwoPhaseDispatches(event); - return event; - } -}; - -var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType; - - -var CALLBACK_BOOKKEEPING_POOL_SIZE = 10; -var callbackBookkeepingPool = []; - -/** - * Find the deepest React component completely containing the root of the - * passed-in instance (for use when entire React trees are nested within each - * other). If React trees are not nested, returns null. - */ -function findRootContainerNode(inst) { - // TODO: It may be a good idea to cache this to prevent unnecessary DOM - // traversal, but caching is difficult to do correctly without using a - // mutation observer to listen for all DOM changes. - while (inst['return']) { - inst = inst['return']; - } - if (inst.tag !== HostRoot) { - // This can happen if we're in a detached tree. - return null; - } - return inst.stateNode.containerInfo; -} - -// Used to store ancestor hierarchy in top level callback -function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { - if (callbackBookkeepingPool.length) { - var instance = callbackBookkeepingPool.pop(); - instance.topLevelType = topLevelType; - instance.nativeEvent = nativeEvent; - instance.targetInst = targetInst; - return instance; - } - return { - topLevelType: topLevelType, - nativeEvent: nativeEvent, - targetInst: targetInst, - ancestors: [] - }; -} - -function releaseTopLevelCallbackBookKeeping(instance) { - instance.topLevelType = null; - instance.nativeEvent = null; - instance.targetInst = null; - instance.ancestors.length = 0; - if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) { - callbackBookkeepingPool.push(instance); - } -} - -function handleTopLevel(bookKeeping) { - var targetInst = bookKeeping.targetInst; - - // Loop through the hierarchy, in case there's any nested components. - // It's important that we build the array of ancestors before calling any - // event handlers, because event handlers can modify the DOM, leading to - // inconsistencies with ReactMount's node cache. See #1105. - var ancestor = targetInst; - do { - if (!ancestor) { - bookKeeping.ancestors.push(ancestor); - break; - } - var root = findRootContainerNode(ancestor); - if (!root) { - break; - } - bookKeeping.ancestors.push(ancestor); - ancestor = getClosestInstanceFromNode(root); - } while (ancestor); - - for (var i = 0; i < bookKeeping.ancestors.length; i++) { - targetInst = bookKeeping.ancestors[i]; - runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); - } -} - -// TODO: can we stop exporting these? -var _enabled = true; - -function setEnabled(enabled) { - _enabled = !!enabled; -} - -function isEnabled() { - return _enabled; -} - -/** - * Traps top-level events by using event bubbling. - * - * @param {string} topLevelType Record from `BrowserEventConstants`. - * @param {string} handlerBaseName Event name (e.g. "click"). - * @param {object} element Element on which to attach listener. - * @return {?object} An object with a remove function which will forcefully - * remove the listener. - * @internal - */ -function trapBubbledEvent(topLevelType, handlerBaseName, element) { - if (!element) { - return null; - } - var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; - - addEventBubbleListener(element, handlerBaseName, - // Check if interactive and wrap in interactiveUpdates - dispatch.bind(null, topLevelType)); -} - -/** - * Traps a top-level event by using event capturing. - * - * @param {string} topLevelType Record from `BrowserEventConstants`. - * @param {string} handlerBaseName Event name (e.g. "click"). - * @param {object} element Element on which to attach listener. - * @return {?object} An object with a remove function which will forcefully - * remove the listener. - * @internal - */ -function trapCapturedEvent(topLevelType, handlerBaseName, element) { - if (!element) { - return null; - } - var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent; - - addEventCaptureListener(element, handlerBaseName, - // Check if interactive and wrap in interactiveUpdates - dispatch.bind(null, topLevelType)); -} - -function dispatchInteractiveEvent(topLevelType, nativeEvent) { - interactiveUpdates(dispatchEvent, topLevelType, nativeEvent); -} - -function dispatchEvent(topLevelType, nativeEvent) { - if (!_enabled) { - return; - } - - var nativeEventTarget = getEventTarget(nativeEvent); - var targetInst = getClosestInstanceFromNode(nativeEventTarget); - if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) { - // If we get an event (ex: img onload) before committing that - // component's mount, ignore it for now (that is, treat it as if it was an - // event on a non-React tree). We might also consider queueing events and - // dispatching them after the mount. - targetInst = null; - } - - var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst); - - try { - // Event queue being processed in the same cycle allows - // `preventDefault`. - batchedUpdates(handleTopLevel, bookKeeping); - } finally { - releaseTopLevelCallbackBookKeeping(bookKeeping); - } -} - -var ReactDOMEventListener = Object.freeze({ - get _enabled () { return _enabled; }, - setEnabled: setEnabled, - isEnabled: isEnabled, - trapBubbledEvent: trapBubbledEvent, - trapCapturedEvent: trapCapturedEvent, - dispatchEvent: dispatchEvent -}); - -/** - * Generate a mapping of standard vendor prefixes using the defined style property and event name. - * - * @param {string} styleProp - * @param {string} eventName - * @returns {object} - */ -function makePrefixMap(styleProp, eventName) { - var prefixes = {}; - - prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); - prefixes['Webkit' + styleProp] = 'webkit' + eventName; - prefixes['Moz' + styleProp] = 'moz' + eventName; - prefixes['ms' + styleProp] = 'MS' + eventName; - prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); - - return prefixes; -} - -/** - * A list of event names to a configurable list of vendor prefixes. - */ -var vendorPrefixes = { - animationend: makePrefixMap('Animation', 'AnimationEnd'), - animationiteration: makePrefixMap('Animation', 'AnimationIteration'), - animationstart: makePrefixMap('Animation', 'AnimationStart'), - transitionend: makePrefixMap('Transition', 'TransitionEnd') -}; - -/** - * Event names that have already been detected and prefixed (if applicable). - */ -var prefixedEventNames = {}; - -/** - * Element to check for prefixes on. - */ -var style = {}; - -/** - * Bootstrap if a DOM exists. - */ -if (ExecutionEnvironment.canUseDOM) { - style = document.createElement('div').style; - - // On some platforms, in particular some releases of Android 4.x, - // the un-prefixed "animation" and "transition" properties are defined on the - // style object but the events that fire will still be prefixed, so we need - // to check if the un-prefixed events are usable, and if not remove them from the map. - if (!('AnimationEvent' in window)) { - delete vendorPrefixes.animationend.animation; - delete vendorPrefixes.animationiteration.animation; - delete vendorPrefixes.animationstart.animation; - } - - // Same as above - if (!('TransitionEvent' in window)) { - delete vendorPrefixes.transitionend.transition; - } -} - -/** - * Attempts to determine the correct vendor prefixed event name. - * - * @param {string} eventName - * @returns {string} - */ -function getVendorPrefixedEventName(eventName) { - if (prefixedEventNames[eventName]) { - return prefixedEventNames[eventName]; - } else if (!vendorPrefixes[eventName]) { - return eventName; - } - - var prefixMap = vendorPrefixes[eventName]; - - for (var styleProp in prefixMap) { - if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { - return prefixedEventNames[eventName] = prefixMap[styleProp]; - } - } - - return eventName; -} - -/** - * Types of raw signals from the browser caught at the top level. - * - * For events like 'submit' or audio/video events which don't consistently - * bubble (which we trap at a lower node than `document`), binding - * at `document` would cause duplicate events so we don't include them here. - */ -var topLevelTypes = { - topAnimationEnd: getVendorPrefixedEventName('animationend'), - topAnimationIteration: getVendorPrefixedEventName('animationiteration'), - topAnimationStart: getVendorPrefixedEventName('animationstart'), - topBlur: 'blur', - topCancel: 'cancel', - topChange: 'change', - topClick: 'click', - topClose: 'close', - topCompositionEnd: 'compositionend', - topCompositionStart: 'compositionstart', - topCompositionUpdate: 'compositionupdate', - topContextMenu: 'contextmenu', - topCopy: 'copy', - topCut: 'cut', - topDoubleClick: 'dblclick', - topDrag: 'drag', - topDragEnd: 'dragend', - topDragEnter: 'dragenter', - topDragExit: 'dragexit', - topDragLeave: 'dragleave', - topDragOver: 'dragover', - topDragStart: 'dragstart', - topDrop: 'drop', - topFocus: 'focus', - topInput: 'input', - topKeyDown: 'keydown', - topKeyPress: 'keypress', - topKeyUp: 'keyup', - topLoad: 'load', - topLoadStart: 'loadstart', - topMouseDown: 'mousedown', - topMouseMove: 'mousemove', - topMouseOut: 'mouseout', - topMouseOver: 'mouseover', - topMouseUp: 'mouseup', - topPaste: 'paste', - topScroll: 'scroll', - topSelectionChange: 'selectionchange', - topTextInput: 'textInput', - topToggle: 'toggle', - topTouchCancel: 'touchcancel', - topTouchEnd: 'touchend', - topTouchMove: 'touchmove', - topTouchStart: 'touchstart', - topTransitionEnd: getVendorPrefixedEventName('transitionend'), - topWheel: 'wheel' -}; - -// There are so many media events, it makes sense to just -// maintain a list of them. Note these aren't technically -// "top-level" since they don't bubble. We should come up -// with a better naming convention if we come to refactoring -// the event system. -var mediaEventTypes = { - topAbort: 'abort', - topCanPlay: 'canplay', - topCanPlayThrough: 'canplaythrough', - topDurationChange: 'durationchange', - topEmptied: 'emptied', - topEncrypted: 'encrypted', - topEnded: 'ended', - topError: 'error', - topLoadedData: 'loadeddata', - topLoadedMetadata: 'loadedmetadata', - topLoadStart: 'loadstart', - topPause: 'pause', - topPlay: 'play', - topPlaying: 'playing', - topProgress: 'progress', - topRateChange: 'ratechange', - topSeeked: 'seeked', - topSeeking: 'seeking', - topStalled: 'stalled', - topSuspend: 'suspend', - topTimeUpdate: 'timeupdate', - topVolumeChange: 'volumechange', - topWaiting: 'waiting' -}; - -/** - * Summary of `ReactBrowserEventEmitter` event handling: - * - * - Top-level delegation is used to trap most native browser events. This - * may only occur in the main thread and is the responsibility of - * ReactDOMEventListener, which is injected and can therefore support - * pluggable event sources. This is the only work that occurs in the main - * thread. - * - * - We normalize and de-duplicate events to account for browser quirks. This - * may be done in the worker thread. - * - * - Forward these native events (with the associated top-level type used to - * trap it) to `EventPluginHub`, which in turn will ask plugins if they want - * to extract any synthetic events. - * - * - The `EventPluginHub` will then process each event by annotating them with - * "dispatches", a sequence of listeners and IDs that care about that event. - * - * - The `EventPluginHub` then dispatches the events. - * - * Overview of React and the event system: - * - * +------------+ . - * | DOM | . - * +------------+ . - * | . - * v . - * +------------+ . - * | ReactEvent | . - * | Listener | . - * +------------+ . +-----------+ - * | . +--------+|SimpleEvent| - * | . | |Plugin | - * +-----|------+ . v +-----------+ - * | | | . +--------------+ +------------+ - * | +-----------.--->|EventPluginHub| | Event | - * | | . | | +-----------+ | Propagators| - * | ReactEvent | . | | |TapEvent | |------------| - * | Emitter | . | |<---+|Plugin | |other plugin| - * | | . | | +-----------+ | utilities | - * | +-----------.--->| | +------------+ - * | | | . +--------------+ - * +-----|------+ . ^ +-----------+ - * | . | |Enter/Leave| - * + . +-------+|Plugin | - * +-------------+ . +-----------+ - * | application | . - * |-------------| . - * | | . - * | | . - * +-------------+ . - * . - * React Core . General Purpose Event Plugin System - */ - -var alreadyListeningTo = {}; -var reactTopListenersCounter = 0; - -/** - * To ensure no conflicts with other potential React instances on the page - */ -var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2); - -function getListeningForDocument(mountAt) { - // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` - // directly. - if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { - mountAt[topListenersIDKey] = reactTopListenersCounter++; - alreadyListeningTo[mountAt[topListenersIDKey]] = {}; - } - return alreadyListeningTo[mountAt[topListenersIDKey]]; -} - -/** - * We listen for bubbled touch events on the document object. - * - * Firefox v8.01 (and possibly others) exhibited strange behavior when - * mounting `onmousemove` events at some node that was not the document - * element. The symptoms were that if your mouse is not moving over something - * contained within that mount point (for example on the background) the - * top-level listeners for `onmousemove` won't be called. However, if you - * register the `mousemove` on the document object, then it will of course - * catch all `mousemove`s. This along with iOS quirks, justifies restricting - * top-level listeners to the document object only, at least for these - * movement types of events and possibly all events. - * - * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - * - * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but - * they bubble to document. - * - * @param {string} registrationName Name of listener (e.g. `onClick`). - * @param {object} contentDocumentHandle Document which owns the container - */ -function listenTo(registrationName, contentDocumentHandle) { - var mountAt = contentDocumentHandle; - var isListening = getListeningForDocument(mountAt); - var dependencies = registrationNameDependencies[registrationName]; - - for (var i = 0; i < dependencies.length; i++) { - var dependency = dependencies[i]; - if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { - if (dependency === 'topScroll') { - trapCapturedEvent('topScroll', 'scroll', mountAt); - } else if (dependency === 'topFocus' || dependency === 'topBlur') { - trapCapturedEvent('topFocus', 'focus', mountAt); - trapCapturedEvent('topBlur', 'blur', mountAt); - - // to make sure blur and focus event listeners are only attached once - isListening.topBlur = true; - isListening.topFocus = true; - } else if (dependency === 'topCancel') { - if (isEventSupported('cancel', true)) { - trapCapturedEvent('topCancel', 'cancel', mountAt); - } - isListening.topCancel = true; - } else if (dependency === 'topClose') { - if (isEventSupported('close', true)) { - trapCapturedEvent('topClose', 'close', mountAt); - } - isListening.topClose = true; - } else if (topLevelTypes.hasOwnProperty(dependency)) { - trapBubbledEvent(dependency, topLevelTypes[dependency], mountAt); - } - - isListening[dependency] = true; - } - } -} - -function isListeningToAllDependencies(registrationName, mountAt) { - var isListening = getListeningForDocument(mountAt); - var dependencies = registrationNameDependencies[registrationName]; - for (var i = 0; i < dependencies.length; i++) { - var dependency = dependencies[i]; - if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { - return false; - } - } - return true; -} - -/** - * Given any node return the first leaf node without children. - * - * @param {DOMElement|DOMTextNode} node - * @return {DOMElement|DOMTextNode} - */ -function getLeafNode(node) { - while (node && node.firstChild) { - node = node.firstChild; - } - return node; -} - -/** - * Get the next sibling within a container. This will walk up the - * DOM if a node's siblings have been exhausted. - * - * @param {DOMElement|DOMTextNode} node - * @return {?DOMElement|DOMTextNode} - */ -function getSiblingNode(node) { - while (node) { - if (node.nextSibling) { - return node.nextSibling; - } - node = node.parentNode; - } -} - -/** - * Get object describing the nodes which contain characters at offset. - * - * @param {DOMElement|DOMTextNode} root - * @param {number} offset - * @return {?object} - */ -function getNodeForCharacterOffset(root, offset) { - var node = getLeafNode(root); - var nodeStart = 0; - var nodeEnd = 0; - - while (node) { - if (node.nodeType === TEXT_NODE) { - nodeEnd = nodeStart + node.textContent.length; - - if (nodeStart <= offset && nodeEnd >= offset) { - return { - node: node, - offset: offset - nodeStart - }; - } - - nodeStart = nodeEnd; - } - - node = getLeafNode(getSiblingNode(node)); - } -} - -/** - * @param {DOMElement} outerNode - * @return {?object} - */ -function getOffsets(outerNode) { - var selection = window.getSelection && window.getSelection(); - - if (!selection || selection.rangeCount === 0) { - return null; - } - - var anchorNode = selection.anchorNode, - anchorOffset = selection.anchorOffset, - focusNode = selection.focusNode, - focusOffset = selection.focusOffset; - - // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the - // up/down buttons on an . Anonymous divs do not seem to - // expose properties, triggering a "Permission denied error" if any of its - // properties are accessed. The only seemingly possible way to avoid erroring - // is to access a property that typically works for non-anonymous divs and - // catch any error that may otherwise arise. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 - - try { - /* eslint-disable no-unused-expressions */ - anchorNode.nodeType; - focusNode.nodeType; - /* eslint-enable no-unused-expressions */ - } catch (e) { - return null; - } - - return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); -} - -/** - * Returns {start, end} where `start` is the character/codepoint index of - * (anchorNode, anchorOffset) within the textContent of `outerNode`, and - * `end` is the index of (focusNode, focusOffset). - * - * Returns null if you pass in garbage input but we should probably just crash. - * - * Exported only for testing. - */ -function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) { - var length = 0; - var start = -1; - var end = -1; - var indexWithinAnchor = 0; - var indexWithinFocus = 0; - var node = outerNode; - var parentNode = null; - - outer: while (true) { - var next = null; - - while (true) { - if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) { - start = length + anchorOffset; - } - if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) { - end = length + focusOffset; - } - - if (node.nodeType === TEXT_NODE) { - length += node.nodeValue.length; - } - - if ((next = node.firstChild) === null) { - break; - } - // Moving from `node` to its first child `next`. - parentNode = node; - node = next; - } - - while (true) { - if (node === outerNode) { - // If `outerNode` has children, this is always the second time visiting - // it. If it has no children, this is still the first loop, and the only - // valid selection is anchorNode and focusNode both equal to this node - // and both offsets 0, in which case we will have handled above. - break outer; - } - if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { - start = length; - } - if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { - end = length; - } - if ((next = node.nextSibling) !== null) { - break; - } - node = parentNode; - parentNode = node.parentNode; - } - - // Moving from `node` to its next sibling `next`. - node = next; - } - - if (start === -1 || end === -1) { - // This should never happen. (Would happen if the anchor/focus nodes aren't - // actually inside the passed-in node.) - return null; - } - - return { - start: start, - end: end - }; -} - -/** - * In modern non-IE browsers, we can support both forward and backward - * selections. - * - * Note: IE10+ supports the Selection object, but it does not support - * the `extend` method, which means that even in modern IE, it's not possible - * to programmatically create a backward selection. Thus, for all IE - * versions, we use the old IE API to create our selections. - * - * @param {DOMElement|DOMTextNode} node - * @param {object} offsets - */ -function setOffsets(node, offsets) { - if (!window.getSelection) { - return; - } - - var selection = window.getSelection(); - var length = node[getTextContentAccessor()].length; - var start = Math.min(offsets.start, length); - var end = offsets.end === undefined ? start : Math.min(offsets.end, length); - - // IE 11 uses modern selection, but doesn't support the extend method. - // Flip backward selections, so we can set with a single range. - if (!selection.extend && start > end) { - var temp = end; - end = start; - start = temp; - } - - var startMarker = getNodeForCharacterOffset(node, start); - var endMarker = getNodeForCharacterOffset(node, end); - - if (startMarker && endMarker) { - if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { - return; - } - var range = document.createRange(); - range.setStart(startMarker.node, startMarker.offset); - selection.removeAllRanges(); - - if (start > end) { - selection.addRange(range); - selection.extend(endMarker.node, endMarker.offset); - } else { - range.setEnd(endMarker.node, endMarker.offset); - selection.addRange(range); - } - } -} - -function isInDocument(node) { - return containsNode(document.documentElement, node); -} - -/** - * @ReactInputSelection: React input selection module. Based on Selection.js, - * but modified to be suitable for react and has a couple of bug fixes (doesn't - * assume buttons have range selections allowed). - * Input selection module for React. - */ - -function hasSelectionCapabilities(elem) { - var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); - return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); -} - -function getSelectionInformation() { - var focusedElem = getActiveElement(); - return { - focusedElem: focusedElem, - selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null - }; -} - -/** - * @restoreSelection: If any selection information was potentially lost, - * restore it. This is useful when performing operations that could remove dom - * nodes and place them back in, resulting in focus being lost. - */ -function restoreSelection(priorSelectionInformation) { - var curFocusedElem = getActiveElement(); - var priorFocusedElem = priorSelectionInformation.focusedElem; - var priorSelectionRange = priorSelectionInformation.selectionRange; - if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { - if (hasSelectionCapabilities(priorFocusedElem)) { - setSelection(priorFocusedElem, priorSelectionRange); - } - - // Focusing a node can change the scroll position, which is undesirable - var ancestors = []; - var ancestor = priorFocusedElem; - while (ancestor = ancestor.parentNode) { - if (ancestor.nodeType === ELEMENT_NODE) { - ancestors.push({ - element: ancestor, - left: ancestor.scrollLeft, - top: ancestor.scrollTop - }); - } - } - - priorFocusedElem.focus(); - - for (var i = 0; i < ancestors.length; i++) { - var info = ancestors[i]; - info.element.scrollLeft = info.left; - info.element.scrollTop = info.top; - } - } -} - -/** - * @getSelection: Gets the selection bounds of a focused textarea, input or - * contentEditable node. - * -@input: Look up selection bounds of this input - * -@return {start: selectionStart, end: selectionEnd} - */ -function getSelection$1(input) { - var selection = void 0; - - if ('selectionStart' in input) { - // Modern browser with input or textarea. - selection = { - start: input.selectionStart, - end: input.selectionEnd - }; - } else { - // Content editable or old IE textarea. - selection = getOffsets(input); - } - - return selection || { start: 0, end: 0 }; -} - -/** - * @setSelection: Sets the selection bounds of a textarea or input and focuses - * the input. - * -@input Set selection bounds of this input or textarea - * -@offsets Object of same form that is returned from get* - */ -function setSelection(input, offsets) { - var start = offsets.start, - end = offsets.end; - - if (end === undefined) { - end = start; - } - - if ('selectionStart' in input) { - input.selectionStart = start; - input.selectionEnd = Math.min(end, input.value.length); - } else { - setOffsets(input, offsets); - } -} - -var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; - -var eventTypes$3 = { - select: { - phasedRegistrationNames: { - bubbled: 'onSelect', - captured: 'onSelectCapture' - }, - dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] - } -}; - -var activeElement$1 = null; -var activeElementInst$1 = null; -var lastSelection = null; -var mouseDown = false; - -/** - * Get an object which is a unique representation of the current selection. - * - * The return value will not be consistent across nodes or browsers, but - * two identical selections on the same node will return identical objects. - * - * @param {DOMElement} node - * @return {object} - */ -function getSelection(node) { - if ('selectionStart' in node && hasSelectionCapabilities(node)) { - return { - start: node.selectionStart, - end: node.selectionEnd - }; - } else if (window.getSelection) { - var selection = window.getSelection(); - return { - anchorNode: selection.anchorNode, - anchorOffset: selection.anchorOffset, - focusNode: selection.focusNode, - focusOffset: selection.focusOffset - }; - } -} - -/** - * Poll selection to see whether it's changed. - * - * @param {object} nativeEvent - * @return {?SyntheticEvent} - */ -function constructSelectEvent(nativeEvent, nativeEventTarget) { - // Ensure we have the right element, and that the user is not dragging a - // selection (this matches native `select` event behavior). In HTML5, select - // fires only on input and textarea thus if there's no focused element we - // won't dispatch. - if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement()) { - return null; - } - - // Only fire when selection has actually changed. - var currentSelection = getSelection(activeElement$1); - if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { - lastSelection = currentSelection; - - var syntheticEvent = SyntheticEvent$1.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget); - - syntheticEvent.type = 'select'; - syntheticEvent.target = activeElement$1; - - accumulateTwoPhaseDispatches(syntheticEvent); - - return syntheticEvent; - } - - return null; -} - -/** - * This plugin creates an `onSelect` event that normalizes select events - * across form elements. - * - * Supported elements are: - * - input (see `isTextInputElement`) - * - textarea - * - contentEditable - * - * This differs from native browser implementations in the following ways: - * - Fires on contentEditable fields as well as inputs. - * - Fires for collapsed selection. - * - Fires after user input. - */ -var SelectEventPlugin = { - eventTypes: eventTypes$3, - - extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : nativeEventTarget.nodeType === DOCUMENT_NODE ? nativeEventTarget : nativeEventTarget.ownerDocument; - // Track whether all listeners exists for this plugin. If none exist, we do - // not extract events. See #3639. - if (!doc || !isListeningToAllDependencies('onSelect', doc)) { - return null; - } - - var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window; - - switch (topLevelType) { - // Track the input node that has focus. - case 'topFocus': - if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { - activeElement$1 = targetNode; - activeElementInst$1 = targetInst; - lastSelection = null; - } - break; - case 'topBlur': - activeElement$1 = null; - activeElementInst$1 = null; - lastSelection = null; - break; - // Don't fire the event while the user is dragging. This matches the - // semantics of the native select event. - case 'topMouseDown': - mouseDown = true; - break; - case 'topContextMenu': - case 'topMouseUp': - mouseDown = false; - return constructSelectEvent(nativeEvent, nativeEventTarget); - // Chrome and IE fire non-standard event when selection is changed (and - // sometimes when it hasn't). IE's event fires out of order with respect - // to key and input events on deletion, so we discard it. - // - // Firefox doesn't support selectionchange, so check selection status - // after each key entry. The selection changes after keydown and before - // keyup, but we check on keydown as well in the case of holding down a - // key, when multiple keydown events are fired but only one keyup is. - // This is also our approach for IE handling, for the reason above. - case 'topSelectionChange': - if (skipSelectionChangeEvent) { - break; - } - // falls through - case 'topKeyDown': - case 'topKeyUp': - return constructSelectEvent(nativeEvent, nativeEventTarget); - } - - return null; - } -}; - -/** - * Inject modules for resolving DOM hierarchy and plugin ordering. - */ -injection.injectEventPluginOrder(DOMEventPluginOrder); -injection$1.injectComponentTree(ReactDOMComponentTree); - -/** - * Some important event plugins included by default (without having to require - * them). - */ -injection.injectEventPluginsByName({ - SimpleEventPlugin: SimpleEventPlugin, - EnterLeaveEventPlugin: EnterLeaveEventPlugin, - ChangeEventPlugin: ChangeEventPlugin, - SelectEventPlugin: SelectEventPlugin, - BeforeInputEventPlugin: BeforeInputEventPlugin -}); - -// Max 31 bit integer. The max integer size in V8 for 32-bit systems. -// Math.pow(2, 30) - 1 -// 0b111111111111111111111111111111 -var MAX_SIGNED_31_BIT_INT = 1073741823; - -// TODO: Use an opaque type once ESLint et al support the syntax - - -var NoWork = 0; -var Sync = 1; -var Never = MAX_SIGNED_31_BIT_INT; - -var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = 2; - -// 1 unit of expiration time represents 10ms. -function msToExpirationTime(ms) { - // Always add an offset so that we don't clash with the magic number for NoWork. - return (ms / UNIT_SIZE | 0) + MAGIC_NUMBER_OFFSET; -} - -function expirationTimeToMs(expirationTime) { - return (expirationTime - MAGIC_NUMBER_OFFSET) * UNIT_SIZE; -} - -function ceiling(num, precision) { - return ((num / precision | 0) + 1) * precision; -} - -function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { - return ceiling(currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE); -} - -var NoContext = 0; -var AsyncMode = 1; -var StrictMode = 2; - -var hasBadMapPolyfill = void 0; - -{ - hasBadMapPolyfill = false; - try { - var nonExtensibleObject = Object.preventExtensions({}); - var testMap = new Map([[nonExtensibleObject, null]]); - var testSet = new Set([nonExtensibleObject]); - // This is necessary for Rollup to not consider these unused. - // https://github.com/rollup/rollup/issues/1771 - // TODO: we can remove these if Rollup fixes the bug. - testMap.set(0, 0); - testSet.add(0); - } catch (e) { - // TODO: Consider warning about bad polyfills - hasBadMapPolyfill = true; - } -} - -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. - - -var debugCounter = void 0; - -{ - debugCounter = 1; -} - -function FiberNode(tag, pendingProps, key, mode) { - // Instance - this.tag = tag; - this.key = key; - this.type = null; - this.stateNode = null; - - // Fiber - this['return'] = null; - this.child = null; - this.sibling = null; - this.index = 0; - - this.ref = null; - - this.pendingProps = pendingProps; - this.memoizedProps = null; - this.updateQueue = null; - this.memoizedState = null; - - this.mode = mode; - - // Effects - this.effectTag = NoEffect; - this.nextEffect = null; - - this.firstEffect = null; - this.lastEffect = null; - - this.expirationTime = NoWork; - - this.alternate = null; - - { - this._debugID = debugCounter++; - this._debugSource = null; - this._debugOwner = null; - this._debugIsCurrentlyTiming = false; - if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { - Object.preventExtensions(this); - } - } -} - -// This is a constructor function, rather than a POJO constructor, still -// please ensure we do the following: -// 1) Nobody should add any instance methods on this. Instance methods can be -// more difficult to predict when they get optimized and they are almost -// never inlined properly in static compilers. -// 2) Nobody should rely on `instanceof Fiber` for type testing. We should -// always know when it is a fiber. -// 3) We might want to experiment with using numeric keys since they are easier -// to optimize in a non-JIT environment. -// 4) We can easily go from a constructor to a createFiber object literal if that -// is faster. -// 5) It should be easy to port this to a C struct and keep a C implementation -// compatible. -var createFiber = function (tag, pendingProps, key, mode) { - // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors - return new FiberNode(tag, pendingProps, key, mode); -}; - -function shouldConstruct(Component) { - return !!(Component.prototype && Component.prototype.isReactComponent); -} - -// This is used to create an alternate fiber to do work on. -function createWorkInProgress(current, pendingProps, expirationTime) { - var workInProgress = current.alternate; - if (workInProgress === null) { - // We use a double buffering pooling technique because we know that we'll - // only ever need at most two versions of a tree. We pool the "other" unused - // node that we're free to reuse. This is lazily created to avoid allocating - // extra objects for things that are never updated. It also allow us to - // reclaim the extra memory if needed. - workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); - workInProgress.type = current.type; - workInProgress.stateNode = current.stateNode; - - { - // DEV-only fields - workInProgress._debugID = current._debugID; - workInProgress._debugSource = current._debugSource; - workInProgress._debugOwner = current._debugOwner; - } - - workInProgress.alternate = current; - current.alternate = workInProgress; - } else { - workInProgress.pendingProps = pendingProps; - - // We already have an alternate. - // Reset the effect tag. - workInProgress.effectTag = NoEffect; - - // The effect list is no longer valid. - workInProgress.nextEffect = null; - workInProgress.firstEffect = null; - workInProgress.lastEffect = null; - } - - workInProgress.expirationTime = expirationTime; - - workInProgress.child = current.child; - workInProgress.memoizedProps = current.memoizedProps; - workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // These will be overridden during the parent's reconciliation - workInProgress.sibling = current.sibling; - workInProgress.index = current.index; - workInProgress.ref = current.ref; - - return workInProgress; -} - -function createHostRootFiber(isAsync) { - var mode = isAsync ? AsyncMode | StrictMode : NoContext; - return createFiber(HostRoot, null, null, mode); -} - -function createFiberFromElement(element, mode, expirationTime) { - var owner = null; - { - owner = element._owner; - } - - var fiber = void 0; - var type = element.type; - var key = element.key; - var pendingProps = element.props; - - var fiberTag = void 0; - if (typeof type === 'function') { - fiberTag = shouldConstruct(type) ? ClassComponent : IndeterminateComponent; - } else if (typeof type === 'string') { - fiberTag = HostComponent; - } else { - switch (type) { - case REACT_FRAGMENT_TYPE: - return createFiberFromFragment(pendingProps.children, mode, expirationTime, key); - case REACT_ASYNC_MODE_TYPE: - fiberTag = Mode; - mode |= AsyncMode | StrictMode; - break; - case REACT_STRICT_MODE_TYPE: - fiberTag = Mode; - mode |= StrictMode; - break; - case REACT_CALL_TYPE: - fiberTag = CallComponent; - break; - case REACT_RETURN_TYPE: - fiberTag = ReturnComponent; - break; - default: - { - if (typeof type === 'object' && type !== null) { - switch (type.$$typeof) { - case REACT_PROVIDER_TYPE: - fiberTag = ContextProvider; - break; - case REACT_CONTEXT_TYPE: - // This is a consumer - fiberTag = ContextConsumer; - break; - case REACT_FORWARD_REF_TYPE: - fiberTag = ForwardRef; - break; - default: - if (typeof type.tag === 'number') { - // Currently assumed to be a continuation and therefore is a - // fiber already. - // TODO: The yield system is currently broken for updates in - // some cases. The reified yield stores a fiber, but we don't - // know which fiber that is; the current or a workInProgress? - // When the continuation gets rendered here we don't know if we - // can reuse that fiber or if we need to clone it. There is - // probably a clever way to restructure this. - fiber = type; - fiber.pendingProps = pendingProps; - fiber.expirationTime = expirationTime; - return fiber; - } else { - throwOnInvalidElementType(type, owner); - } - break; - } - } else { - throwOnInvalidElementType(type, owner); - } - } - } - } - - fiber = createFiber(fiberTag, pendingProps, key, mode); - fiber.type = type; - fiber.expirationTime = expirationTime; - - { - fiber._debugSource = element._source; - fiber._debugOwner = element._owner; - } - - return fiber; -} - -function throwOnInvalidElementType(type, owner) { - var info = ''; - { - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; - } - var ownerName = owner ? getComponentName(owner) : null; - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - } - invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info); -} - -function createFiberFromFragment(elements, mode, expirationTime, key) { - var fiber = createFiber(Fragment, elements, key, mode); - fiber.expirationTime = expirationTime; - return fiber; -} - -function createFiberFromText(content, mode, expirationTime) { - var fiber = createFiber(HostText, content, null, mode); - fiber.expirationTime = expirationTime; - return fiber; -} - -function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoContext); - fiber.type = 'DELETED'; - return fiber; -} - -function createFiberFromPortal(portal, mode, expirationTime) { - var pendingProps = portal.children !== null ? portal.children : []; - var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); - fiber.expirationTime = expirationTime; - fiber.stateNode = { - containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates - implementation: portal.implementation - }; - return fiber; -} - -// Used for stashing WIP properties to replay failed work in DEV. -function assignFiberPropertiesInDEV(target, source) { - if (target === null) { - // This Fiber's initial properties will always be overwritten. - // We only use a Fiber to ensure the same hidden class so DEV isn't slow. - target = createFiber(IndeterminateComponent, null, null, NoContext); - } - - // This is intentionally written as a list of all properties. - // We tried to use Object.assign() instead but this is called in - // the hottest path, and Object.assign() was too slow: - // https://github.com/facebook/react/issues/12502 - // This code is DEV-only so size is not a concern. - - target.tag = source.tag; - target.key = source.key; - target.type = source.type; - target.stateNode = source.stateNode; - target['return'] = source['return']; - target.child = source.child; - target.sibling = source.sibling; - target.index = source.index; - target.ref = source.ref; - target.pendingProps = source.pendingProps; - target.memoizedProps = source.memoizedProps; - target.updateQueue = source.updateQueue; - target.memoizedState = source.memoizedState; - target.mode = source.mode; - target.effectTag = source.effectTag; - target.nextEffect = source.nextEffect; - target.firstEffect = source.firstEffect; - target.lastEffect = source.lastEffect; - target.expirationTime = source.expirationTime; - target.alternate = source.alternate; - target._debugID = source._debugID; - target._debugSource = source._debugSource; - target._debugOwner = source._debugOwner; - target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming; - return target; -} - -// TODO: This should be lifted into the renderer. - - -function createFiberRoot(containerInfo, isAsync, hydrate) { - // Cyclic construction. This cheats the type system right now because - // stateNode is any. - var uninitializedFiber = createHostRootFiber(isAsync); - var root = { - current: uninitializedFiber, - containerInfo: containerInfo, - pendingChildren: null, - pendingCommitExpirationTime: NoWork, - finishedWork: null, - context: null, - pendingContext: null, - hydrate: hydrate, - remainingExpirationTime: NoWork, - firstBatch: null, - nextScheduledRoot: null - }; - uninitializedFiber.stateNode = root; - return root; -} - -var onCommitFiberRoot = null; -var onCommitFiberUnmount = null; -var hasLoggedError = false; - -function catchErrors(fn) { - return function (arg) { - try { - return fn(arg); - } catch (err) { - if (true && !hasLoggedError) { - hasLoggedError = true; - warning(false, 'React DevTools encountered an error: %s', err); - } - } - }; -} - -function injectInternals(internals) { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { - // No DevTools - return false; - } - var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; - if (hook.isDisabled) { - // This isn't a real property on the hook, but it can be set to opt out - // of DevTools integration and associated warnings and logs. - // https://github.com/facebook/react/issues/3877 - return true; - } - if (!hook.supportsFiber) { - { - warning(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools'); - } - // DevTools exists, even though it doesn't support Fiber. - return true; - } - try { - var rendererID = hook.inject(internals); - // We have successfully injected, so now it is safe to set up hooks. - onCommitFiberRoot = catchErrors(function (root) { - return hook.onCommitFiberRoot(rendererID, root); - }); - onCommitFiberUnmount = catchErrors(function (fiber) { - return hook.onCommitFiberUnmount(rendererID, fiber); - }); - } catch (err) { - // Catch all errors because it is unsafe to throw during initialization. - { - warning(false, 'React DevTools encountered an error: %s.', err); - } - } - // DevTools exists - return true; -} - -function onCommitRoot(root) { - if (typeof onCommitFiberRoot === 'function') { - onCommitFiberRoot(root); - } -} - -function onCommitUnmount(fiber) { - if (typeof onCommitFiberUnmount === 'function') { - onCommitFiberUnmount(fiber); - } -} - -/** - * Forked from fbjs/warning: - * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js - * - * Only change is we use console.warn instead of console.error, - * and do nothing when 'console' is not supported. - * This really simplifies the code. - * --- - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var lowPriorityWarning = function () {}; - -{ - var printWarning = function (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.warn(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) {} - }; - - lowPriorityWarning = function (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]; - } - - printWarning.apply(undefined, [format].concat(args)); - } - }; -} - -var lowPriorityWarning$1 = lowPriorityWarning; - -var ReactStrictModeWarnings = { - discardPendingWarnings: function () {}, - flushPendingDeprecationWarnings: function () {}, - flushPendingUnsafeLifecycleWarnings: function () {}, - recordDeprecationWarnings: function (fiber, instance) {}, - recordUnsafeLifecycleWarnings: function (fiber, instance) {} -}; - -{ - var LIFECYCLE_SUGGESTIONS = { - UNSAFE_componentWillMount: 'componentDidMount', - UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps', - UNSAFE_componentWillUpdate: 'componentDidUpdate' - }; - - var pendingComponentWillMountWarnings = []; - var pendingComponentWillReceivePropsWarnings = []; - var pendingComponentWillUpdateWarnings = []; - var pendingUnsafeLifecycleWarnings = new Map(); - - // Tracks components we have already warned about. - var didWarnAboutDeprecatedLifecycles = new Set(); - var didWarnAboutUnsafeLifecycles = new Set(); - - var setToSortedString = function (set) { - var array = []; - set.forEach(function (value) { - array.push(value); - }); - return array.sort().join(', '); - }; - - ReactStrictModeWarnings.discardPendingWarnings = function () { - pendingComponentWillMountWarnings = []; - pendingComponentWillReceivePropsWarnings = []; - pendingComponentWillUpdateWarnings = []; - pendingUnsafeLifecycleWarnings = new Map(); - }; - - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { - pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) { - var lifecyclesWarningMesages = []; - - Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) { - var lifecycleWarnings = lifecycleWarningsMap[lifecycle]; - if (lifecycleWarnings.length > 0) { - var componentNames = new Set(); - lifecycleWarnings.forEach(function (fiber) { - componentNames.add(getComponentName(fiber) || 'Component'); - didWarnAboutUnsafeLifecycles.add(fiber.type); - }); - - var formatted = lifecycle.replace('UNSAFE_', ''); - var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle]; - var sortedComponentNames = setToSortedString(componentNames); - - lifecyclesWarningMesages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames)); - } - }); - - if (lifecyclesWarningMesages.length > 0) { - var strictRootComponentStack = getStackAddendumByWorkInProgressFiber(strictRoot); - - warning(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMesages.join('\n\n')); - } - }); - - pendingUnsafeLifecycleWarnings = new Map(); - }; - - var getStrictRoot = function (fiber) { - var maybeStrictRoot = null; - - while (fiber !== null) { - if (fiber.mode & StrictMode) { - maybeStrictRoot = fiber; - } - - fiber = fiber['return']; - } - - return maybeStrictRoot; - }; - - ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () { - if (pendingComponentWillMountWarnings.length > 0) { - var uniqueNames = new Set(); - pendingComponentWillMountWarnings.forEach(function (fiber) { - uniqueNames.add(getComponentName(fiber) || 'Component'); - didWarnAboutDeprecatedLifecycles.add(fiber.type); - }); - - var sortedNames = setToSortedString(uniqueNames); - - lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames); - - pendingComponentWillMountWarnings = []; - } - - if (pendingComponentWillReceivePropsWarnings.length > 0) { - var _uniqueNames = new Set(); - pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { - _uniqueNames.add(getComponentName(fiber) || 'Component'); - didWarnAboutDeprecatedLifecycles.add(fiber.type); - }); - - var _sortedNames = setToSortedString(_uniqueNames); - - lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames); - - pendingComponentWillReceivePropsWarnings = []; - } - - if (pendingComponentWillUpdateWarnings.length > 0) { - var _uniqueNames2 = new Set(); - pendingComponentWillUpdateWarnings.forEach(function (fiber) { - _uniqueNames2.add(getComponentName(fiber) || 'Component'); - didWarnAboutDeprecatedLifecycles.add(fiber.type); - }); - - var _sortedNames2 = setToSortedString(_uniqueNames2); - - lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2); - - pendingComponentWillUpdateWarnings = []; - } - }; - - ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) { - // Dedup strategy: Warn once per component. - if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) { - return; - } - - // Don't warn about react-lifecycles-compat polyfilled components. - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { - pendingComponentWillMountWarnings.push(fiber); - } - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - pendingComponentWillReceivePropsWarnings.push(fiber); - } - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - pendingComponentWillUpdateWarnings.push(fiber); - } - }; - - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { - var strictRoot = getStrictRoot(fiber); - - // Dedup strategy: Warn once per component. - // This is difficult to track any other way since component names - // are often vague and are likely to collide between 3rd party libraries. - // An expand property is probably okay to use here since it's DEV-only, - // and will only be set in the event of serious warnings. - if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { - return; - } - - // Don't warn about react-lifecycles-compat polyfilled components. - // Note that it is sufficient to check for the presence of a - // single lifecycle, componentWillMount, with the polyfill flag. - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning === true) { - return; - } - - var warningsForRoot = void 0; - if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) { - warningsForRoot = { - UNSAFE_componentWillMount: [], - UNSAFE_componentWillReceiveProps: [], - UNSAFE_componentWillUpdate: [] - }; - - pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot); - } else { - warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot); - } - - var unsafeLifecycles = []; - if (typeof instance.componentWillMount === 'function' || typeof instance.UNSAFE_componentWillMount === 'function') { - unsafeLifecycles.push('UNSAFE_componentWillMount'); - } - if (typeof instance.componentWillReceiveProps === 'function' || typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - unsafeLifecycles.push('UNSAFE_componentWillReceiveProps'); - } - if (typeof instance.componentWillUpdate === 'function' || typeof instance.UNSAFE_componentWillUpdate === 'function') { - unsafeLifecycles.push('UNSAFE_componentWillUpdate'); - } - - if (unsafeLifecycles.length > 0) { - unsafeLifecycles.forEach(function (lifecycle) { - warningsForRoot[lifecycle].push(fiber); - }); - } - }; -} - -// Exports ReactDOM.createRoot -var enableUserTimingAPI = true; - -// Mutating mode (React DOM, React ART, React Native): -var enableMutatingReconciler = true; -// Experimental noop mode (currently unused): -var enableNoopReconciler = false; -// Experimental persistent mode (Fabric): -var enablePersistentReconciler = false; -// Experimental error-boundary API that can recover from errors within a single -// render phase -var enableGetDerivedStateFromCatch = false; -// Helps identify side effects in begin-phase lifecycle hooks and setState reducers: -var debugRenderPhaseSideEffects = false; - -// In some cases, StrictMode should also double-render lifecycles. -// This can be confusing for tests though, -// And it can be bad for performance in production. -// This feature flag can be used to control the behavior: -var debugRenderPhaseSideEffectsForStrictMode = true; - -// To preserve the "Pause on caught exceptions" behavior of the debugger, we -// replay the begin phase of a failed component inside invokeGuardedCallback. -var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; - -// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: -var warnAboutDeprecatedLifecycles = false; - -var alwaysUseRequestIdleCallbackPolyfill = false; - -// Only used in www builds. - -// Prefix measurements so that it's possible to filter them. -// Longer prefixes are hard to read in DevTools. -var reactEmoji = '\u269B'; -var warningEmoji = '\u26D4'; -var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; - -// Keep track of current fiber so that we know the path to unwind on pause. -// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? -var currentFiber = null; -// If we're in the middle of user code, which fiber and method is it? -// Reusing `currentFiber` would be confusing for this because user code fiber -// can change during commit phase too, but we don't need to unwind it (since -// lifecycles in the commit phase don't resemble a tree). -var currentPhase = null; -var currentPhaseFiber = null; -// Did lifecycle hook schedule an update? This is often a performance problem, -// so we will keep track of it, and include it in the report. -// Track commits caused by cascading updates. -var isCommitting = false; -var hasScheduledUpdateInCurrentCommit = false; -var hasScheduledUpdateInCurrentPhase = false; -var commitCountInCurrentWorkLoop = 0; -var effectCountInCurrentCommit = 0; -var isWaitingForCallback = false; -// During commits, we only show a measurement once per method name -// to avoid stretch the commit phase with measurement overhead. -var labelsInCurrentCommit = new Set(); - -var formatMarkName = function (markName) { - return reactEmoji + ' ' + markName; -}; - -var formatLabel = function (label, warning$$1) { - var prefix = warning$$1 ? warningEmoji + ' ' : reactEmoji + ' '; - var suffix = warning$$1 ? ' Warning: ' + warning$$1 : ''; - return '' + prefix + label + suffix; -}; - -var beginMark = function (markName) { - performance.mark(formatMarkName(markName)); -}; - -var clearMark = function (markName) { - performance.clearMarks(formatMarkName(markName)); -}; - -var endMark = function (label, markName, warning$$1) { - var formattedMarkName = formatMarkName(markName); - var formattedLabel = formatLabel(label, warning$$1); - try { - performance.measure(formattedLabel, formattedMarkName); - } catch (err) {} - // If previous mark was missing for some reason, this will throw. - // This could only happen if React crashed in an unexpected place earlier. - // Don't pile on with more errors. - - // Clear marks immediately to avoid growing buffer. - performance.clearMarks(formattedMarkName); - performance.clearMeasures(formattedLabel); -}; - -var getFiberMarkName = function (label, debugID) { - return label + ' (#' + debugID + ')'; -}; - -var getFiberLabel = function (componentName, isMounted, phase) { - if (phase === null) { - // These are composite component total time measurements. - return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']'; - } else { - // Composite component methods. - return componentName + '.' + phase; - } -}; - -var beginFiberMark = function (fiber, phase) { - var componentName = getComponentName(fiber) || 'Unknown'; - var debugID = fiber._debugID; - var isMounted = fiber.alternate !== null; - var label = getFiberLabel(componentName, isMounted, phase); - - if (isCommitting && labelsInCurrentCommit.has(label)) { - // During the commit phase, we don't show duplicate labels because - // there is a fixed overhead for every measurement, and we don't - // want to stretch the commit phase beyond necessary. - return false; - } - labelsInCurrentCommit.add(label); - - var markName = getFiberMarkName(label, debugID); - beginMark(markName); - return true; -}; - -var clearFiberMark = function (fiber, phase) { - var componentName = getComponentName(fiber) || 'Unknown'; - var debugID = fiber._debugID; - var isMounted = fiber.alternate !== null; - var label = getFiberLabel(componentName, isMounted, phase); - var markName = getFiberMarkName(label, debugID); - clearMark(markName); -}; - -var endFiberMark = function (fiber, phase, warning$$1) { - var componentName = getComponentName(fiber) || 'Unknown'; - var debugID = fiber._debugID; - var isMounted = fiber.alternate !== null; - var label = getFiberLabel(componentName, isMounted, phase); - var markName = getFiberMarkName(label, debugID); - endMark(label, markName, warning$$1); -}; - -var shouldIgnoreFiber = function (fiber) { - // Host components should be skipped in the timeline. - // We could check typeof fiber.type, but does this work with RN? - switch (fiber.tag) { - case HostRoot: - case HostComponent: - case HostText: - case HostPortal: - case CallComponent: - case ReturnComponent: - case Fragment: - case ContextProvider: - case ContextConsumer: - case Mode: - return true; - default: - return false; - } -}; - -var clearPendingPhaseMeasurement = function () { - if (currentPhase !== null && currentPhaseFiber !== null) { - clearFiberMark(currentPhaseFiber, currentPhase); - } - currentPhaseFiber = null; - currentPhase = null; - hasScheduledUpdateInCurrentPhase = false; -}; - -var pauseTimers = function () { - // Stops all currently active measurements so that they can be resumed - // if we continue in a later deferred loop from the same unit of work. - var fiber = currentFiber; - while (fiber) { - if (fiber._debugIsCurrentlyTiming) { - endFiberMark(fiber, null, null); - } - fiber = fiber['return']; - } -}; - -var resumeTimersRecursively = function (fiber) { - if (fiber['return'] !== null) { - resumeTimersRecursively(fiber['return']); - } - if (fiber._debugIsCurrentlyTiming) { - beginFiberMark(fiber, null); - } -}; - -var resumeTimers = function () { - // Resumes all measurements that were active during the last deferred loop. - if (currentFiber !== null) { - resumeTimersRecursively(currentFiber); - } -}; - -function recordEffect() { - if (enableUserTimingAPI) { - effectCountInCurrentCommit++; - } -} - -function recordScheduleUpdate() { - if (enableUserTimingAPI) { - if (isCommitting) { - hasScheduledUpdateInCurrentCommit = true; - } - if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') { - hasScheduledUpdateInCurrentPhase = true; - } - } -} - -function startRequestCallbackTimer() { - if (enableUserTimingAPI) { - if (supportsUserTiming && !isWaitingForCallback) { - isWaitingForCallback = true; - beginMark('(Waiting for async callback...)'); - } - } -} - -function stopRequestCallbackTimer(didExpire, expirationTime) { - if (enableUserTimingAPI) { - if (supportsUserTiming) { - isWaitingForCallback = false; - var warning$$1 = didExpire ? 'React was blocked by main thread' : null; - endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning$$1); - } - } -} - -function startWorkTimer(fiber) { - if (enableUserTimingAPI) { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // If we pause, this is the fiber to unwind from. - currentFiber = fiber; - if (!beginFiberMark(fiber, null)) { - return; - } - fiber._debugIsCurrentlyTiming = true; - } -} - -function cancelWorkTimer(fiber) { - if (enableUserTimingAPI) { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // Remember we shouldn't complete measurement for this fiber. - // Otherwise flamechart will be deep even for small updates. - fiber._debugIsCurrentlyTiming = false; - clearFiberMark(fiber, null); - } -} - -function stopWorkTimer(fiber) { - if (enableUserTimingAPI) { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // If we pause, its parent is the fiber to unwind from. - currentFiber = fiber['return']; - if (!fiber._debugIsCurrentlyTiming) { - return; - } - fiber._debugIsCurrentlyTiming = false; - endFiberMark(fiber, null, null); - } -} - -function stopFailedWorkTimer(fiber) { - if (enableUserTimingAPI) { - if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { - return; - } - // If we pause, its parent is the fiber to unwind from. - currentFiber = fiber['return']; - if (!fiber._debugIsCurrentlyTiming) { - return; - } - fiber._debugIsCurrentlyTiming = false; - var warning$$1 = 'An error was thrown inside this error boundary'; - endFiberMark(fiber, null, warning$$1); - } -} - -function startPhaseTimer(fiber, phase) { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - clearPendingPhaseMeasurement(); - if (!beginFiberMark(fiber, phase)) { - return; - } - currentPhaseFiber = fiber; - currentPhase = phase; - } -} - -function stopPhaseTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - if (currentPhase !== null && currentPhaseFiber !== null) { - var warning$$1 = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null; - endFiberMark(currentPhaseFiber, currentPhase, warning$$1); - } - currentPhase = null; - currentPhaseFiber = null; - } -} - -function startWorkLoopTimer(nextUnitOfWork) { - if (enableUserTimingAPI) { - currentFiber = nextUnitOfWork; - if (!supportsUserTiming) { - return; - } - commitCountInCurrentWorkLoop = 0; - // This is top level call. - // Any other measurements are performed within. - beginMark('(React Tree Reconciliation)'); - // Resume any measurements that were in progress during the last loop. - resumeTimers(); - } -} - -function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - var warning$$1 = null; - if (interruptedBy !== null) { - if (interruptedBy.tag === HostRoot) { - warning$$1 = 'A top-level update interrupted the previous render'; - } else { - var componentName = getComponentName(interruptedBy) || 'Unknown'; - warning$$1 = 'An update to ' + componentName + ' interrupted the previous render'; - } - } else if (commitCountInCurrentWorkLoop > 1) { - warning$$1 = 'There were cascading updates'; - } - commitCountInCurrentWorkLoop = 0; - var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; - // Pause any measurements until the next loop. - pauseTimers(); - endMark(label, '(React Tree Reconciliation)', warning$$1); - } -} - -function startCommitTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - isCommitting = true; - hasScheduledUpdateInCurrentCommit = false; - labelsInCurrentCommit.clear(); - beginMark('(Committing Changes)'); - } -} - -function stopCommitTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - - var warning$$1 = null; - if (hasScheduledUpdateInCurrentCommit) { - warning$$1 = 'Lifecycle hook scheduled a cascading update'; - } else if (commitCountInCurrentWorkLoop > 0) { - warning$$1 = 'Caused by a cascading update in earlier commit'; - } - hasScheduledUpdateInCurrentCommit = false; - commitCountInCurrentWorkLoop++; - isCommitting = false; - labelsInCurrentCommit.clear(); - - endMark('(Committing Changes)', '(Committing Changes)', warning$$1); - } -} - -function startCommitSnapshotEffectsTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - effectCountInCurrentCommit = 0; - beginMark('(Committing Snapshot Effects)'); - } -} - -function stopCommitSnapshotEffectsTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - var count = effectCountInCurrentCommit; - effectCountInCurrentCommit = 0; - endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null); - } -} - -function startCommitHostEffectsTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - effectCountInCurrentCommit = 0; - beginMark('(Committing Host Effects)'); - } -} - -function stopCommitHostEffectsTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - var count = effectCountInCurrentCommit; - effectCountInCurrentCommit = 0; - endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null); - } -} - -function startCommitLifeCyclesTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - effectCountInCurrentCommit = 0; - beginMark('(Calling Lifecycle Methods)'); - } -} - -function stopCommitLifeCyclesTimer() { - if (enableUserTimingAPI) { - if (!supportsUserTiming) { - return; - } - var count = effectCountInCurrentCommit; - effectCountInCurrentCommit = 0; - endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null); - } -} - -var didWarnUpdateInsideUpdate = void 0; - -{ - didWarnUpdateInsideUpdate = false; -} - -// Callbacks are not validated until invocation - - -// Singly linked-list of updates. When an update is scheduled, it is added to -// the queue of the current fiber and the work-in-progress fiber. The two queues -// are separate but they share a persistent structure. -// -// During reconciliation, updates are removed from the work-in-progress fiber, -// but they remain on the current fiber. That ensures that if a work-in-progress -// is aborted, the aborted updates are recovered by cloning from current. -// -// The work-in-progress queue is always a subset of the current queue. -// -// When the tree is committed, the work-in-progress becomes the current. - - -function createUpdateQueue(baseState) { - var queue = { - baseState: baseState, - expirationTime: NoWork, - first: null, - last: null, - callbackList: null, - hasForceUpdate: false, - isInitialized: false, - capturedValues: null - }; - { - queue.isProcessing = false; - } - return queue; -} - -function insertUpdateIntoQueue(queue, update) { - // Append the update to the end of the list. - if (queue.last === null) { - // Queue is empty - queue.first = queue.last = update; - } else { - queue.last.next = update; - queue.last = update; - } - if (queue.expirationTime === NoWork || queue.expirationTime > update.expirationTime) { - queue.expirationTime = update.expirationTime; - } -} - -var q1 = void 0; -var q2 = void 0; -function ensureUpdateQueues(fiber) { - q1 = q2 = null; - // We'll have at least one and at most two distinct update queues. - var alternateFiber = fiber.alternate; - var queue1 = fiber.updateQueue; - if (queue1 === null) { - // TODO: We don't know what the base state will be until we begin work. - // It depends on which fiber is the next current. Initialize with an empty - // base state, then set to the memoizedState when rendering. Not super - // happy with this approach. - queue1 = fiber.updateQueue = createUpdateQueue(null); - } - - var queue2 = void 0; - if (alternateFiber !== null) { - queue2 = alternateFiber.updateQueue; - if (queue2 === null) { - queue2 = alternateFiber.updateQueue = createUpdateQueue(null); - } - } else { - queue2 = null; - } - queue2 = queue2 !== queue1 ? queue2 : null; - - // Use module variables instead of returning a tuple - q1 = queue1; - q2 = queue2; -} - -function insertUpdateIntoFiber(fiber, update) { - ensureUpdateQueues(fiber); - var queue1 = q1; - var queue2 = q2; - - // Warn if an update is scheduled from inside an updater function. - { - if ((queue1.isProcessing || queue2 !== null && queue2.isProcessing) && !didWarnUpdateInsideUpdate) { - warning(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); - didWarnUpdateInsideUpdate = true; - } - } - - // If there's only one queue, add the update to that queue and exit. - if (queue2 === null) { - insertUpdateIntoQueue(queue1, update); - return; - } - - // If either queue is empty, we need to add to both queues. - if (queue1.last === null || queue2.last === null) { - insertUpdateIntoQueue(queue1, update); - insertUpdateIntoQueue(queue2, update); - return; - } - - // If both lists are not empty, the last update is the same for both lists - // because of structural sharing. So, we should only append to one of - // the lists. - insertUpdateIntoQueue(queue1, update); - // But we still need to update the `last` pointer of queue2. - queue2.last = update; -} - -function getUpdateExpirationTime(fiber) { - switch (fiber.tag) { - case HostRoot: - case ClassComponent: - var updateQueue = fiber.updateQueue; - if (updateQueue === null) { - return NoWork; - } - return updateQueue.expirationTime; - default: - return NoWork; - } -} - -function getStateFromUpdate(update, instance, prevState, props) { - var partialState = update.partialState; - if (typeof partialState === 'function') { - return partialState.call(instance, prevState, props); - } else { - return partialState; - } -} - -function processUpdateQueue(current, workInProgress, queue, instance, props, renderExpirationTime) { - if (current !== null && current.updateQueue === queue) { - // We need to create a work-in-progress queue, by cloning the current queue. - var currentQueue = queue; - queue = workInProgress.updateQueue = { - baseState: currentQueue.baseState, - expirationTime: currentQueue.expirationTime, - first: currentQueue.first, - last: currentQueue.last, - isInitialized: currentQueue.isInitialized, - capturedValues: currentQueue.capturedValues, - // These fields are no longer valid because they were already committed. - // Reset them. - callbackList: null, - hasForceUpdate: false - }; - } - - { - // Set this flag so we can warn if setState is called inside the update - // function of another setState. - queue.isProcessing = true; - } - - // Reset the remaining expiration time. If we skip over any updates, we'll - // increase this accordingly. - queue.expirationTime = NoWork; - - // TODO: We don't know what the base state will be until we begin work. - // It depends on which fiber is the next current. Initialize with an empty - // base state, then set to the memoizedState when rendering. Not super - // happy with this approach. - var state = void 0; - if (queue.isInitialized) { - state = queue.baseState; - } else { - state = queue.baseState = workInProgress.memoizedState; - queue.isInitialized = true; - } - var dontMutatePrevState = true; - var update = queue.first; - var didSkip = false; - while (update !== null) { - var updateExpirationTime = update.expirationTime; - if (updateExpirationTime > renderExpirationTime) { - // This update does not have sufficient priority. Skip it. - var remainingExpirationTime = queue.expirationTime; - if (remainingExpirationTime === NoWork || remainingExpirationTime > updateExpirationTime) { - // Update the remaining expiration time. - queue.expirationTime = updateExpirationTime; - } - if (!didSkip) { - didSkip = true; - queue.baseState = state; - } - // Continue to the next update. - update = update.next; - continue; - } - - // This update does have sufficient priority. - - // If no previous updates were skipped, drop this update from the queue by - // advancing the head of the list. - if (!didSkip) { - queue.first = update.next; - if (queue.first === null) { - queue.last = null; - } - } - - // Invoke setState callback an extra time to help detect side-effects. - // Ignore the return value in this case. - if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { - getStateFromUpdate(update, instance, state, props); - } - - // Process the update - var _partialState = void 0; - if (update.isReplace) { - state = getStateFromUpdate(update, instance, state, props); - dontMutatePrevState = true; - } else { - _partialState = getStateFromUpdate(update, instance, state, props); - if (_partialState) { - if (dontMutatePrevState) { - // $FlowFixMe: Idk how to type this properly. - state = _assign({}, state, _partialState); - } else { - state = _assign(state, _partialState); - } - dontMutatePrevState = false; - } - } - if (update.isForced) { - queue.hasForceUpdate = true; - } - if (update.callback !== null) { - // Append to list of callbacks. - var _callbackList = queue.callbackList; - if (_callbackList === null) { - _callbackList = queue.callbackList = []; - } - _callbackList.push(update); - } - if (update.capturedValue !== null) { - var _capturedValues = queue.capturedValues; - if (_capturedValues === null) { - queue.capturedValues = [update.capturedValue]; - } else { - _capturedValues.push(update.capturedValue); - } - } - update = update.next; - } - - if (queue.callbackList !== null) { - workInProgress.effectTag |= Callback; - } else if (queue.first === null && !queue.hasForceUpdate && queue.capturedValues === null) { - // The queue is empty. We can reset it. - workInProgress.updateQueue = null; - } - - if (!didSkip) { - didSkip = true; - queue.baseState = state; - } - - { - // No longer processing. - queue.isProcessing = false; - } - - return state; -} - -function commitCallbacks(queue, context) { - var callbackList = queue.callbackList; - if (callbackList === null) { - return; - } - // Set the list to null to make sure they don't get called more than once. - queue.callbackList = null; - for (var i = 0; i < callbackList.length; i++) { - var update = callbackList[i]; - var _callback = update.callback; - // This update might be processed again. Clear the callback so it's only - // called once. - update.callback = null; - !(typeof _callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback) : void 0; - _callback.call(context); - } -} - -var fakeInternalInstance = {}; -var isArray = Array.isArray; - -var didWarnAboutStateAssignmentForComponent = void 0; -var didWarnAboutUndefinedDerivedState = void 0; -var didWarnAboutUninitializedState = void 0; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; -var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; -var warnOnInvalidCallback$1 = void 0; - -{ - didWarnAboutStateAssignmentForComponent = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - - var didWarnOnInvalidCallback = new Set(); - - warnOnInvalidCallback$1 = function (callback, callerName) { - if (callback === null || typeof callback === 'function') { - return; - } - var key = callerName + '_' + callback; - if (!didWarnOnInvalidCallback.has(key)) { - didWarnOnInvalidCallback.add(key); - warning(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); - } - }; - - // This is so gross but it's at least non-critical and can be removed if - // it causes problems. This is meant to give a nicer error message for - // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, - // ...)) which otherwise throws a "_processChildContext is not a function" - // exception. - Object.defineProperty(fakeInternalInstance, '_processChildContext', { - enumerable: false, - value: function () { - invariant(false, '_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn\'t supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).'); - } - }); - Object.freeze(fakeInternalInstance); -} -function callGetDerivedStateFromCatch(ctor, capturedValues) { - var resultState = {}; - for (var i = 0; i < capturedValues.length; i++) { - var capturedValue = capturedValues[i]; - var error = capturedValue.value; - var partialState = ctor.getDerivedStateFromCatch.call(null, error); - if (partialState !== null && partialState !== undefined) { - _assign(resultState, partialState); - } - } - return resultState; -} - -var ReactFiberClassComponent = function (legacyContext, scheduleWork, computeExpirationForFiber, memoizeProps, memoizeState) { - var cacheContext = legacyContext.cacheContext, - getMaskedContext = legacyContext.getMaskedContext, - getUnmaskedContext = legacyContext.getUnmaskedContext, - isContextConsumer = legacyContext.isContextConsumer, - hasContextChanged = legacyContext.hasContextChanged; - - // Class component state updater - - var updater = { - isMounted: isMounted, - enqueueSetState: function (instance, partialState, callback) { - var fiber = get(instance); - callback = callback === undefined ? null : callback; - { - warnOnInvalidCallback$1(callback, 'setState'); - } - var expirationTime = computeExpirationForFiber(fiber); - var update = { - expirationTime: expirationTime, - partialState: partialState, - callback: callback, - isReplace: false, - isForced: false, - capturedValue: null, - next: null - }; - insertUpdateIntoFiber(fiber, update); - scheduleWork(fiber, expirationTime); - }, - enqueueReplaceState: function (instance, state, callback) { - var fiber = get(instance); - callback = callback === undefined ? null : callback; - { - warnOnInvalidCallback$1(callback, 'replaceState'); - } - var expirationTime = computeExpirationForFiber(fiber); - var update = { - expirationTime: expirationTime, - partialState: state, - callback: callback, - isReplace: true, - isForced: false, - capturedValue: null, - next: null - }; - insertUpdateIntoFiber(fiber, update); - scheduleWork(fiber, expirationTime); - }, - enqueueForceUpdate: function (instance, callback) { - var fiber = get(instance); - callback = callback === undefined ? null : callback; - { - warnOnInvalidCallback$1(callback, 'forceUpdate'); - } - var expirationTime = computeExpirationForFiber(fiber); - var update = { - expirationTime: expirationTime, - partialState: null, - callback: callback, - isReplace: false, - isForced: true, - capturedValue: null, - next: null - }; - insertUpdateIntoFiber(fiber, update); - scheduleWork(fiber, expirationTime); - } - }; - - function checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext) { - if (oldProps === null || workInProgress.updateQueue !== null && workInProgress.updateQueue.hasForceUpdate) { - // If the workInProgress already has an Update effect, return true - return true; - } - - var instance = workInProgress.stateNode; - var ctor = workInProgress.type; - if (typeof instance.shouldComponentUpdate === 'function') { - startPhaseTimer(workInProgress, 'shouldComponentUpdate'); - var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, newContext); - stopPhaseTimer(); - - { - !(shouldUpdate !== undefined) ? warning(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(workInProgress) || 'Component') : void 0; - } - - return shouldUpdate; - } - - if (ctor.prototype && ctor.prototype.isPureReactComponent) { - return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); - } - - return true; - } - - function checkClassInstance(workInProgress) { - var instance = workInProgress.stateNode; - var type = workInProgress.type; - { - var name = getComponentName(workInProgress) || 'Component'; - var renderPresent = instance.render; - - if (!renderPresent) { - if (type.prototype && typeof type.prototype.render === 'function') { - warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); - } else { - warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); - } - } - - var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state; - !noGetInitialStateOnES6 ? warning(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0; - var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved; - !noGetDefaultPropsOnES6 ? warning(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0; - var noInstancePropTypes = !instance.propTypes; - !noInstancePropTypes ? warning(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0; - var noInstanceContextTypes = !instance.contextTypes; - !noInstanceContextTypes ? warning(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0; - var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function'; - !noComponentShouldUpdate ? warning(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0; - if (type.prototype && type.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { - warning(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(workInProgress) || 'A pure component'); - } - var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function'; - !noComponentDidUnmount ? warning(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0; - var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function'; - !noComponentDidReceiveProps ? warning(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0; - var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function'; - !noComponentWillRecieveProps ? warning(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0; - var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function'; - !noUnsafeComponentWillRecieveProps ? warning(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0; - var hasMutatedProps = instance.props !== workInProgress.pendingProps; - !(instance.props === undefined || !hasMutatedProps) ? warning(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0; - var noInstanceDefaultProps = !instance.defaultProps; - !noInstanceDefaultProps ? warning(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0; - - if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(type)) { - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(type); - warning(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(workInProgress)); - } - - var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function'; - !noInstanceGetDerivedStateFromProps ? warning(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0; - var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromCatch !== 'function'; - !noInstanceGetDerivedStateFromCatch ? warning(false, '%s: getDerivedStateFromCatch() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0; - var noStaticGetSnapshotBeforeUpdate = typeof type.getSnapshotBeforeUpdate !== 'function'; - !noStaticGetSnapshotBeforeUpdate ? warning(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0; - var _state = instance.state; - if (_state && (typeof _state !== 'object' || isArray(_state))) { - warning(false, '%s.state: must be set to an object or null', name); - } - if (typeof instance.getChildContext === 'function') { - !(typeof type.childContextTypes === 'object') ? warning(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0; - } - } - } - - function resetInputPointers(workInProgress, instance) { - instance.props = workInProgress.memoizedProps; - instance.state = workInProgress.memoizedState; - } - - function adoptClassInstance(workInProgress, instance) { - instance.updater = updater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates - set(instance, workInProgress); - { - instance._reactInternalInstance = fakeInternalInstance; - } - } - - function constructClassInstance(workInProgress, props) { - var ctor = workInProgress.type; - var unmaskedContext = getUnmaskedContext(workInProgress); - var needsContext = isContextConsumer(workInProgress); - var context = needsContext ? getMaskedContext(workInProgress, unmaskedContext) : emptyObject; - - // Instantiate twice to help detect side-effects. - if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { - new ctor(props, context); // eslint-disable-line no-new - } - - var instance = new ctor(props, context); - var state = instance.state !== null && instance.state !== undefined ? instance.state : null; - adoptClassInstance(workInProgress, instance); - - { - if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { - var componentName = getComponentName(workInProgress) || 'Component'; - if (!didWarnAboutUninitializedState.has(componentName)) { - didWarnAboutUninitializedState.add(componentName); - warning(false, '%s: Did not properly initialize state during construction. ' + 'Expected state to be an object, but it was %s.', componentName, instance.state === null ? 'null' : 'undefined'); - } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Warn about these lifecycles if they are present. - // Don't warn about react-lifecycles-compat polyfilled methods though. - if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { - var foundWillMountName = null; - var foundWillReceivePropsName = null; - var foundWillUpdateName = null; - if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { - foundWillMountName = 'componentWillMount'; - } else if (typeof instance.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount'; - } - if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { - foundWillReceivePropsName = 'componentWillReceiveProps'; - } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; - } - if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { - foundWillUpdateName = 'componentWillUpdate'; - } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate'; - } - if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { - var _componentName = getComponentName(workInProgress) || 'Component'; - var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; - if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { - didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); - warning(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : ''); - } - } - } - } - - workInProgress.memoizedState = state; - - var partialState = callGetDerivedStateFromProps(workInProgress, instance, props, state); - - if (partialState !== null && partialState !== undefined) { - // Render-phase updates (like this) should not be added to the update queue, - // So that multiple render passes do not enqueue multiple updates. - // Instead, just synchronously merge the returned state into the instance. - workInProgress.memoizedState = _assign({}, workInProgress.memoizedState, partialState); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // ReactFiberContext usually updates this cache but can't for newly-created instances. - if (needsContext) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return instance; - } - - function callComponentWillMount(workInProgress, instance) { - startPhaseTimer(workInProgress, 'componentWillMount'); - var oldState = instance.state; - - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - - stopPhaseTimer(); - - if (oldState !== instance.state) { - { - warning(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress) || 'Component'); - } - updater.enqueueReplaceState(instance, instance.state, null); - } - } - - function callComponentWillReceiveProps(workInProgress, instance, newProps, newContext) { - var oldState = instance.state; - startPhaseTimer(workInProgress, 'componentWillReceiveProps'); - if (typeof instance.componentWillReceiveProps === 'function') { - instance.componentWillReceiveProps(newProps, newContext); - } - if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { - instance.UNSAFE_componentWillReceiveProps(newProps, newContext); - } - stopPhaseTimer(); - - if (instance.state !== oldState) { - { - var componentName = getComponentName(workInProgress) || 'Component'; - if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { - didWarnAboutStateAssignmentForComponent.add(componentName); - warning(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); - } - } - updater.enqueueReplaceState(instance, instance.state, null); - } - } - - function callGetDerivedStateFromProps(workInProgress, instance, nextProps, prevState) { - var type = workInProgress.type; - - - if (typeof type.getDerivedStateFromProps === 'function') { - if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { - // Invoke method an extra time to help detect side-effects. - type.getDerivedStateFromProps.call(null, nextProps, prevState); - } - - var partialState = type.getDerivedStateFromProps.call(null, nextProps, prevState); - - { - if (partialState === undefined) { - var componentName = getComponentName(workInProgress) || 'Component'; - if (!didWarnAboutUndefinedDerivedState.has(componentName)) { - didWarnAboutUndefinedDerivedState.add(componentName); - warning(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); - } - } - } - - return partialState; - } - } - - // Invokes the mount life-cycles on a previously never rendered instance. - function mountClassInstance(workInProgress, renderExpirationTime) { - var ctor = workInProgress.type; - var current = workInProgress.alternate; - - { - checkClassInstance(workInProgress); - } - - var instance = workInProgress.stateNode; - var props = workInProgress.pendingProps; - var unmaskedContext = getUnmaskedContext(workInProgress); - - instance.props = props; - instance.state = workInProgress.memoizedState; - instance.refs = emptyObject; - instance.context = getMaskedContext(workInProgress, unmaskedContext); - - { - if (workInProgress.mode & StrictMode) { - ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); - } - - if (warnAboutDeprecatedLifecycles) { - ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance); - } - } - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's - // process them now. - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null) { - instance.state = processUpdateQueue(current, workInProgress, updateQueue, instance, props, renderExpirationTime); - } - } - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - } - - function resumeMountClassInstance(workInProgress, renderExpirationTime) { - var ctor = workInProgress.type; - var instance = workInProgress.stateNode; - resetInputPointers(workInProgress, instance); - - var oldProps = workInProgress.memoizedProps; - var newProps = workInProgress.pendingProps; - var oldContext = instance.context; - var newUnmaskedContext = getUnmaskedContext(workInProgress); - var newContext = getMaskedContext(workInProgress, newUnmaskedContext); - - var hasNewLifecycles = typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; - - // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (oldProps !== newProps || oldContext !== newContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); - } - } - - // Compute the next state using the memoized state and the update queue. - var oldState = workInProgress.memoizedState; - // TODO: Previous state can be null. - var newState = void 0; - var derivedStateFromCatch = void 0; - if (workInProgress.updateQueue !== null) { - newState = processUpdateQueue(null, workInProgress, workInProgress.updateQueue, instance, newProps, renderExpirationTime); - - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null && updateQueue.capturedValues !== null && enableGetDerivedStateFromCatch && typeof ctor.getDerivedStateFromCatch === 'function') { - var capturedValues = updateQueue.capturedValues; - // Don't remove these from the update queue yet. We need them in - // finishClassComponent. Do the reset there. - // TODO: This is awkward. Refactor class components. - // updateQueue.capturedValues = null; - derivedStateFromCatch = callGetDerivedStateFromCatch(ctor, capturedValues); - } - } else { - newState = oldState; - } - - var derivedStateFromProps = void 0; - if (oldProps !== newProps) { - // The prevState parameter should be the partially updated state. - // Otherwise, spreading state in return values could override updates. - derivedStateFromProps = callGetDerivedStateFromProps(workInProgress, instance, newProps, newState); - } - - if (derivedStateFromProps !== null && derivedStateFromProps !== undefined) { - // Render-phase updates (like this) should not be added to the update queue, - // So that multiple render passes do not enqueue multiple updates. - // Instead, just synchronously merge the returned state into the instance. - newState = newState === null || newState === undefined ? derivedStateFromProps : _assign({}, newState, derivedStateFromProps); - - // Update the base state of the update queue. - // FIXME: This is getting ridiculous. Refactor plz! - var _updateQueue = workInProgress.updateQueue; - if (_updateQueue !== null) { - _updateQueue.baseState = _assign({}, _updateQueue.baseState, derivedStateFromProps); - } - } - if (derivedStateFromCatch !== null && derivedStateFromCatch !== undefined) { - // Render-phase updates (like this) should not be added to the update queue, - // So that multiple render passes do not enqueue multiple updates. - // Instead, just synchronously merge the returned state into the instance. - newState = newState === null || newState === undefined ? derivedStateFromCatch : _assign({}, newState, derivedStateFromCatch); - - // Update the base state of the update queue. - // FIXME: This is getting ridiculous. Refactor plz! - var _updateQueue2 = workInProgress.updateQueue; - if (_updateQueue2 !== null) { - _updateQueue2.baseState = _assign({}, _updateQueue2.baseState, derivedStateFromCatch); - } - } - - if (oldProps === newProps && oldState === newState && !hasContextChanged() && !(workInProgress.updateQueue !== null && workInProgress.updateQueue.hasForceUpdate)) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - return false; - } - - var shouldUpdate = checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { - startPhaseTimer(workInProgress, 'componentWillMount'); - if (typeof instance.componentWillMount === 'function') { - instance.componentWillMount(); - } - if (typeof instance.UNSAFE_componentWillMount === 'function') { - instance.UNSAFE_componentWillMount(); - } - stopPhaseTimer(); - } - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidMount === 'function') { - workInProgress.effectTag |= Update; - } - - // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - memoizeProps(workInProgress, newProps); - memoizeState(workInProgress, newState); - } - - // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - instance.props = newProps; - instance.state = newState; - instance.context = newContext; - - return shouldUpdate; - } - - // Invokes the update life-cycles and returns false if it shouldn't rerender. - function updateClassInstance(current, workInProgress, renderExpirationTime) { - var ctor = workInProgress.type; - var instance = workInProgress.stateNode; - resetInputPointers(workInProgress, instance); - - var oldProps = workInProgress.memoizedProps; - var newProps = workInProgress.pendingProps; - var oldContext = instance.context; - var newUnmaskedContext = getUnmaskedContext(workInProgress); - var newContext = getMaskedContext(workInProgress, newUnmaskedContext); - - var hasNewLifecycles = typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; - - // Note: During these life-cycles, instance.props/instance.state are what - // ever the previously attempted to render - not the "current". However, - // during componentDidUpdate we pass the "current" props. - - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { - if (oldProps !== newProps || oldContext !== newContext) { - callComponentWillReceiveProps(workInProgress, instance, newProps, newContext); - } - } - - // Compute the next state using the memoized state and the update queue. - var oldState = workInProgress.memoizedState; - // TODO: Previous state can be null. - var newState = void 0; - var derivedStateFromCatch = void 0; - - if (workInProgress.updateQueue !== null) { - newState = processUpdateQueue(current, workInProgress, workInProgress.updateQueue, instance, newProps, renderExpirationTime); - - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null && updateQueue.capturedValues !== null && enableGetDerivedStateFromCatch && typeof ctor.getDerivedStateFromCatch === 'function') { - var capturedValues = updateQueue.capturedValues; - // Don't remove these from the update queue yet. We need them in - // finishClassComponent. Do the reset there. - // TODO: This is awkward. Refactor class components. - // updateQueue.capturedValues = null; - derivedStateFromCatch = callGetDerivedStateFromCatch(ctor, capturedValues); - } - } else { - newState = oldState; - } - - var derivedStateFromProps = void 0; - if (oldProps !== newProps) { - // The prevState parameter should be the partially updated state. - // Otherwise, spreading state in return values could override updates. - derivedStateFromProps = callGetDerivedStateFromProps(workInProgress, instance, newProps, newState); - } - - if (derivedStateFromProps !== null && derivedStateFromProps !== undefined) { - // Render-phase updates (like this) should not be added to the update queue, - // So that multiple render passes do not enqueue multiple updates. - // Instead, just synchronously merge the returned state into the instance. - newState = newState === null || newState === undefined ? derivedStateFromProps : _assign({}, newState, derivedStateFromProps); - - // Update the base state of the update queue. - // FIXME: This is getting ridiculous. Refactor plz! - var _updateQueue3 = workInProgress.updateQueue; - if (_updateQueue3 !== null) { - _updateQueue3.baseState = _assign({}, _updateQueue3.baseState, derivedStateFromProps); - } - } - if (derivedStateFromCatch !== null && derivedStateFromCatch !== undefined) { - // Render-phase updates (like this) should not be added to the update queue, - // So that multiple render passes do not enqueue multiple updates. - // Instead, just synchronously merge the returned state into the instance. - newState = newState === null || newState === undefined ? derivedStateFromCatch : _assign({}, newState, derivedStateFromCatch); - - // Update the base state of the update queue. - // FIXME: This is getting ridiculous. Refactor plz! - var _updateQueue4 = workInProgress.updateQueue; - if (_updateQueue4 !== null) { - _updateQueue4.baseState = _assign({}, _updateQueue4.baseState, derivedStateFromCatch); - } - } - - if (oldProps === newProps && oldState === newState && !hasContextChanged() && !(workInProgress.updateQueue !== null && workInProgress.updateQueue.hasForceUpdate)) { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.effectTag |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.effectTag |= Snapshot; - } - } - return false; - } - - var shouldUpdate = checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext); - - if (shouldUpdate) { - // In order to support react-lifecycles-compat polyfilled components, - // Unsafe lifecycles should not be invoked for components using the new APIs. - if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { - startPhaseTimer(workInProgress, 'componentWillUpdate'); - if (typeof instance.componentWillUpdate === 'function') { - instance.componentWillUpdate(newProps, newState, newContext); - } - if (typeof instance.UNSAFE_componentWillUpdate === 'function') { - instance.UNSAFE_componentWillUpdate(newProps, newState, newContext); - } - stopPhaseTimer(); - } - if (typeof instance.componentDidUpdate === 'function') { - workInProgress.effectTag |= Update; - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - workInProgress.effectTag |= Snapshot; - } - } else { - // If an update was already in progress, we should schedule an Update - // effect even though we're bailing out, so that cWU/cDU are called. - if (typeof instance.componentDidUpdate === 'function') { - if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.effectTag |= Update; - } - } - if (typeof instance.getSnapshotBeforeUpdate === 'function') { - if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { - workInProgress.effectTag |= Snapshot; - } - } - - // If shouldComponentUpdate returned false, we should still update the - // memoized props/state to indicate that this work can be reused. - memoizeProps(workInProgress, newProps); - memoizeState(workInProgress, newState); - } - - // Update the existing instance's state, props, and context pointers even - // if shouldComponentUpdate returns false. - instance.props = newProps; - instance.state = newState; - instance.context = newContext; - - return shouldUpdate; - } - - return { - adoptClassInstance: adoptClassInstance, - callGetDerivedStateFromProps: callGetDerivedStateFromProps, - constructClassInstance: constructClassInstance, - mountClassInstance: mountClassInstance, - resumeMountClassInstance: resumeMountClassInstance, - updateClassInstance: updateClassInstance - }; -}; - -var getCurrentFiberStackAddendum$2 = ReactDebugCurrentFiber.getCurrentFiberStackAddendum; - - -var didWarnAboutMaps = void 0; -var didWarnAboutStringRefInStrictMode = void 0; -var ownerHasKeyUseWarning = void 0; -var ownerHasFunctionTypeWarning = void 0; -var warnForMissingKey = function (child) {}; - -{ - didWarnAboutMaps = false; - didWarnAboutStringRefInStrictMode = {}; - - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - ownerHasKeyUseWarning = {}; - ownerHasFunctionTypeWarning = {}; - - warnForMissingKey = function (child) { - if (child === null || typeof child !== 'object') { - return; - } - if (!child._store || child._store.validated || child.key != null) { - return; - } - !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0; - child._store.validated = true; - - var currentComponentErrorInfo = 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + (getCurrentFiberStackAddendum$2() || ''); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - - warning(false, 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.%s', getCurrentFiberStackAddendum$2()); - }; -} - -var isArray$1 = Array.isArray; - -function coerceRef(returnFiber, current, element) { - var mixedRef = element.ref; - if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { - { - if (returnFiber.mode & StrictMode) { - var componentName = getComponentName(returnFiber) || 'Component'; - if (!didWarnAboutStringRefInStrictMode[componentName]) { - warning(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackAddendumByWorkInProgressFiber(returnFiber)); - didWarnAboutStringRefInStrictMode[componentName] = true; - } - } - } - - if (element._owner) { - var owner = element._owner; - var inst = void 0; - if (owner) { - var ownerFiber = owner; - !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Stateless function components cannot have refs.') : void 0; - inst = ownerFiber.stateNode; - } - !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0; - var stringRef = '' + mixedRef; - // Check if previous string ref matches new string ref - if (current !== null && current.ref !== null && current.ref._stringRef === stringRef) { - return current.ref; - } - var ref = function (value) { - var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; - if (value === null) { - delete refs[stringRef]; - } else { - refs[stringRef] = value; - } - }; - ref._stringRef = stringRef; - return ref; - } else { - !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function or a string.') : void 0; - !element._owner ? invariant(false, 'Element ref was specified as a string (%s) but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a functional component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.', mixedRef) : void 0; - } - } - return mixedRef; -} - -function throwOnInvalidObjectType(returnFiber, newChild) { - if (returnFiber.type !== 'textarea') { - var addendum = ''; - { - addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + (getCurrentFiberStackAddendum$2() || ''); - } - invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum); - } -} - -function warnOnFunctionType() { - var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.' + (getCurrentFiberStackAddendum$2() || ''); - - if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { - return; - } - ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; - - warning(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.%s', getCurrentFiberStackAddendum$2() || ''); -} - -// This wrapper function exists because I expect to clone the code in each path -// to be able to optimize each path individually by branching early. This needs -// a compiler or we can do it manually. Helpers that don't need this branching -// live outside of this function. -function ChildReconciler(shouldTrackSideEffects) { - function deleteChild(returnFiber, childToDelete) { - if (!shouldTrackSideEffects) { - // Noop. - return; - } - // Deletions are added in reversed order so we add it to the front. - // At this point, the return fiber's effect list is empty except for - // deletions, so we can just append the deletion to the list. The remaining - // effects aren't added until the complete phase. Once we implement - // resuming, this may not be true. - var last = returnFiber.lastEffect; - if (last !== null) { - last.nextEffect = childToDelete; - returnFiber.lastEffect = childToDelete; - } else { - returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; - } - childToDelete.nextEffect = null; - childToDelete.effectTag = Deletion; - } - - function deleteRemainingChildren(returnFiber, currentFirstChild) { - if (!shouldTrackSideEffects) { - // Noop. - return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by - // assuming that after the first child we've already added everything. - var childToDelete = currentFirstChild; - while (childToDelete !== null) { - deleteChild(returnFiber, childToDelete); - childToDelete = childToDelete.sibling; - } - return null; - } - - function mapRemainingChildren(returnFiber, currentFirstChild) { - // Add the remaining children to a temporary map so that we can find them by - // keys quickly. Implicit (null) keys get added to this set with their index - var existingChildren = new Map(); - - var existingChild = currentFirstChild; - while (existingChild !== null) { - if (existingChild.key !== null) { - existingChildren.set(existingChild.key, existingChild); - } else { - existingChildren.set(existingChild.index, existingChild); - } - existingChild = existingChild.sibling; - } - return existingChildren; - } - - function useFiber(fiber, pendingProps, expirationTime) { - // We currently set sibling to null and index to 0 here because it is easy - // to forget to do before returning it. E.g. for the single child case. - var clone = createWorkInProgress(fiber, pendingProps, expirationTime); - clone.index = 0; - clone.sibling = null; - return clone; - } - - function placeChild(newFiber, lastPlacedIndex, newIndex) { - newFiber.index = newIndex; - if (!shouldTrackSideEffects) { - // Noop. - return lastPlacedIndex; - } - var current = newFiber.alternate; - if (current !== null) { - var oldIndex = current.index; - if (oldIndex < lastPlacedIndex) { - // This is a move. - newFiber.effectTag = Placement; - return lastPlacedIndex; - } else { - // This item can stay in place. - return oldIndex; - } - } else { - // This is an insertion. - newFiber.effectTag = Placement; - return lastPlacedIndex; - } - } - - function placeSingleChild(newFiber) { - // This is simpler for the single child case. We only need to do a - // placement for inserting new children. - if (shouldTrackSideEffects && newFiber.alternate === null) { - newFiber.effectTag = Placement; - } - return newFiber; - } - - function updateTextNode(returnFiber, current, textContent, expirationTime) { - if (current === null || current.tag !== HostText) { - // Insert - var created = createFiberFromText(textContent, returnFiber.mode, expirationTime); - created['return'] = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, textContent, expirationTime); - existing['return'] = returnFiber; - return existing; - } - } - - function updateElement(returnFiber, current, element, expirationTime) { - if (current !== null && current.type === element.type) { - // Move based on index - var existing = useFiber(current, element.props, expirationTime); - existing.ref = coerceRef(returnFiber, current, element); - existing['return'] = returnFiber; - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } else { - // Insert - var created = createFiberFromElement(element, returnFiber.mode, expirationTime); - created.ref = coerceRef(returnFiber, current, element); - created['return'] = returnFiber; - return created; - } - } - - function updatePortal(returnFiber, current, portal, expirationTime) { - if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { - // Insert - var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime); - created['return'] = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, portal.children || [], expirationTime); - existing['return'] = returnFiber; - return existing; - } - } - - function updateFragment(returnFiber, current, fragment, expirationTime, key) { - if (current === null || current.tag !== Fragment) { - // Insert - var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key); - created['return'] = returnFiber; - return created; - } else { - // Update - var existing = useFiber(current, fragment, expirationTime); - existing['return'] = returnFiber; - return existing; - } - } - - function createChild(returnFiber, newChild, expirationTime) { - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime); - created['return'] = returnFiber; - return created; - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime); - _created.ref = coerceRef(returnFiber, null, newChild); - _created['return'] = returnFiber; - return _created; - } - case REACT_PORTAL_TYPE: - { - var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime); - _created2['return'] = returnFiber; - return _created2; - } - } - - if (isArray$1(newChild) || getIteratorFn(newChild)) { - var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null); - _created3['return'] = returnFiber; - return _created3; - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(); - } - } - - return null; - } - - function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { - // Update the fiber if the keys match, otherwise return null. - - var key = oldFiber !== null ? oldFiber.key : null; - - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes don't have keys. If the previous node is implicitly keyed - // we can continue to replace it without aborting even if it is not a text - // node. - if (key !== null) { - return null; - } - return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - if (newChild.key === key) { - if (newChild.type === REACT_FRAGMENT_TYPE) { - return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key); - } - return updateElement(returnFiber, oldFiber, newChild, expirationTime); - } else { - return null; - } - } - case REACT_PORTAL_TYPE: - { - if (newChild.key === key) { - return updatePortal(returnFiber, oldFiber, newChild, expirationTime); - } else { - return null; - } - } - } - - if (isArray$1(newChild) || getIteratorFn(newChild)) { - if (key !== null) { - return null; - } - - return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(); - } - } - - return null; - } - - function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) { - if (typeof newChild === 'string' || typeof newChild === 'number') { - // Text nodes don't have keys, so we neither have to check the old nor - // new node for the key. If both are text nodes, they match. - var matchedFiber = existingChildren.get(newIdx) || null; - return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime); - } - - if (typeof newChild === 'object' && newChild !== null) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - { - var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - if (newChild.type === REACT_FRAGMENT_TYPE) { - return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key); - } - return updateElement(returnFiber, _matchedFiber, newChild, expirationTime); - } - case REACT_PORTAL_TYPE: - { - var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; - return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime); - } - } - - if (isArray$1(newChild) || getIteratorFn(newChild)) { - var _matchedFiber3 = existingChildren.get(newIdx) || null; - return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null); - } - - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(); - } - } - - return null; - } - - /** - * Warns if there is a duplicate or missing key - */ - function warnOnInvalidKey(child, knownKeys) { - { - if (typeof child !== 'object' || child === null) { - return knownKeys; - } - switch (child.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - warnForMissingKey(child); - var key = child.key; - if (typeof key !== 'string') { - break; - } - if (knownKeys === null) { - knownKeys = new Set(); - knownKeys.add(key); - break; - } - if (!knownKeys.has(key)) { - knownKeys.add(key); - break; - } - warning(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum$2()); - break; - default: - break; - } - } - return knownKeys; - } - - function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) { - // This algorithm can't optimize by searching from boths ends since we - // don't have backpointers on fibers. I'm trying to see how far we can get - // with that model. If it ends up not being worth the tradeoffs, we can - // add it later. - - // Even with a two ended optimization, we'd want to optimize for the case - // where there are few changes and brute force the comparison instead of - // going for the Map. It'd like to explore hitting that path first in - // forward-only mode and only go for the Map once we notice that we need - // lots of look ahead. This doesn't handle reversal as well as two ended - // search but that's unusual. Besides, for the two ended optimization to - // work on Iterables, we'd need to copy the whole set. - - // In this first iteration, we'll just live with hitting the bad case - // (adding everything to a Map) in for every insert/move. - - // If you change this code, also update reconcileChildrenIterator() which - // uses the same algorithm. - - { - // First, validate keys. - var knownKeys = null; - for (var i = 0; i < newChildren.length; i++) { - var child = newChildren[i]; - knownKeys = warnOnInvalidKey(child, knownKeys); - } - } - - var resultingFirstChild = null; - var previousNewFiber = null; - - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (oldFiber === null) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (newIdx === newChildren.length) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime); - if (!_newFiber) { - continue; - } - lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber; - } else { - previousNewFiber.sibling = _newFiber; - } - previousNewFiber = _newFiber; - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; newIdx < newChildren.length; newIdx++) { - var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime); - if (_newFiber2) { - if (shouldTrackSideEffects) { - if (_newFiber2.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren['delete'](_newFiber2.key === null ? newIdx : _newFiber2.key); - } - } - lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber2; - } else { - previousNewFiber.sibling = _newFiber2; - } - previousNewFiber = _newFiber2; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - return resultingFirstChild; - } - - function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) { - // This is the same implementation as reconcileChildrenArray(), - // but using the iterator instead. - - var iteratorFn = getIteratorFn(newChildrenIterable); - !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - { - // Warn about using Maps as children - if (typeof newChildrenIterable.entries === 'function') { - var possibleMap = newChildrenIterable; - if (possibleMap.entries === iteratorFn) { - !didWarnAboutMaps ? warning(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.%s', getCurrentFiberStackAddendum$2()) : void 0; - didWarnAboutMaps = true; - } - } - - // First, validate keys. - // We'll get a different iterator later for the main pass. - var _newChildren = iteratorFn.call(newChildrenIterable); - if (_newChildren) { - var knownKeys = null; - var _step = _newChildren.next(); - for (; !_step.done; _step = _newChildren.next()) { - var child = _step.value; - knownKeys = warnOnInvalidKey(child, knownKeys); - } - } - } - - var newChildren = iteratorFn.call(newChildrenIterable); - !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0; - - var resultingFirstChild = null; - var previousNewFiber = null; - - var oldFiber = currentFirstChild; - var lastPlacedIndex = 0; - var newIdx = 0; - var nextOldFiber = null; - - var step = newChildren.next(); - for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { - if (oldFiber.index > newIdx) { - nextOldFiber = oldFiber; - oldFiber = null; - } else { - nextOldFiber = oldFiber.sibling; - } - var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime); - if (newFiber === null) { - // TODO: This breaks on empty slots like null children. That's - // unfortunate because it triggers the slow path all the time. We need - // a better way to communicate whether this was a miss or null, - // boolean, undefined, etc. - if (!oldFiber) { - oldFiber = nextOldFiber; - } - break; - } - if (shouldTrackSideEffects) { - if (oldFiber && newFiber.alternate === null) { - // We matched the slot, but we didn't reuse the existing fiber, so we - // need to delete the existing child. - deleteChild(returnFiber, oldFiber); - } - } - lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = newFiber; - } else { - // TODO: Defer siblings if we're not at the right index for this slot. - // I.e. if we had null values before, then we want to defer this - // for each null value. However, we also don't want to call updateSlot - // with the previous one. - previousNewFiber.sibling = newFiber; - } - previousNewFiber = newFiber; - oldFiber = nextOldFiber; - } - - if (step.done) { - // We've reached the end of the new children. We can delete the rest. - deleteRemainingChildren(returnFiber, oldFiber); - return resultingFirstChild; - } - - if (oldFiber === null) { - // If we don't have any more existing children we can choose a fast path - // since the rest will all be insertions. - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber3 = createChild(returnFiber, step.value, expirationTime); - if (_newFiber3 === null) { - continue; - } - lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - // TODO: Move out of the loop. This only happens for the first run. - resultingFirstChild = _newFiber3; - } else { - previousNewFiber.sibling = _newFiber3; - } - previousNewFiber = _newFiber3; - } - return resultingFirstChild; - } - - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); - - // Keep scanning and use the map to restore deleted items as moves. - for (; !step.done; newIdx++, step = newChildren.next()) { - var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime); - if (_newFiber4 !== null) { - if (shouldTrackSideEffects) { - if (_newFiber4.alternate !== null) { - // The new fiber is a work in progress, but if there exists a - // current, that means that we reused the fiber. We need to delete - // it from the child list so that we don't add it to the deletion - // list. - existingChildren['delete'](_newFiber4.key === null ? newIdx : _newFiber4.key); - } - } - lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); - if (previousNewFiber === null) { - resultingFirstChild = _newFiber4; - } else { - previousNewFiber.sibling = _newFiber4; - } - previousNewFiber = _newFiber4; - } - } - - if (shouldTrackSideEffects) { - // Any existing children that weren't consumed above were deleted. We need - // to add them to the deletion list. - existingChildren.forEach(function (child) { - return deleteChild(returnFiber, child); - }); - } - - return resultingFirstChild; - } - - function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) { - // There's no need to check for keys on text nodes since we don't have a - // way to define them. - if (currentFirstChild !== null && currentFirstChild.tag === HostText) { - // We already have an existing node so let's just update it and delete - // the rest. - deleteRemainingChildren(returnFiber, currentFirstChild.sibling); - var existing = useFiber(currentFirstChild, textContent, expirationTime); - existing['return'] = returnFiber; - return existing; - } - // The existing first child is not a text node so we need to create one - // and delete the existing ones. - deleteRemainingChildren(returnFiber, currentFirstChild); - var created = createFiberFromText(textContent, returnFiber.mode, expirationTime); - created['return'] = returnFiber; - return created; - } - - function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) { - var key = element.key; - var child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.type === element.type) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime); - existing.ref = coerceRef(returnFiber, child, element); - existing['return'] = returnFiber; - { - existing._debugSource = element._source; - existing._debugOwner = element._owner; - } - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - if (element.type === REACT_FRAGMENT_TYPE) { - var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key); - created['return'] = returnFiber; - return created; - } else { - var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime); - _created4.ref = coerceRef(returnFiber, currentFirstChild, element); - _created4['return'] = returnFiber; - return _created4; - } - } - - function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) { - var key = portal.key; - var child = currentFirstChild; - while (child !== null) { - // TODO: If key === null and child.key === null, then this only applies to - // the first item in the list. - if (child.key === key) { - if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, portal.children || [], expirationTime); - existing['return'] = returnFiber; - return existing; - } else { - deleteRemainingChildren(returnFiber, child); - break; - } - } else { - deleteChild(returnFiber, child); - } - child = child.sibling; - } - - var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime); - created['return'] = returnFiber; - return created; - } - - // This API will tag the children with the side-effect of the reconciliation - // itself. They will be added to the side-effect list as we pass through the - // children and the parent. - function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) { - // This function is not recursive. - // If the top level item is an array, we treat it as a set of children, - // not as a fragment. Nested arrays on the other hand will be treated as - // fragment nodes. Recursion happens at the normal flow. - - // Handle top level unkeyed fragments as if they were arrays. - // This leads to an ambiguity between <>{[...]} and <>.... - // We treat the ambiguous cases above the same. - if (typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null) { - newChild = newChild.props.children; - } - - // Handle object types - var isObject = typeof newChild === 'object' && newChild !== null; - - if (isObject) { - switch (newChild.$$typeof) { - case REACT_ELEMENT_TYPE: - return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime)); - case REACT_PORTAL_TYPE: - return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime)); - } - } - - if (typeof newChild === 'string' || typeof newChild === 'number') { - return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime)); - } - - if (isArray$1(newChild)) { - return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime); - } - - if (getIteratorFn(newChild)) { - return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime); - } - - if (isObject) { - throwOnInvalidObjectType(returnFiber, newChild); - } - - { - if (typeof newChild === 'function') { - warnOnFunctionType(); - } - } - if (typeof newChild === 'undefined') { - // If the new child is undefined, and the return fiber is a composite - // component, throw an error. If Fiber return types are disabled, - // we already threw above. - switch (returnFiber.tag) { - case ClassComponent: - { - { - var instance = returnFiber.stateNode; - if (instance.render._isMockFunction) { - // We allow auto-mocks to proceed as if they're returning null. - break; - } - } - } - // Intentionally fall through to the next case, which handles both - // functions and classes - // eslint-disable-next-lined no-fallthrough - case FunctionalComponent: - { - var Component = returnFiber.type; - invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component'); - } - } - } - - // Remaining cases are all treated as empty. - return deleteRemainingChildren(returnFiber, currentFirstChild); - } - - return reconcileChildFibers; -} - -var reconcileChildFibers = ChildReconciler(true); -var mountChildFibers = ChildReconciler(false); - -function cloneChildFibers(current, workInProgress) { - !(current === null || workInProgress.child === current.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0; - - if (workInProgress.child === null) { - return; - } - - var currentChild = workInProgress.child; - var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime); - workInProgress.child = newChild; - - newChild['return'] = workInProgress; - while (currentChild.sibling !== null) { - currentChild = currentChild.sibling; - newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime); - newChild['return'] = workInProgress; - } - newChild.sibling = null; -} - -var didWarnAboutBadClass = void 0; -var didWarnAboutGetDerivedStateOnFunctionalComponent = void 0; -var didWarnAboutStatelessRefs = void 0; - -{ - didWarnAboutBadClass = {}; - didWarnAboutGetDerivedStateOnFunctionalComponent = {}; - didWarnAboutStatelessRefs = {}; -} - -var ReactFiberBeginWork = function (config, hostContext, legacyContext, newContext, hydrationContext, scheduleWork, computeExpirationForFiber) { - var shouldSetTextContent = config.shouldSetTextContent, - shouldDeprioritizeSubtree = config.shouldDeprioritizeSubtree; - var pushHostContext = hostContext.pushHostContext, - pushHostContainer = hostContext.pushHostContainer; - var pushProvider = newContext.pushProvider; - var getMaskedContext = legacyContext.getMaskedContext, - getUnmaskedContext = legacyContext.getUnmaskedContext, - hasLegacyContextChanged = legacyContext.hasContextChanged, - pushLegacyContextProvider = legacyContext.pushContextProvider, - pushTopLevelContextObject = legacyContext.pushTopLevelContextObject, - invalidateContextProvider = legacyContext.invalidateContextProvider; - var enterHydrationState = hydrationContext.enterHydrationState, - resetHydrationState = hydrationContext.resetHydrationState, - tryToClaimNextHydratableInstance = hydrationContext.tryToClaimNextHydratableInstance; - - var _ReactFiberClassCompo = ReactFiberClassComponent(legacyContext, scheduleWork, computeExpirationForFiber, memoizeProps, memoizeState), - adoptClassInstance = _ReactFiberClassCompo.adoptClassInstance, - callGetDerivedStateFromProps = _ReactFiberClassCompo.callGetDerivedStateFromProps, - constructClassInstance = _ReactFiberClassCompo.constructClassInstance, - mountClassInstance = _ReactFiberClassCompo.mountClassInstance, - resumeMountClassInstance = _ReactFiberClassCompo.resumeMountClassInstance, - updateClassInstance = _ReactFiberClassCompo.updateClassInstance; - - // TODO: Remove this and use reconcileChildrenAtExpirationTime directly. - - - function reconcileChildren(current, workInProgress, nextChildren) { - reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, workInProgress.expirationTime); - } - - function reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, renderExpirationTime) { - if (current === null) { - // If this is a fresh new component that hasn't been rendered yet, we - // won't update its child set by applying minimal side-effects. Instead, - // we will add them all to the child before it gets rendered. That means - // we can optimize this reconciliation pass by not tracking side-effects. - workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime); - } else { - // If the current child is the same as the work in progress, it means that - // we haven't yet started any work on these children. Therefore, we use - // the clone algorithm to create a copy of all the current children. - - // If we had any progressed work already, that is invalid at this point so - // let's throw it out. - workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime); - } - } - - function updateForwardRef(current, workInProgress) { - var render = workInProgress.type.render; - var nextChildren = render(workInProgress.pendingProps, workInProgress.ref); - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - return workInProgress.child; - } - - function updateFragment(current, workInProgress) { - var nextChildren = workInProgress.pendingProps; - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (workInProgress.memoizedProps === nextChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - return workInProgress.child; - } - - function updateMode(current, workInProgress) { - var nextChildren = workInProgress.pendingProps.children; - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (nextChildren === null || workInProgress.memoizedProps === nextChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - return workInProgress.child; - } - - function markRef(current, workInProgress) { - var ref = workInProgress.ref; - if (current === null && ref !== null || current !== null && current.ref !== ref) { - // Schedule a Ref effect - workInProgress.effectTag |= Ref; - } - } - - function updateFunctionalComponent(current, workInProgress) { - var fn = workInProgress.type; - var nextProps = workInProgress.pendingProps; - - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else { - if (workInProgress.memoizedProps === nextProps) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - // TODO: consider bringing fn.shouldComponentUpdate() back. - // It used to be here. - } - - var unmaskedContext = getUnmaskedContext(workInProgress); - var context = getMaskedContext(workInProgress, unmaskedContext); - - var nextChildren = void 0; - - { - ReactCurrentOwner.current = workInProgress; - ReactDebugCurrentFiber.setCurrentPhase('render'); - nextChildren = fn(nextProps, context); - ReactDebugCurrentFiber.setCurrentPhase(null); - } - // React DevTools reads this flag. - workInProgress.effectTag |= PerformedWork; - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextProps); - return workInProgress.child; - } - - function updateClassComponent(current, workInProgress, renderExpirationTime) { - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = pushLegacyContextProvider(workInProgress); - var shouldUpdate = void 0; - if (current === null) { - if (workInProgress.stateNode === null) { - // In the initial pass we might need to construct the instance. - constructClassInstance(workInProgress, workInProgress.pendingProps); - mountClassInstance(workInProgress, renderExpirationTime); - - shouldUpdate = true; - } else { - // In a resume, we'll already have an instance we can reuse. - shouldUpdate = resumeMountClassInstance(workInProgress, renderExpirationTime); - } - } else { - shouldUpdate = updateClassInstance(current, workInProgress, renderExpirationTime); - } - - // We processed the update queue inside updateClassInstance. It may have - // included some errors that were dispatched during the commit phase. - // TODO: Refactor class components so this is less awkward. - var didCaptureError = false; - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null && updateQueue.capturedValues !== null) { - shouldUpdate = true; - didCaptureError = true; - } - return finishClassComponent(current, workInProgress, shouldUpdate, hasContext, didCaptureError, renderExpirationTime); - } - - function finishClassComponent(current, workInProgress, shouldUpdate, hasContext, didCaptureError, renderExpirationTime) { - // Refs should update even if shouldComponentUpdate returns false - markRef(current, workInProgress); - - if (!shouldUpdate && !didCaptureError) { - // Context providers should defer to sCU for rendering - if (hasContext) { - invalidateContextProvider(workInProgress, false); - } - - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - var ctor = workInProgress.type; - var instance = workInProgress.stateNode; - - // Rerender - ReactCurrentOwner.current = workInProgress; - var nextChildren = void 0; - if (didCaptureError && (!enableGetDerivedStateFromCatch || typeof ctor.getDerivedStateFromCatch !== 'function')) { - // If we captured an error, but getDerivedStateFrom catch is not defined, - // unmount all the children. componentDidCatch will schedule an update to - // re-render a fallback. This is temporary until we migrate everyone to - // the new API. - // TODO: Warn in a future release. - nextChildren = null; - } else { - { - ReactDebugCurrentFiber.setCurrentPhase('render'); - nextChildren = instance.render(); - if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { - instance.render(); - } - ReactDebugCurrentFiber.setCurrentPhase(null); - } - } - - // React DevTools reads this flag. - workInProgress.effectTag |= PerformedWork; - if (didCaptureError) { - // If we're recovering from an error, reconcile twice: first to delete - // all the existing children. - reconcileChildrenAtExpirationTime(current, workInProgress, null, renderExpirationTime); - workInProgress.child = null; - // Now we can continue reconciling like normal. This has the effect of - // remounting all children regardless of whether their their - // identity matches. - } - reconcileChildrenAtExpirationTime(current, workInProgress, nextChildren, renderExpirationTime); - // Memoize props and state using the values we just used to render. - // TODO: Restructure so we never read values from the instance. - memoizeState(workInProgress, instance.state); - memoizeProps(workInProgress, instance.props); - - // The context might have changed so we need to recalculate it. - if (hasContext) { - invalidateContextProvider(workInProgress, true); - } - - return workInProgress.child; - } - - function pushHostRootContext(workInProgress) { - var root = workInProgress.stateNode; - if (root.pendingContext) { - pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); - } else if (root.context) { - // Should always be set - pushTopLevelContextObject(workInProgress, root.context, false); - } - pushHostContainer(workInProgress, root.containerInfo); - } - - function updateHostRoot(current, workInProgress, renderExpirationTime) { - pushHostRootContext(workInProgress); - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null) { - var prevState = workInProgress.memoizedState; - var state = processUpdateQueue(current, workInProgress, updateQueue, null, null, renderExpirationTime); - memoizeState(workInProgress, state); - updateQueue = workInProgress.updateQueue; - - var element = void 0; - if (updateQueue !== null && updateQueue.capturedValues !== null) { - // There's an uncaught error. Unmount the whole root. - element = null; - } else if (prevState === state) { - // If the state is the same as before, that's a bailout because we had - // no work that expires at this time. - resetHydrationState(); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } else { - element = state.element; - } - var root = workInProgress.stateNode; - if ((current === null || current.child === null) && root.hydrate && enterHydrationState(workInProgress)) { - // If we don't have any current children this might be the first pass. - // We always try to hydrate. If this isn't a hydration pass there won't - // be any children to hydrate which is effectively the same thing as - // not hydrating. - - // This is a bit of a hack. We track the host root as a placement to - // know that we're currently in a mounting state. That way isMounted - // works as expected. We must reset this before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag |= Placement; - - // Ensure that children mount into this root without tracking - // side-effects. This ensures that we don't store Placement effects on - // nodes that will be hydrated. - workInProgress.child = mountChildFibers(workInProgress, null, element, renderExpirationTime); - } else { - // Otherwise reset hydration state in case we aborted and resumed another - // root. - resetHydrationState(); - reconcileChildren(current, workInProgress, element); - } - memoizeState(workInProgress, state); - return workInProgress.child; - } - resetHydrationState(); - // If there is no update queue, that's a bailout because the root has no props. - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - function updateHostComponent(current, workInProgress, renderExpirationTime) { - pushHostContext(workInProgress); - - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - - var type = workInProgress.type; - var memoizedProps = workInProgress.memoizedProps; - var nextProps = workInProgress.pendingProps; - var prevProps = current !== null ? current.memoizedProps : null; - - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (memoizedProps === nextProps) { - var isHidden = workInProgress.mode & AsyncMode && shouldDeprioritizeSubtree(type, nextProps); - if (isHidden) { - // Before bailing out, make sure we've deprioritized a hidden component. - workInProgress.expirationTime = Never; - } - if (!isHidden || renderExpirationTime !== Never) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - // If we're rendering a hidden node at hidden priority, don't bailout. The - // parent is complete, but the children may not be. - } - - var nextChildren = nextProps.children; - var isDirectTextChild = shouldSetTextContent(type, nextProps); - - if (isDirectTextChild) { - // We special case a direct text child of a host node. This is a common - // case. We won't handle it as a reified child. We will instead handle - // this in the host environment that also have access to this prop. That - // avoids allocating another HostText fiber and traversing it. - nextChildren = null; - } else if (prevProps && shouldSetTextContent(type, prevProps)) { - // If we're switching from a direct text child to a normal child, or to - // empty, we need to schedule the text content to be reset. - workInProgress.effectTag |= ContentReset; - } - - markRef(current, workInProgress); - - // Check the host config to see if the children are offscreen/hidden. - if (renderExpirationTime !== Never && workInProgress.mode & AsyncMode && shouldDeprioritizeSubtree(type, nextProps)) { - // Down-prioritize the children. - workInProgress.expirationTime = Never; - // Bailout and come back to this fiber later. - workInProgress.memoizedProps = nextProps; - return null; - } - - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextProps); - return workInProgress.child; - } - - function updateHostText(current, workInProgress) { - if (current === null) { - tryToClaimNextHydratableInstance(workInProgress); - } - var nextProps = workInProgress.pendingProps; - memoizeProps(workInProgress, nextProps); - // Nothing to do here. This is terminal. We'll do the completion step - // immediately after. - return null; - } - - function mountIndeterminateComponent(current, workInProgress, renderExpirationTime) { - !(current === null) ? invariant(false, 'An indeterminate component should never have mounted. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var fn = workInProgress.type; - var props = workInProgress.pendingProps; - var unmaskedContext = getUnmaskedContext(workInProgress); - var context = getMaskedContext(workInProgress, unmaskedContext); - - var value = void 0; - - { - if (fn.prototype && typeof fn.prototype.render === 'function') { - var componentName = getComponentName(workInProgress) || 'Unknown'; - - if (!didWarnAboutBadClass[componentName]) { - warning(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); - didWarnAboutBadClass[componentName] = true; - } - } - ReactCurrentOwner.current = workInProgress; - value = fn(props, context); - } - // React DevTools reads this flag. - workInProgress.effectTag |= PerformedWork; - - if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { - var Component = workInProgress.type; - - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; - - workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - - if (typeof Component.getDerivedStateFromProps === 'function') { - var partialState = callGetDerivedStateFromProps(workInProgress, value, props, workInProgress.memoizedState); - - if (partialState !== null && partialState !== undefined) { - workInProgress.memoizedState = _assign({}, workInProgress.memoizedState, partialState); - } - } - - // Push context providers early to prevent context stack mismatches. - // During mounting we don't know the child context yet as the instance doesn't exist. - // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = pushLegacyContextProvider(workInProgress); - adoptClassInstance(workInProgress, value); - mountClassInstance(workInProgress, renderExpirationTime); - return finishClassComponent(current, workInProgress, true, hasContext, false, renderExpirationTime); - } else { - // Proceed under the assumption that this is a functional component - workInProgress.tag = FunctionalComponent; - { - var _Component = workInProgress.type; - - if (_Component) { - !!_Component.childContextTypes ? warning(false, '%s(...): childContextTypes cannot be defined on a functional component.', _Component.displayName || _Component.name || 'Component') : void 0; - } - if (workInProgress.ref !== null) { - var info = ''; - var ownerName = ReactDebugCurrentFiber.getCurrentFiberOwnerName(); - if (ownerName) { - info += '\n\nCheck the render method of `' + ownerName + '`.'; - } - - var warningKey = ownerName || workInProgress._debugID || ''; - var debugSource = workInProgress._debugSource; - if (debugSource) { - warningKey = debugSource.fileName + ':' + debugSource.lineNumber; - } - if (!didWarnAboutStatelessRefs[warningKey]) { - didWarnAboutStatelessRefs[warningKey] = true; - warning(false, 'Stateless function components cannot be given refs. ' + 'Attempts to access this ref will fail.%s%s', info, ReactDebugCurrentFiber.getCurrentFiberStackAddendum()); - } - } - - if (typeof fn.getDerivedStateFromProps === 'function') { - var _componentName = getComponentName(workInProgress) || 'Unknown'; - - if (!didWarnAboutGetDerivedStateOnFunctionalComponent[_componentName]) { - warning(false, '%s: Stateless functional components do not support getDerivedStateFromProps.', _componentName); - didWarnAboutGetDerivedStateOnFunctionalComponent[_componentName] = true; - } - } - } - reconcileChildren(current, workInProgress, value); - memoizeProps(workInProgress, props); - return workInProgress.child; - } - } - - function updateCallComponent(current, workInProgress, renderExpirationTime) { - var nextProps = workInProgress.pendingProps; - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (workInProgress.memoizedProps === nextProps) { - nextProps = workInProgress.memoizedProps; - // TODO: When bailing out, we might need to return the stateNode instead - // of the child. To check it for work. - // return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - var nextChildren = nextProps.children; - - // The following is a fork of reconcileChildrenAtExpirationTime but using - // stateNode to store the child. - if (current === null) { - workInProgress.stateNode = mountChildFibers(workInProgress, workInProgress.stateNode, nextChildren, renderExpirationTime); - } else { - workInProgress.stateNode = reconcileChildFibers(workInProgress, current.stateNode, nextChildren, renderExpirationTime); - } - - memoizeProps(workInProgress, nextProps); - // This doesn't take arbitrary time so we could synchronously just begin - // eagerly do the work of workInProgress.child as an optimization. - return workInProgress.stateNode; - } - - function updatePortalComponent(current, workInProgress, renderExpirationTime) { - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - var nextChildren = workInProgress.pendingProps; - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (workInProgress.memoizedProps === nextChildren) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - if (current === null) { - // Portals are special because we don't append the children during mount - // but at commit. Therefore we need to track insertions which the normal - // flow doesn't do during mount. This doesn't happen at the root because - // the root always starts with a "current" with a null child. - // TODO: Consider unifying this with how the root works. - workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime); - memoizeProps(workInProgress, nextChildren); - } else { - reconcileChildren(current, workInProgress, nextChildren); - memoizeProps(workInProgress, nextChildren); - } - return workInProgress.child; - } - - function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) { - var fiber = workInProgress.child; - if (fiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - fiber['return'] = workInProgress; - } - while (fiber !== null) { - var nextFiber = void 0; - // Visit this fiber. - switch (fiber.tag) { - case ContextConsumer: - // Check if the context matches. - var observedBits = fiber.stateNode | 0; - if (fiber.type === context && (observedBits & changedBits) !== 0) { - // Update the expiration time of all the ancestors, including - // the alternates. - var node = fiber; - while (node !== null) { - var alternate = node.alternate; - if (node.expirationTime === NoWork || node.expirationTime > renderExpirationTime) { - node.expirationTime = renderExpirationTime; - if (alternate !== null && (alternate.expirationTime === NoWork || alternate.expirationTime > renderExpirationTime)) { - alternate.expirationTime = renderExpirationTime; - } - } else if (alternate !== null && (alternate.expirationTime === NoWork || alternate.expirationTime > renderExpirationTime)) { - alternate.expirationTime = renderExpirationTime; - } else { - // Neither alternate was updated, which means the rest of the - // ancestor path already has sufficient priority. - break; - } - node = node['return']; - } - // Don't scan deeper than a matching consumer. When we render the - // consumer, we'll continue scanning from that point. This way the - // scanning work is time-sliced. - nextFiber = null; - } else { - // Traverse down. - nextFiber = fiber.child; - } - break; - case ContextProvider: - // Don't scan deeper if this is a matching provider - nextFiber = fiber.type === workInProgress.type ? null : fiber.child; - break; - default: - // Traverse down. - nextFiber = fiber.child; - break; - } - if (nextFiber !== null) { - // Set the return pointer of the child to the work-in-progress fiber. - nextFiber['return'] = fiber; - } else { - // No child. Traverse to next sibling. - nextFiber = fiber; - while (nextFiber !== null) { - if (nextFiber === workInProgress) { - // We're back to the root of this subtree. Exit. - nextFiber = null; - break; - } - var sibling = nextFiber.sibling; - if (sibling !== null) { - nextFiber = sibling; - break; - } - // No more siblings. Traverse up. - nextFiber = nextFiber['return']; - } - } - fiber = nextFiber; - } - } - - function updateContextProvider(current, workInProgress, renderExpirationTime) { - var providerType = workInProgress.type; - var context = providerType._context; - - var newProps = workInProgress.pendingProps; - var oldProps = workInProgress.memoizedProps; - - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (oldProps === newProps) { - workInProgress.stateNode = 0; - pushProvider(workInProgress); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - - var newValue = newProps.value; - workInProgress.memoizedProps = newProps; - - var changedBits = void 0; - if (oldProps === null) { - // Initial render - changedBits = MAX_SIGNED_31_BIT_INT; - } else { - if (oldProps.value === newProps.value) { - // No change. Bailout early if children are the same. - if (oldProps.children === newProps.children) { - workInProgress.stateNode = 0; - pushProvider(workInProgress); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - changedBits = 0; - } else { - var oldValue = oldProps.value; - // Use Object.is to compare the new context value to the old value. - // Inlined Object.is polyfill. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - if (oldValue === newValue && (oldValue !== 0 || 1 / oldValue === 1 / newValue) || oldValue !== oldValue && newValue !== newValue // eslint-disable-line no-self-compare - ) { - // No change. Bailout early if children are the same. - if (oldProps.children === newProps.children) { - workInProgress.stateNode = 0; - pushProvider(workInProgress); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - changedBits = 0; - } else { - changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT; - { - !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0; - } - changedBits |= 0; - - if (changedBits === 0) { - // No change. Bailout early if children are the same. - if (oldProps.children === newProps.children) { - workInProgress.stateNode = 0; - pushProvider(workInProgress); - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - } else { - propagateContextChange(workInProgress, context, changedBits, renderExpirationTime); - } - } - } - } - - workInProgress.stateNode = changedBits; - pushProvider(workInProgress); - - var newChildren = newProps.children; - reconcileChildren(current, workInProgress, newChildren); - return workInProgress.child; - } - - function updateContextConsumer(current, workInProgress, renderExpirationTime) { - var context = workInProgress.type; - var newProps = workInProgress.pendingProps; - var oldProps = workInProgress.memoizedProps; - - var newValue = context._currentValue; - var changedBits = context._changedBits; - - if (hasLegacyContextChanged()) { - // Normally we can bail out on props equality but if context has changed - // we don't do the bailout and we have to reuse existing props instead. - } else if (changedBits === 0 && oldProps === newProps) { - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - workInProgress.memoizedProps = newProps; - - var observedBits = newProps.unstable_observedBits; - if (observedBits === undefined || observedBits === null) { - // Subscribe to all changes by default - observedBits = MAX_SIGNED_31_BIT_INT; - } - // Store the observedBits on the fiber's stateNode for quick access. - workInProgress.stateNode = observedBits; - - if ((changedBits & observedBits) !== 0) { - // Context change propagation stops at matching consumers, for time- - // slicing. Continue the propagation here. - propagateContextChange(workInProgress, context, changedBits, renderExpirationTime); - } else if (oldProps === newProps) { - // Skip over a memoized parent with a bitmask bailout even - // if we began working on it because of a deeper matching child. - return bailoutOnAlreadyFinishedWork(current, workInProgress); - } - // There is no bailout on `children` equality because we expect people - // to often pass a bound method as a child, but it may reference - // `this.state` or `this.props` (and thus needs to re-render on `setState`). - - var render = newProps.children; - - { - !(typeof render === 'function') ? warning(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0; - } - - var newChildren = render(newValue); - reconcileChildren(current, workInProgress, newChildren); - return workInProgress.child; - } - - /* - function reuseChildrenEffects(returnFiber : Fiber, firstChild : Fiber) { - let child = firstChild; - do { - // Ensure that the first and last effect of the parent corresponds - // to the children's first and last effect. - if (!returnFiber.firstEffect) { - returnFiber.firstEffect = child.firstEffect; - } - if (child.lastEffect) { - if (returnFiber.lastEffect) { - returnFiber.lastEffect.nextEffect = child.firstEffect; - } - returnFiber.lastEffect = child.lastEffect; - } - } while (child = child.sibling); - } - */ - - function bailoutOnAlreadyFinishedWork(current, workInProgress) { - cancelWorkTimer(workInProgress); - - // TODO: We should ideally be able to bail out early if the children have no - // more work to do. However, since we don't have a separation of this - // Fiber's priority and its children yet - we don't know without doing lots - // of the same work we do anyway. Once we have that separation we can just - // bail out here if the children has no more work at this priority level. - // if (workInProgress.priorityOfChildren <= priorityLevel) { - // // If there are side-effects in these children that have not yet been - // // committed we need to ensure that they get properly transferred up. - // if (current && current.child !== workInProgress.child) { - // reuseChildrenEffects(workInProgress, child); - // } - // return null; - // } - - cloneChildFibers(current, workInProgress); - return workInProgress.child; - } - - function bailoutOnLowPriority(current, workInProgress) { - cancelWorkTimer(workInProgress); - - // TODO: Handle HostComponent tags here as well and call pushHostContext()? - // See PR 8590 discussion for context - switch (workInProgress.tag) { - case HostRoot: - pushHostRootContext(workInProgress); - break; - case ClassComponent: - pushLegacyContextProvider(workInProgress); - break; - case HostPortal: - pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); - break; - case ContextProvider: - pushProvider(workInProgress); - break; - } - // TODO: What if this is currently in progress? - // How can that happen? How is this not being cloned? - return null; - } - - // TODO: Delete memoizeProps/State and move to reconcile/bailout instead - function memoizeProps(workInProgress, nextProps) { - workInProgress.memoizedProps = nextProps; - } - - function memoizeState(workInProgress, nextState) { - workInProgress.memoizedState = nextState; - // Don't reset the updateQueue, in case there are pending updates. Resetting - // is handled by processUpdateQueue. - } - - function beginWork(current, workInProgress, renderExpirationTime) { - if (workInProgress.expirationTime === NoWork || workInProgress.expirationTime > renderExpirationTime) { - return bailoutOnLowPriority(current, workInProgress); - } - - switch (workInProgress.tag) { - case IndeterminateComponent: - return mountIndeterminateComponent(current, workInProgress, renderExpirationTime); - case FunctionalComponent: - return updateFunctionalComponent(current, workInProgress); - case ClassComponent: - return updateClassComponent(current, workInProgress, renderExpirationTime); - case HostRoot: - return updateHostRoot(current, workInProgress, renderExpirationTime); - case HostComponent: - return updateHostComponent(current, workInProgress, renderExpirationTime); - case HostText: - return updateHostText(current, workInProgress); - case CallHandlerPhase: - // This is a restart. Reset the tag to the initial phase. - workInProgress.tag = CallComponent; - // Intentionally fall through since this is now the same. - case CallComponent: - return updateCallComponent(current, workInProgress, renderExpirationTime); - case ReturnComponent: - // A return component is just a placeholder, we can just run through the - // next one immediately. - return null; - case HostPortal: - return updatePortalComponent(current, workInProgress, renderExpirationTime); - case ForwardRef: - return updateForwardRef(current, workInProgress); - case Fragment: - return updateFragment(current, workInProgress); - case Mode: - return updateMode(current, workInProgress); - case ContextProvider: - return updateContextProvider(current, workInProgress, renderExpirationTime); - case ContextConsumer: - return updateContextConsumer(current, workInProgress, renderExpirationTime); - default: - invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.'); - } - } - - return { - beginWork: beginWork - }; -}; - -var ReactFiberCompleteWork = function (config, hostContext, legacyContext, newContext, hydrationContext) { - var createInstance = config.createInstance, - createTextInstance = config.createTextInstance, - appendInitialChild = config.appendInitialChild, - finalizeInitialChildren = config.finalizeInitialChildren, - prepareUpdate = config.prepareUpdate, - mutation = config.mutation, - persistence = config.persistence; - var getRootHostContainer = hostContext.getRootHostContainer, - popHostContext = hostContext.popHostContext, - getHostContext = hostContext.getHostContext, - popHostContainer = hostContext.popHostContainer; - var popLegacyContextProvider = legacyContext.popContextProvider, - popTopLevelLegacyContextObject = legacyContext.popTopLevelContextObject; - var popProvider = newContext.popProvider; - var prepareToHydrateHostInstance = hydrationContext.prepareToHydrateHostInstance, - prepareToHydrateHostTextInstance = hydrationContext.prepareToHydrateHostTextInstance, - popHydrationState = hydrationContext.popHydrationState; - - - function markUpdate(workInProgress) { - // Tag the fiber with an update effect. This turns a Placement into - // a PlacementAndUpdate. - workInProgress.effectTag |= Update; - } - - function markRef(workInProgress) { - workInProgress.effectTag |= Ref; - } - - function appendAllReturns(returns, workInProgress) { - var node = workInProgress.stateNode; - if (node) { - node['return'] = workInProgress; - } - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText || node.tag === HostPortal) { - invariant(false, 'A call cannot have host component children.'); - } else if (node.tag === ReturnComponent) { - returns.push(node.pendingProps.value); - } else if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === workInProgress) { - return; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - } - - function moveCallToHandlerPhase(current, workInProgress, renderExpirationTime) { - var props = workInProgress.memoizedProps; - !props ? invariant(false, 'Should be resolved by now. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - // First step of the call has completed. Now we need to do the second. - // TODO: It would be nice to have a multi stage call represented by a - // single component, or at least tail call optimize nested ones. Currently - // that requires additional fields that we don't want to add to the fiber. - // So this requires nested handlers. - // Note: This doesn't mutate the alternate node. I don't think it needs to - // since this stage is reset for every pass. - workInProgress.tag = CallHandlerPhase; - - // Build up the returns. - // TODO: Compare this to a generator or opaque helpers like Children. - var returns = []; - appendAllReturns(returns, workInProgress); - var fn = props.handler; - var childProps = props.props; - var nextChildren = fn(childProps, returns); - - var currentFirstChild = current !== null ? current.child : null; - workInProgress.child = reconcileChildFibers(workInProgress, currentFirstChild, nextChildren, renderExpirationTime); - return workInProgress.child; - } - - function appendAllChildren(parent, workInProgress) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendInitialChild(parent, node.stateNode); - } else if (node.tag === HostPortal) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === workInProgress) { - return; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === workInProgress) { - return; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - } - - var updateHostContainer = void 0; - var updateHostComponent = void 0; - var updateHostText = void 0; - if (mutation) { - if (enableMutatingReconciler) { - // Mutation mode - updateHostContainer = function (workInProgress) { - // Noop - }; - updateHostComponent = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) { - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. All the work is done in commitWork. - if (updatePayload) { - markUpdate(workInProgress); - } - }; - updateHostText = function (current, workInProgress, oldText, newText) { - // If the text differs, mark it as an update. All the work in done in commitWork. - if (oldText !== newText) { - markUpdate(workInProgress); - } - }; - } else { - invariant(false, 'Mutating reconciler is disabled.'); - } - } else if (persistence) { - if (enablePersistentReconciler) { - // Persistent host tree mode - var cloneInstance = persistence.cloneInstance, - createContainerChildSet = persistence.createContainerChildSet, - appendChildToContainerChildSet = persistence.appendChildToContainerChildSet, - finalizeContainerChildren = persistence.finalizeContainerChildren; - - // An unfortunate fork of appendAllChildren because we have two different parent types. - - var appendAllChildrenToContainer = function (containerChildSet, workInProgress) { - // We only have the top Fiber that was created but we need recurse down its - // children to find all the terminal nodes. - var node = workInProgress.child; - while (node !== null) { - if (node.tag === HostComponent || node.tag === HostText) { - appendChildToContainerChildSet(containerChildSet, node.stateNode); - } else if (node.tag === HostPortal) { - // If we have a portal child, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === workInProgress) { - return; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === workInProgress) { - return; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - }; - updateHostContainer = function (workInProgress) { - var portalOrRoot = workInProgress.stateNode; - var childrenUnchanged = workInProgress.firstEffect === null; - if (childrenUnchanged) { - // No changes, just reuse the existing instance. - } else { - var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. - appendAllChildrenToContainer(newChildSet, workInProgress); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. - markUpdate(workInProgress); - finalizeContainerChildren(container, newChildSet); - } - }; - updateHostComponent = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) { - // If there are no effects associated with this node, then none of our children had any updates. - // This guarantees that we can reuse all of them. - var childrenUnchanged = workInProgress.firstEffect === null; - var currentInstance = current.stateNode; - if (childrenUnchanged && updatePayload === null) { - // No changes, just reuse the existing instance. - // Note that this might release a previous clone. - workInProgress.stateNode = currentInstance; - } else { - var recyclableInstance = workInProgress.stateNode; - var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); - if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { - markUpdate(workInProgress); - } - workInProgress.stateNode = newInstance; - if (childrenUnchanged) { - // If there are no other effects in this tree, we need to flag this node as having one. - // Even though we're not going to use it for anything. - // Otherwise parents won't know that there are new children to propagate upwards. - markUpdate(workInProgress); - } else { - // If children might have changed, we have to add them all to the set. - appendAllChildren(newInstance, workInProgress); - } - } - }; - updateHostText = function (current, workInProgress, oldText, newText) { - if (oldText !== newText) { - // If the text content differs, we'll create a new text instance for it. - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. - // This lets the parents know that at least one of their children has changed. - markUpdate(workInProgress); - } - }; - } else { - invariant(false, 'Persistent reconciler is disabled.'); - } - } else { - if (enableNoopReconciler) { - // No host operations - updateHostContainer = function (workInProgress) { - // Noop - }; - updateHostComponent = function (current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext) { - // Noop - }; - updateHostText = function (current, workInProgress, oldText, newText) { - // Noop - }; - } else { - invariant(false, 'Noop reconciler is disabled.'); - } - } - - function completeWork(current, workInProgress, renderExpirationTime) { - var newProps = workInProgress.pendingProps; - switch (workInProgress.tag) { - case FunctionalComponent: - return null; - case ClassComponent: - { - // We are leaving this subtree, so pop context if any. - popLegacyContextProvider(workInProgress); - - // If this component caught an error, schedule an error log effect. - var instance = workInProgress.stateNode; - var updateQueue = workInProgress.updateQueue; - if (updateQueue !== null && updateQueue.capturedValues !== null) { - workInProgress.effectTag &= ~DidCapture; - if (typeof instance.componentDidCatch === 'function') { - workInProgress.effectTag |= ErrLog; - } else { - // Normally we clear this in the commit phase, but since we did not - // schedule an effect, we need to reset it here. - updateQueue.capturedValues = null; - } - } - return null; - } - case HostRoot: - { - popHostContainer(workInProgress); - popTopLevelLegacyContextObject(workInProgress); - var fiberRoot = workInProgress.stateNode; - if (fiberRoot.pendingContext) { - fiberRoot.context = fiberRoot.pendingContext; - fiberRoot.pendingContext = null; - } - if (current === null || current.child === null) { - // If we hydrated, pop so that we can delete any remaining children - // that weren't hydrated. - popHydrationState(workInProgress); - // This resets the hacky state to fix isMounted before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag &= ~Placement; - } - updateHostContainer(workInProgress); - - var _updateQueue = workInProgress.updateQueue; - if (_updateQueue !== null && _updateQueue.capturedValues !== null) { - workInProgress.effectTag |= ErrLog; - } - return null; - } - case HostComponent: - { - popHostContext(workInProgress); - var rootContainerInstance = getRootHostContainer(); - var type = workInProgress.type; - if (current !== null && workInProgress.stateNode != null) { - // If we have an alternate, that means this is an update and we need to - // schedule a side-effect to do the updates. - var oldProps = current.memoizedProps; - // If we get updated because one of our children updated, we don't - // have newProps so we'll have to reuse them. - // TODO: Split the update API as separate for the props vs. children. - // Even better would be if children weren't special cased at all tho. - var _instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host - // component is hitting the resume path. Figure out why. Possibly - // related to `hidden`. - var updatePayload = prepareUpdate(_instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); - - updateHostComponent(current, workInProgress, updatePayload, type, oldProps, newProps, rootContainerInstance, currentHostContext); - - if (current.ref !== workInProgress.ref) { - markRef(workInProgress); - } - } else { - if (!newProps) { - !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0; - // This can happen when we abort work. - return null; - } - - var _currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context - // "stack" as the parent. Then append children as we go in beginWork - // or completeWork depending on we want to add then top->down or - // bottom->up. Top->down is faster in IE11. - var wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { - // TODO: Move this and createInstance step into the beginPhase - // to consolidate. - if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, _currentHostContext)) { - // If changes to the hydrated node needs to be applied at the - // commit-phase we mark this as such. - markUpdate(workInProgress); - } - } else { - var _instance2 = createInstance(type, newProps, rootContainerInstance, _currentHostContext, workInProgress); - - appendAllChildren(_instance2, workInProgress); - - // Certain renderers require commit-time effects for initial mount. - // (eg DOM renderer supports auto-focus for certain elements). - // Make sure such renderers get scheduled for later work. - if (finalizeInitialChildren(_instance2, type, newProps, rootContainerInstance, _currentHostContext)) { - markUpdate(workInProgress); - } - workInProgress.stateNode = _instance2; - } - - if (workInProgress.ref !== null) { - // If there is a ref on a host node we need to schedule a callback - markRef(workInProgress); - } - } - return null; - } - case HostText: - { - var newText = newProps; - if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need - // to schedule a side-effect to do the updates. - updateHostText(current, workInProgress, oldText, newText); - } else { - if (typeof newText !== 'string') { - !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0; - // This can happen when we abort work. - return null; - } - var _rootContainerInstance = getRootHostContainer(); - var _currentHostContext2 = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress); - if (_wasHydrated) { - if (prepareToHydrateHostTextInstance(workInProgress)) { - markUpdate(workInProgress); - } - } else { - workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext2, workInProgress); - } - } - return null; - } - case CallComponent: - return moveCallToHandlerPhase(current, workInProgress, renderExpirationTime); - case CallHandlerPhase: - // Reset the tag to now be a first phase call. - workInProgress.tag = CallComponent; - return null; - case ReturnComponent: - // Does nothing. - return null; - case ForwardRef: - return null; - case Fragment: - return null; - case Mode: - return null; - case HostPortal: - popHostContainer(workInProgress); - updateHostContainer(workInProgress); - return null; - case ContextProvider: - // Pop provider fiber - popProvider(workInProgress); - return null; - case ContextConsumer: - return null; - // Error cases - case IndeterminateComponent: - invariant(false, 'An indeterminate component should have become determinate before completing. This error is likely caused by a bug in React. Please file an issue.'); - // eslint-disable-next-line no-fallthrough - default: - invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.'); - } - } - - return { - completeWork: completeWork - }; -}; - -function createCapturedValue(value, source) { - // If the value is an error, call this function immediately after it is thrown - // so the stack is accurate. - return { - value: value, - source: source, - stack: getStackAddendumByWorkInProgressFiber(source) - }; -} - -var ReactFiberUnwindWork = function (hostContext, legacyContext, newContext, scheduleWork, isAlreadyFailedLegacyErrorBoundary) { - var popHostContainer = hostContext.popHostContainer, - popHostContext = hostContext.popHostContext; - var popLegacyContextProvider = legacyContext.popContextProvider, - popTopLevelLegacyContextObject = legacyContext.popTopLevelContextObject; - var popProvider = newContext.popProvider; - - - function throwException(returnFiber, sourceFiber, rawValue) { - // The source fiber did not complete. - sourceFiber.effectTag |= Incomplete; - // Its effect list is no longer valid. - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - - var value = createCapturedValue(rawValue, sourceFiber); - - var workInProgress = returnFiber; - do { - switch (workInProgress.tag) { - case HostRoot: - { - // Uncaught error - var errorInfo = value; - ensureUpdateQueues(workInProgress); - var updateQueue = workInProgress.updateQueue; - updateQueue.capturedValues = [errorInfo]; - workInProgress.effectTag |= ShouldCapture; - return; - } - case ClassComponent: - // Capture and retry - var ctor = workInProgress.type; - var _instance = workInProgress.stateNode; - if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromCatch === 'function' && enableGetDerivedStateFromCatch || _instance !== null && typeof _instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(_instance))) { - ensureUpdateQueues(workInProgress); - var _updateQueue = workInProgress.updateQueue; - var capturedValues = _updateQueue.capturedValues; - if (capturedValues === null) { - _updateQueue.capturedValues = [value]; - } else { - capturedValues.push(value); - } - workInProgress.effectTag |= ShouldCapture; - return; - } - break; - default: - break; - } - workInProgress = workInProgress['return']; - } while (workInProgress !== null); - } - - function unwindWork(workInProgress) { - switch (workInProgress.tag) { - case ClassComponent: - { - popLegacyContextProvider(workInProgress); - var effectTag = workInProgress.effectTag; - if (effectTag & ShouldCapture) { - workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture; - return workInProgress; - } - return null; - } - case HostRoot: - { - popHostContainer(workInProgress); - popTopLevelLegacyContextObject(workInProgress); - var _effectTag = workInProgress.effectTag; - if (_effectTag & ShouldCapture) { - workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture; - return workInProgress; - } - return null; - } - case HostComponent: - { - popHostContext(workInProgress); - return null; - } - case HostPortal: - popHostContainer(workInProgress); - return null; - case ContextProvider: - popProvider(workInProgress); - return null; - default: - return null; - } - } - - function unwindInterruptedWork(interruptedWork) { - switch (interruptedWork.tag) { - case ClassComponent: - { - popLegacyContextProvider(interruptedWork); - break; - } - case HostRoot: - { - popHostContainer(interruptedWork); - popTopLevelLegacyContextObject(interruptedWork); - break; - } - case HostComponent: - { - popHostContext(interruptedWork); - break; - } - case HostPortal: - popHostContainer(interruptedWork); - break; - case ContextProvider: - popProvider(interruptedWork); - break; - default: - break; - } - } - - return { - throwException: throwException, - unwindWork: unwindWork, - unwindInterruptedWork: unwindInterruptedWork - }; -}; - -// This module is forked in different environments. -// By default, return `true` to log errors to the console. -// Forks can return `false` if this isn't desirable. -function showErrorDialog(capturedError) { - return true; -} - -function logCapturedError(capturedError) { - var logError = showErrorDialog(capturedError); - - // Allow injected showErrorDialog() to prevent default console.error logging. - // This enables renderers like ReactNative to better manage redbox behavior. - if (logError === false) { - return; - } - - var error = capturedError.error; - var suppressLogging = error && error.suppressReactErrorLogging; - if (suppressLogging) { - return; - } - - { - var componentName = capturedError.componentName, - componentStack = capturedError.componentStack, - errorBoundaryName = capturedError.errorBoundaryName, - errorBoundaryFound = capturedError.errorBoundaryFound, - willRetry = capturedError.willRetry; - - - var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:'; - - var errorBoundaryMessage = void 0; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - if (errorBoundaryFound && errorBoundaryName) { - if (willRetry) { - errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.'); - } else { - errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.'; - } - } else { - errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.'; - } - var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage); - - // In development, we provide our own message with just the component stack. - // We don't include the original error message and JS stack because the browser - // has already printed it. Even if the application swallows the error, it is still - // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. - console.error(combinedMessage); - } -} - -var invokeGuardedCallback$3 = ReactErrorUtils.invokeGuardedCallback; -var hasCaughtError$1 = ReactErrorUtils.hasCaughtError; -var clearCaughtError$1 = ReactErrorUtils.clearCaughtError; - - -var didWarnAboutUndefinedSnapshotBeforeUpdate = null; -{ - didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); -} - -function logError(boundary, errorInfo) { - var source = errorInfo.source; - var stack = errorInfo.stack; - if (stack === null) { - stack = getStackAddendumByWorkInProgressFiber(source); - } - - var capturedError = { - componentName: source !== null ? getComponentName(source) : null, - componentStack: stack !== null ? stack : '', - error: errorInfo.value, - errorBoundary: null, - errorBoundaryName: null, - errorBoundaryFound: false, - willRetry: false - }; - - if (boundary !== null && boundary.tag === ClassComponent) { - capturedError.errorBoundary = boundary.stateNode; - capturedError.errorBoundaryName = getComponentName(boundary); - capturedError.errorBoundaryFound = true; - capturedError.willRetry = true; - } - - try { - logCapturedError(capturedError); - } catch (e) { - // Prevent cycle if logCapturedError() throws. - // A cycle may still occur if logCapturedError renders a component that throws. - var suppressLogging = e && e.suppressReactErrorLogging; - if (!suppressLogging) { - console.error(e); - } - } -} - -var ReactFiberCommitWork = function (config, captureError, scheduleWork, computeExpirationForFiber, markLegacyErrorBoundaryAsFailed, recalculateCurrentTime) { - var getPublicInstance = config.getPublicInstance, - mutation = config.mutation, - persistence = config.persistence; - - - var callComponentWillUnmountWithTimer = function (current, instance) { - startPhaseTimer(current, 'componentWillUnmount'); - instance.props = current.memoizedProps; - instance.state = current.memoizedState; - instance.componentWillUnmount(); - stopPhaseTimer(); - }; - - // Capture errors so they don't interrupt unmounting. - function safelyCallComponentWillUnmount(current, instance) { - { - invokeGuardedCallback$3(null, callComponentWillUnmountWithTimer, null, current, instance); - if (hasCaughtError$1()) { - var unmountError = clearCaughtError$1(); - captureError(current, unmountError); - } - } - } - - function safelyDetachRef(current) { - var ref = current.ref; - if (ref !== null) { - if (typeof ref === 'function') { - { - invokeGuardedCallback$3(null, ref, null, null); - if (hasCaughtError$1()) { - var refError = clearCaughtError$1(); - captureError(current, refError); - } - } - } else { - ref.current = null; - } - } - } - - function commitBeforeMutationLifeCycles(current, finishedWork) { - switch (finishedWork.tag) { - case ClassComponent: - { - if (finishedWork.effectTag & Snapshot) { - if (current !== null) { - var prevProps = current.memoizedProps; - var prevState = current.memoizedState; - startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate'); - var _instance = finishedWork.stateNode; - _instance.props = finishedWork.memoizedProps; - _instance.state = finishedWork.memoizedState; - var snapshot = _instance.getSnapshotBeforeUpdate(prevProps, prevState); - { - var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; - if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { - didWarnSet.add(finishedWork.type); - warning(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork)); - } - } - _instance.__reactInternalSnapshotBeforeUpdate = snapshot; - stopPhaseTimer(); - } - } - return; - } - case HostRoot: - case HostComponent: - case HostText: - case HostPortal: - // Nothing to do for these component types - return; - default: - { - invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); - } - } - } - - function commitLifeCycles(finishedRoot, current, finishedWork, currentTime, committedExpirationTime) { - switch (finishedWork.tag) { - case ClassComponent: - { - var _instance2 = finishedWork.stateNode; - if (finishedWork.effectTag & Update) { - if (current === null) { - startPhaseTimer(finishedWork, 'componentDidMount'); - _instance2.props = finishedWork.memoizedProps; - _instance2.state = finishedWork.memoizedState; - _instance2.componentDidMount(); - stopPhaseTimer(); - } else { - var prevProps = current.memoizedProps; - var prevState = current.memoizedState; - startPhaseTimer(finishedWork, 'componentDidUpdate'); - _instance2.props = finishedWork.memoizedProps; - _instance2.state = finishedWork.memoizedState; - _instance2.componentDidUpdate(prevProps, prevState, _instance2.__reactInternalSnapshotBeforeUpdate); - stopPhaseTimer(); - } - } - var updateQueue = finishedWork.updateQueue; - if (updateQueue !== null) { - commitCallbacks(updateQueue, _instance2); - } - return; - } - case HostRoot: - { - var _updateQueue = finishedWork.updateQueue; - if (_updateQueue !== null) { - var _instance3 = null; - if (finishedWork.child !== null) { - switch (finishedWork.child.tag) { - case HostComponent: - _instance3 = getPublicInstance(finishedWork.child.stateNode); - break; - case ClassComponent: - _instance3 = finishedWork.child.stateNode; - break; - } - } - commitCallbacks(_updateQueue, _instance3); - } - return; - } - case HostComponent: - { - var _instance4 = finishedWork.stateNode; - - // Renderers may schedule work to be done after host components are mounted - // (eg DOM renderer may schedule auto-focus for inputs and form controls). - // These effects should only be committed when components are first mounted, - // aka when there is no current/alternate. - if (current === null && finishedWork.effectTag & Update) { - var type = finishedWork.type; - var props = finishedWork.memoizedProps; - commitMount(_instance4, type, props, finishedWork); - } - - return; - } - case HostText: - { - // We have no life-cycles associated with text. - return; - } - case HostPortal: - { - // We have no life-cycles associated with portals. - return; - } - default: - { - invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); - } - } - } - - function commitErrorLogging(finishedWork, onUncaughtError) { - switch (finishedWork.tag) { - case ClassComponent: - { - var ctor = finishedWork.type; - var _instance5 = finishedWork.stateNode; - var updateQueue = finishedWork.updateQueue; - !(updateQueue !== null && updateQueue.capturedValues !== null) ? invariant(false, 'An error logging effect should not have been scheduled if no errors were captured. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var capturedErrors = updateQueue.capturedValues; - updateQueue.capturedValues = null; - - if (typeof ctor.getDerivedStateFromCatch !== 'function') { - // To preserve the preexisting retry behavior of error boundaries, - // we keep track of which ones already failed during this batch. - // This gets reset before we yield back to the browser. - // TODO: Warn in strict mode if getDerivedStateFromCatch is - // not defined. - markLegacyErrorBoundaryAsFailed(_instance5); - } - - _instance5.props = finishedWork.memoizedProps; - _instance5.state = finishedWork.memoizedState; - for (var i = 0; i < capturedErrors.length; i++) { - var errorInfo = capturedErrors[i]; - var _error = errorInfo.value; - var stack = errorInfo.stack; - logError(finishedWork, errorInfo); - _instance5.componentDidCatch(_error, { - componentStack: stack !== null ? stack : '' - }); - } - } - break; - case HostRoot: - { - var _updateQueue2 = finishedWork.updateQueue; - !(_updateQueue2 !== null && _updateQueue2.capturedValues !== null) ? invariant(false, 'An error logging effect should not have been scheduled if no errors were captured. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var _capturedErrors = _updateQueue2.capturedValues; - _updateQueue2.capturedValues = null; - for (var _i = 0; _i < _capturedErrors.length; _i++) { - var _errorInfo = _capturedErrors[_i]; - logError(finishedWork, _errorInfo); - onUncaughtError(_errorInfo.value); - } - break; - } - default: - invariant(false, 'This unit of work tag cannot capture errors. This error is likely caused by a bug in React. Please file an issue.'); - } - } - - function commitAttachRef(finishedWork) { - var ref = finishedWork.ref; - if (ref !== null) { - var _instance6 = finishedWork.stateNode; - var instanceToUse = void 0; - switch (finishedWork.tag) { - case HostComponent: - instanceToUse = getPublicInstance(_instance6); - break; - default: - instanceToUse = _instance6; - } - if (typeof ref === 'function') { - ref(instanceToUse); - } else { - { - if (!ref.hasOwnProperty('current')) { - warning(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork), getStackAddendumByWorkInProgressFiber(finishedWork)); - } - } - - ref.current = instanceToUse; - } - } - } - - function commitDetachRef(current) { - var currentRef = current.ref; - if (currentRef !== null) { - if (typeof currentRef === 'function') { - currentRef(null); - } else { - currentRef.current = null; - } - } - } - - // User-originating errors (lifecycles and refs) should not interrupt - // deletion, so don't let them throw. Host-originating errors should - // interrupt deletion, so it's okay - function commitUnmount(current) { - if (typeof onCommitUnmount === 'function') { - onCommitUnmount(current); - } - - switch (current.tag) { - case ClassComponent: - { - safelyDetachRef(current); - var _instance7 = current.stateNode; - if (typeof _instance7.componentWillUnmount === 'function') { - safelyCallComponentWillUnmount(current, _instance7); - } - return; - } - case HostComponent: - { - safelyDetachRef(current); - return; - } - case CallComponent: - { - commitNestedUnmounts(current.stateNode); - return; - } - case HostPortal: - { - // TODO: this is recursive. - // We are also not using this parent because - // the portal will get pushed immediately. - if (enableMutatingReconciler && mutation) { - unmountHostComponents(current); - } else if (enablePersistentReconciler && persistence) { - emptyPortalContainer(current); - } - return; - } - } - } - - function commitNestedUnmounts(root) { - // While we're inside a removed host node we don't want to call - // removeChild on the inner nodes because they're removed by the top - // call anyway. We also want to call componentWillUnmount on all - // composites before this host node is removed from the tree. Therefore - var node = root; - while (true) { - commitUnmount(node); - // Visit children because they may contain more composite or host nodes. - // Skip portals because commitUnmount() currently visits them recursively. - if (node.child !== null && ( - // If we use mutation we drill down into portals using commitUnmount above. - // If we don't use mutation we drill down into portals here instead. - !mutation || node.tag !== HostPortal)) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === root) { - return; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === root) { - return; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - } - - function detachFiber(current) { - // Cut off the return pointers to disconnect it from the tree. Ideally, we - // should clear the child pointer of the parent alternate to let this - // get GC:ed but we don't know which for sure which parent is the current - // one so we'll settle for GC:ing the subtree of this child. This child - // itself will be GC:ed when the parent updates the next time. - current['return'] = null; - current.child = null; - if (current.alternate) { - current.alternate.child = null; - current.alternate['return'] = null; - } - } - - var emptyPortalContainer = void 0; - - if (!mutation) { - var commitContainer = void 0; - if (persistence) { - var replaceContainerChildren = persistence.replaceContainerChildren, - createContainerChildSet = persistence.createContainerChildSet; - - emptyPortalContainer = function (current) { - var portal = current.stateNode; - var containerInfo = portal.containerInfo; - - var emptyChildSet = createContainerChildSet(containerInfo); - replaceContainerChildren(containerInfo, emptyChildSet); - }; - commitContainer = function (finishedWork) { - switch (finishedWork.tag) { - case ClassComponent: - { - return; - } - case HostComponent: - { - return; - } - case HostText: - { - return; - } - case HostRoot: - case HostPortal: - { - var portalOrRoot = finishedWork.stateNode; - var containerInfo = portalOrRoot.containerInfo, - _pendingChildren = portalOrRoot.pendingChildren; - - replaceContainerChildren(containerInfo, _pendingChildren); - return; - } - default: - { - invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); - } - } - }; - } else { - commitContainer = function (finishedWork) { - // Noop - }; - } - if (enablePersistentReconciler || enableNoopReconciler) { - return { - commitResetTextContent: function (finishedWork) {}, - commitPlacement: function (finishedWork) {}, - commitDeletion: function (current) { - // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(current); - detachFiber(current); - }, - commitWork: function (current, finishedWork) { - commitContainer(finishedWork); - }, - - commitLifeCycles: commitLifeCycles, - commitBeforeMutationLifeCycles: commitBeforeMutationLifeCycles, - commitErrorLogging: commitErrorLogging, - commitAttachRef: commitAttachRef, - commitDetachRef: commitDetachRef - }; - } else if (persistence) { - invariant(false, 'Persistent reconciler is disabled.'); - } else { - invariant(false, 'Noop reconciler is disabled.'); - } - } - var commitMount = mutation.commitMount, - commitUpdate = mutation.commitUpdate, - resetTextContent = mutation.resetTextContent, - commitTextUpdate = mutation.commitTextUpdate, - appendChild = mutation.appendChild, - appendChildToContainer = mutation.appendChildToContainer, - insertBefore = mutation.insertBefore, - insertInContainerBefore = mutation.insertInContainerBefore, - removeChild = mutation.removeChild, - removeChildFromContainer = mutation.removeChildFromContainer; - - - function getHostParentFiber(fiber) { - var parent = fiber['return']; - while (parent !== null) { - if (isHostParent(parent)) { - return parent; - } - parent = parent['return']; - } - invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.'); - } - - function isHostParent(fiber) { - return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; - } - - function getHostSibling(fiber) { - // We're going to search forward into the tree until we find a sibling host - // node. Unfortunately, if multiple insertions are done in a row we have to - // search past them. This leads to exponential search for the next sibling. - var node = fiber; - siblings: while (true) { - // If we didn't find anything, let's try the next sibling. - while (node.sibling === null) { - if (node['return'] === null || isHostParent(node['return'])) { - // If we pop out of the root or hit the parent the fiber we are the - // last sibling. - return null; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - while (node.tag !== HostComponent && node.tag !== HostText) { - // If it is not host node and, we might have a host node inside it. - // Try to search down until we find one. - if (node.effectTag & Placement) { - // If we don't have a child, try the siblings instead. - continue siblings; - } - // If we don't have a child, try the siblings instead. - // We also skip portals because they are not part of this host tree. - if (node.child === null || node.tag === HostPortal) { - continue siblings; - } else { - node.child['return'] = node; - node = node.child; - } - } - // Check if this host node is stable or about to be placed. - if (!(node.effectTag & Placement)) { - // Found it! - return node.stateNode; - } - } - } - - function commitPlacement(finishedWork) { - // Recursively insert all host nodes into the parent. - var parentFiber = getHostParentFiber(finishedWork); - var parent = void 0; - var isContainer = void 0; - switch (parentFiber.tag) { - case HostComponent: - parent = parentFiber.stateNode; - isContainer = false; - break; - case HostRoot: - parent = parentFiber.stateNode.containerInfo; - isContainer = true; - break; - case HostPortal: - parent = parentFiber.stateNode.containerInfo; - isContainer = true; - break; - default: - invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.'); - } - if (parentFiber.effectTag & ContentReset) { - // Reset the text content of the parent before doing any insertions - resetTextContent(parent); - // Clear ContentReset from the effect tag - parentFiber.effectTag &= ~ContentReset; - } - - var before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need recurse down its - // children to find all the terminal nodes. - var node = finishedWork; - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - if (before) { - if (isContainer) { - insertInContainerBefore(parent, node.stateNode, before); - } else { - insertBefore(parent, node.stateNode, before); - } - } else { - if (isContainer) { - appendChildToContainer(parent, node.stateNode); - } else { - appendChild(parent, node.stateNode); - } - } - } else if (node.tag === HostPortal) { - // If the insertion itself is a portal, then we don't want to traverse - // down its children. Instead, we'll get insertions from each child in - // the portal directly. - } else if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - if (node === finishedWork) { - return; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === finishedWork) { - return; - } - node = node['return']; - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - } - - function unmountHostComponents(current) { - // We only have the top Fiber that was inserted but we need recurse down its - var node = current; - - // Each iteration, currentParent is populated with node's host parent if not - // currentParentIsValid. - var currentParentIsValid = false; - var currentParent = void 0; - var currentParentIsContainer = void 0; - - while (true) { - if (!currentParentIsValid) { - var parent = node['return']; - findParent: while (true) { - !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0; - switch (parent.tag) { - case HostComponent: - currentParent = parent.stateNode; - currentParentIsContainer = false; - break findParent; - case HostRoot: - currentParent = parent.stateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - case HostPortal: - currentParent = parent.stateNode.containerInfo; - currentParentIsContainer = true; - break findParent; - } - parent = parent['return']; - } - currentParentIsValid = true; - } - - if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node); - // After all the children have unmounted, it is now safe to remove the - // node from the tree. - if (currentParentIsContainer) { - removeChildFromContainer(currentParent, node.stateNode); - } else { - removeChild(currentParent, node.stateNode); - } - // Don't visit children because we already visited them. - } else if (node.tag === HostPortal) { - // When we go into a portal, it becomes the parent to remove from. - // We will reassign it back when we pop the portal on the way up. - currentParent = node.stateNode.containerInfo; - // Visit children because portals might contain host components. - if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - } else { - commitUnmount(node); - // Visit children because we may find more host components below. - if (node.child !== null) { - node.child['return'] = node; - node = node.child; - continue; - } - } - if (node === current) { - return; - } - while (node.sibling === null) { - if (node['return'] === null || node['return'] === current) { - return; - } - node = node['return']; - if (node.tag === HostPortal) { - // When we go out of the portal, we need to restore the parent. - // Since we don't keep a stack of them, we will search for it. - currentParentIsValid = false; - } - } - node.sibling['return'] = node['return']; - node = node.sibling; - } - } - - function commitDeletion(current) { - // Recursively delete all host nodes from the parent. - // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(current); - detachFiber(current); - } - - function commitWork(current, finishedWork) { - switch (finishedWork.tag) { - case ClassComponent: - { - return; - } - case HostComponent: - { - var _instance8 = finishedWork.stateNode; - if (_instance8 != null) { - // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - var oldProps = current !== null ? current.memoizedProps : newProps; - var type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. - var updatePayload = finishedWork.updateQueue; - finishedWork.updateQueue = null; - if (updatePayload !== null) { - commitUpdate(_instance8, updatePayload, type, oldProps, newProps, finishedWork); - } - } - return; - } - case HostText: - { - !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps - // as the newProps. The updatePayload will contain the real change in - // this case. - var oldText = current !== null ? current.memoizedProps : newText; - commitTextUpdate(textInstance, oldText, newText); - return; - } - case HostRoot: - { - return; - } - default: - { - invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); - } - } - } - - function commitResetTextContent(current) { - resetTextContent(current.stateNode); - } - - if (enableMutatingReconciler) { - return { - commitBeforeMutationLifeCycles: commitBeforeMutationLifeCycles, - commitResetTextContent: commitResetTextContent, - commitPlacement: commitPlacement, - commitDeletion: commitDeletion, - commitWork: commitWork, - commitLifeCycles: commitLifeCycles, - commitErrorLogging: commitErrorLogging, - commitAttachRef: commitAttachRef, - commitDetachRef: commitDetachRef - }; - } else { - invariant(false, 'Mutating reconciler is disabled.'); - } -}; - -var NO_CONTEXT = {}; - -var ReactFiberHostContext = function (config, stack) { - var getChildHostContext = config.getChildHostContext, - getRootHostContext = config.getRootHostContext; - var createCursor = stack.createCursor, - push = stack.push, - pop = stack.pop; - - - var contextStackCursor = createCursor(NO_CONTEXT); - var contextFiberStackCursor = createCursor(NO_CONTEXT); - var rootInstanceStackCursor = createCursor(NO_CONTEXT); - - function requiredContext(c) { - !(c !== NO_CONTEXT) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0; - return c; - } - - function getRootHostContainer() { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - return rootInstance; - } - - function pushHostContainer(fiber, nextRootInstance) { - // Push current root instance onto the stack; - // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - - // Finally, we need to push the host context to the stack. - // However, we can't just call getRootHostContext() and push it because - // we'd have a different number of entries on the stack depending on - // whether getRootHostContext() throws somewhere in renderer code or not. - // So we push an empty value first. This lets us safely unwind on errors. - push(contextStackCursor, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. - pop(contextStackCursor, fiber); - push(contextStackCursor, nextRootContext, fiber); - } - - function popHostContainer(fiber) { - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); - pop(rootInstanceStackCursor, fiber); - } - - function getHostContext() { - var context = requiredContext(contextStackCursor.current); - return context; - } - - function pushHostContext(fiber) { - var rootInstance = requiredContext(rootInstanceStackCursor.current); - var context = requiredContext(contextStackCursor.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); - - // Don't push this Fiber's context unless it's unique. - if (context === nextContext) { - return; - } - - // Track the context and the Fiber that provided it. - // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - push(contextStackCursor, nextContext, fiber); - } - - function popHostContext(fiber) { - // Do not pop unless this Fiber provided the current context. - // pushHostContext() only pushes Fibers that provide unique contexts. - if (contextFiberStackCursor.current !== fiber) { - return; - } - - pop(contextStackCursor, fiber); - pop(contextFiberStackCursor, fiber); - } - - return { - getHostContext: getHostContext, - getRootHostContainer: getRootHostContainer, - popHostContainer: popHostContainer, - popHostContext: popHostContext, - pushHostContainer: pushHostContainer, - pushHostContext: pushHostContext - }; -}; - -var ReactFiberHydrationContext = function (config) { - var shouldSetTextContent = config.shouldSetTextContent, - hydration = config.hydration; - - // If this doesn't have hydration mode. - - if (!hydration) { - return { - enterHydrationState: function () { - return false; - }, - resetHydrationState: function () {}, - tryToClaimNextHydratableInstance: function () {}, - prepareToHydrateHostInstance: function () { - invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.'); - }, - prepareToHydrateHostTextInstance: function () { - invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.'); - }, - popHydrationState: function (fiber) { - return false; - } - }; - } - - var canHydrateInstance = hydration.canHydrateInstance, - canHydrateTextInstance = hydration.canHydrateTextInstance, - getNextHydratableSibling = hydration.getNextHydratableSibling, - getFirstHydratableChild = hydration.getFirstHydratableChild, - hydrateInstance = hydration.hydrateInstance, - hydrateTextInstance = hydration.hydrateTextInstance, - didNotMatchHydratedContainerTextInstance = hydration.didNotMatchHydratedContainerTextInstance, - didNotMatchHydratedTextInstance = hydration.didNotMatchHydratedTextInstance, - didNotHydrateContainerInstance = hydration.didNotHydrateContainerInstance, - didNotHydrateInstance = hydration.didNotHydrateInstance, - didNotFindHydratableContainerInstance = hydration.didNotFindHydratableContainerInstance, - didNotFindHydratableContainerTextInstance = hydration.didNotFindHydratableContainerTextInstance, - didNotFindHydratableInstance = hydration.didNotFindHydratableInstance, - didNotFindHydratableTextInstance = hydration.didNotFindHydratableTextInstance; - - // The deepest Fiber on the stack involved in a hydration context. - // This may have been an insertion or a hydration. - - var hydrationParentFiber = null; - var nextHydratableInstance = null; - var isHydrating = false; - - function enterHydrationState(fiber) { - var parentInstance = fiber.stateNode.containerInfo; - nextHydratableInstance = getFirstHydratableChild(parentInstance); - hydrationParentFiber = fiber; - isHydrating = true; - return true; - } - - function deleteHydratableInstance(returnFiber, instance) { - { - switch (returnFiber.tag) { - case HostRoot: - didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance); - break; - case HostComponent: - didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); - break; - } - } - - var childToDelete = createFiberFromHostInstanceForDeletion(); - childToDelete.stateNode = instance; - childToDelete['return'] = returnFiber; - childToDelete.effectTag = Deletion; - - // This might seem like it belongs on progressedFirstDeletion. However, - // these children are not part of the reconciliation list of children. - // Even if we abort and rereconcile the children, that will try to hydrate - // again and the nodes are still in the host tree so these will be - // recreated. - if (returnFiber.lastEffect !== null) { - returnFiber.lastEffect.nextEffect = childToDelete; - returnFiber.lastEffect = childToDelete; - } else { - returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; - } - } - - function insertNonHydratedInstance(returnFiber, fiber) { - fiber.effectTag |= Placement; - { - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - switch (fiber.tag) { - case HostComponent: - var type = fiber.type; - var props = fiber.pendingProps; - didNotFindHydratableContainerInstance(parentContainer, type, props); - break; - case HostText: - var text = fiber.pendingProps; - didNotFindHydratableContainerTextInstance(parentContainer, text); - break; - } - break; - } - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - switch (fiber.tag) { - case HostComponent: - var _type = fiber.type; - var _props = fiber.pendingProps; - didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); - break; - case HostText: - var _text = fiber.pendingProps; - didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); - break; - } - break; - } - default: - return; - } - } - } - - function tryHydrate(fiber, nextInstance) { - switch (fiber.tag) { - case HostComponent: - { - var type = fiber.type; - var props = fiber.pendingProps; - var instance = canHydrateInstance(nextInstance, type, props); - if (instance !== null) { - fiber.stateNode = instance; - return true; - } - return false; - } - case HostText: - { - var text = fiber.pendingProps; - var textInstance = canHydrateTextInstance(nextInstance, text); - if (textInstance !== null) { - fiber.stateNode = textInstance; - return true; - } - return false; - } - default: - return false; - } - } - - function tryToClaimNextHydratableInstance(fiber) { - if (!isHydrating) { - return; - } - var nextInstance = nextHydratableInstance; - if (!nextInstance) { - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - if (!tryHydrate(fiber, nextInstance)) { - // If we can't hydrate this instance let's try the next one. - // We use this as a heuristic. It's based on intuition and not data so it - // might be flawed or unnecessary. - nextInstance = getNextHydratableSibling(nextInstance); - if (!nextInstance || !tryHydrate(fiber, nextInstance)) { - // Nothing to hydrate. Make it an insertion. - insertNonHydratedInstance(hydrationParentFiber, fiber); - isHydrating = false; - hydrationParentFiber = fiber; - return; - } - // We matched the next one, we'll now assume that the first one was - // superfluous and we'll delete it. Since we can't eagerly delete it - // we'll have to schedule a deletion. To do that, this node needs a dummy - // fiber associated with it. - deleteHydratableInstance(hydrationParentFiber, nextHydratableInstance); - } - hydrationParentFiber = fiber; - nextHydratableInstance = getFirstHydratableChild(nextInstance); - } - - function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { - var instance = fiber.stateNode; - var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); - // TODO: Type this specific to this type of component. - fiber.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there - // is a new ref we mark this as an update. - if (updatePayload !== null) { - return true; - } - return false; - } - - function prepareToHydrateHostTextInstance(fiber) { - var textInstance = fiber.stateNode; - var textContent = fiber.memoizedProps; - var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); - { - if (shouldUpdate) { - // We assume that prepareToHydrateHostTextInstance is called in a context where the - // hydration parent is the parent host component of this host text. - var returnFiber = hydrationParentFiber; - if (returnFiber !== null) { - switch (returnFiber.tag) { - case HostRoot: - { - var parentContainer = returnFiber.stateNode.containerInfo; - didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent); - break; - } - case HostComponent: - { - var parentType = returnFiber.type; - var parentProps = returnFiber.memoizedProps; - var parentInstance = returnFiber.stateNode; - didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent); - break; - } - } - } - } - } - return shouldUpdate; - } - - function popToNextHostParent(fiber) { - var parent = fiber['return']; - while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot) { - parent = parent['return']; - } - hydrationParentFiber = parent; - } - - function popHydrationState(fiber) { - if (fiber !== hydrationParentFiber) { - // We're deeper than the current hydration context, inside an inserted - // tree. - return false; - } - if (!isHydrating) { - // If we're not currently hydrating but we're in a hydration context, then - // we were an insertion and now need to pop up reenter hydration of our - // siblings. - popToNextHostParent(fiber); - isHydrating = true; - return false; - } - - var type = fiber.type; - - // If we have any remaining hydratable nodes, we need to delete them now. - // We only do this deeper than head and body since they tend to have random - // other nodes in them. We also ignore components with pure text content in - // side of them. - // TODO: Better heuristic. - if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) { - var nextInstance = nextHydratableInstance; - while (nextInstance) { - deleteHydratableInstance(fiber, nextInstance); - nextInstance = getNextHydratableSibling(nextInstance); - } - } - - popToNextHostParent(fiber); - nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; - return true; - } - - function resetHydrationState() { - hydrationParentFiber = null; - nextHydratableInstance = null; - isHydrating = false; - } - - return { - enterHydrationState: enterHydrationState, - resetHydrationState: resetHydrationState, - tryToClaimNextHydratableInstance: tryToClaimNextHydratableInstance, - prepareToHydrateHostInstance: prepareToHydrateHostInstance, - prepareToHydrateHostTextInstance: prepareToHydrateHostTextInstance, - popHydrationState: popHydrationState - }; -}; - -// This lets us hook into Fiber to debug what it's doing. -// See https://github.com/facebook/react/pull/8033. -// This is not part of the public API, not even for React DevTools. -// You may only inject a debugTool if you work on React Fiber itself. -var ReactFiberInstrumentation = { - debugTool: null -}; - -var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; - -var warnedAboutMissingGetChildContext = void 0; - -{ - warnedAboutMissingGetChildContext = {}; -} - -var ReactFiberLegacyContext = function (stack) { - var createCursor = stack.createCursor, - push = stack.push, - pop = stack.pop; - - // A cursor to the current merged context object on the stack. - - var contextStackCursor = createCursor(emptyObject); - // A cursor to a boolean indicating whether the context has changed. - var didPerformWorkStackCursor = createCursor(false); - // Keep track of the previous context object that was on the stack. - // We use this to get access to the parent context after we have already - // pushed the next context provider, and now need to merge their contexts. - var previousContext = emptyObject; - - function getUnmaskedContext(workInProgress) { - var hasOwnContext = isContextProvider(workInProgress); - if (hasOwnContext) { - // If the fiber is a context provider itself, when we read its context - // we have already pushed its own child context on the stack. A context - // provider should not "see" its own child context. Therefore we read the - // previous (parent) context instead for a context provider. - return previousContext; - } - return contextStackCursor.current; - } - - function cacheContext(workInProgress, unmaskedContext, maskedContext) { - var instance = workInProgress.stateNode; - instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; - instance.__reactInternalMemoizedMaskedChildContext = maskedContext; - } - - function getMaskedContext(workInProgress, unmaskedContext) { - var type = workInProgress.type; - var contextTypes = type.contextTypes; - if (!contextTypes) { - return emptyObject; - } - - // Avoid recreating masked context unless unmasked context has changed. - // Failing to do this will result in unnecessary calls to componentWillReceiveProps. - // This may trigger infinite loops if componentWillReceiveProps calls setState. - var instance = workInProgress.stateNode; - if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { - return instance.__reactInternalMemoizedMaskedChildContext; - } - - var context = {}; - for (var key in contextTypes) { - context[key] = unmaskedContext[key]; - } - - { - var name = getComponentName(workInProgress) || 'Unknown'; - checkPropTypes(contextTypes, context, 'context', name, ReactDebugCurrentFiber.getCurrentFiberStackAddendum); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. - // Context is created before the class component is instantiated so check for instance. - if (instance) { - cacheContext(workInProgress, unmaskedContext, context); - } - - return context; - } - - function hasContextChanged() { - return didPerformWorkStackCursor.current; - } - - function isContextConsumer(fiber) { - return fiber.tag === ClassComponent && fiber.type.contextTypes != null; - } - - function isContextProvider(fiber) { - return fiber.tag === ClassComponent && fiber.type.childContextTypes != null; - } - - function popContextProvider(fiber) { - if (!isContextProvider(fiber)) { - return; - } - - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - - function popTopLevelContextObject(fiber) { - pop(didPerformWorkStackCursor, fiber); - pop(contextStackCursor, fiber); - } - - function pushTopLevelContextObject(fiber, context, didChange) { - !(contextStackCursor.cursor == null) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - push(contextStackCursor, context, fiber); - push(didPerformWorkStackCursor, didChange, fiber); - } - - function processChildContext(fiber, parentContext) { - var instance = fiber.stateNode; - var childContextTypes = fiber.type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. - // It has only been added in Fiber to match the (unintentional) behavior in Stack. - if (typeof instance.getChildContext !== 'function') { - { - var componentName = getComponentName(fiber) || 'Unknown'; - - if (!warnedAboutMissingGetChildContext[componentName]) { - warnedAboutMissingGetChildContext[componentName] = true; - warning(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); - } - } - return parentContext; - } - - var childContext = void 0; - { - ReactDebugCurrentFiber.setCurrentPhase('getChildContext'); - } - startPhaseTimer(fiber, 'getChildContext'); - childContext = instance.getChildContext(); - stopPhaseTimer(); - { - ReactDebugCurrentFiber.setCurrentPhase(null); - } - for (var contextKey in childContext) { - !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(fiber) || 'Unknown', contextKey) : void 0; - } - { - var name = getComponentName(fiber) || 'Unknown'; - checkPropTypes(childContextTypes, childContext, 'child context', name, - // In practice, there is one case in which we won't get a stack. It's when - // somebody calls unstable_renderSubtreeIntoContainer() and we process - // context from the parent component instance. The stack will be missing - // because it's outside of the reconciliation, and so the pointer has not - // been set. This is rare and doesn't matter. We'll also remove that API. - ReactDebugCurrentFiber.getCurrentFiberStackAddendum); - } - - return _assign({}, parentContext, childContext); - } - - function pushContextProvider(workInProgress) { - if (!isContextProvider(workInProgress)) { - return false; - } - - var instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. - // If the instance does not exist yet, we will push null at first, - // and replace it on the stack later when invalidating the context. - var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyObject; - - // Remember the parent context so we can merge with it later. - // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. - previousContext = contextStackCursor.current; - push(contextStackCursor, memoizedMergedChildContext, workInProgress); - push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); - - return true; - } - - function invalidateContextProvider(workInProgress, didChange) { - var instance = workInProgress.stateNode; - !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - if (didChange) { - // Merge parent and own context. - // Skip this if we're not updating due to sCU. - // This avoids unnecessarily recomputing memoized values. - var mergedContext = processChildContext(workInProgress, previousContext); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. - // It is important to unwind the context in the reverse order. - pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. - push(contextStackCursor, mergedContext, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } else { - pop(didPerformWorkStackCursor, workInProgress); - push(didPerformWorkStackCursor, didChange, workInProgress); - } - } - - function findCurrentUnmaskedContext(fiber) { - // Currently this is only used with renderSubtreeIntoContainer; not sure if it - // makes sense elsewhere - !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - var node = fiber; - while (node.tag !== HostRoot) { - if (isContextProvider(node)) { - return node.stateNode.__reactInternalMemoizedMergedChildContext; - } - var parent = node['return']; - !parent ? invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.') : void 0; - node = parent; - } - return node.stateNode.context; - } - - return { - getUnmaskedContext: getUnmaskedContext, - cacheContext: cacheContext, - getMaskedContext: getMaskedContext, - hasContextChanged: hasContextChanged, - isContextConsumer: isContextConsumer, - isContextProvider: isContextProvider, - popContextProvider: popContextProvider, - popTopLevelContextObject: popTopLevelContextObject, - pushTopLevelContextObject: pushTopLevelContextObject, - processChildContext: processChildContext, - pushContextProvider: pushContextProvider, - invalidateContextProvider: invalidateContextProvider, - findCurrentUnmaskedContext: findCurrentUnmaskedContext - }; -}; - -var ReactFiberNewContext = function (stack) { - var createCursor = stack.createCursor, - push = stack.push, - pop = stack.pop; - - - var providerCursor = createCursor(null); - var valueCursor = createCursor(null); - var changedBitsCursor = createCursor(0); - - var rendererSigil = void 0; - { - // Use this to detect multiple renderers using the same context - rendererSigil = {}; - } - - function pushProvider(providerFiber) { - var context = providerFiber.type._context; - - push(changedBitsCursor, context._changedBits, providerFiber); - push(valueCursor, context._currentValue, providerFiber); - push(providerCursor, providerFiber, providerFiber); - - context._currentValue = providerFiber.pendingProps.value; - context._changedBits = providerFiber.stateNode; - - { - !(context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warning(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0; - context._currentRenderer = rendererSigil; - } - } - - function popProvider(providerFiber) { - var changedBits = changedBitsCursor.current; - var currentValue = valueCursor.current; - - pop(providerCursor, providerFiber); - pop(valueCursor, providerFiber); - pop(changedBitsCursor, providerFiber); - - var context = providerFiber.type._context; - context._currentValue = currentValue; - context._changedBits = changedBits; - } - - return { - pushProvider: pushProvider, - popProvider: popProvider - }; -}; - -var ReactFiberStack = function () { - var valueStack = []; - - var fiberStack = void 0; - - { - fiberStack = []; - } - - var index = -1; - - function createCursor(defaultValue) { - return { - current: defaultValue - }; - } - - function isEmpty() { - return index === -1; - } - - function pop(cursor, fiber) { - if (index < 0) { - { - warning(false, 'Unexpected pop.'); - } - return; - } - - { - if (fiber !== fiberStack[index]) { - warning(false, 'Unexpected Fiber popped.'); - } - } - - cursor.current = valueStack[index]; - - valueStack[index] = null; - - { - fiberStack[index] = null; - } - - index--; - } - - function push(cursor, value, fiber) { - index++; - - valueStack[index] = cursor.current; - - { - fiberStack[index] = fiber; - } - - cursor.current = value; - } - - function checkThatStackIsEmpty() { - { - if (index !== -1) { - warning(false, 'Expected an empty stack. Something was not reset properly.'); - } - } - } - - function resetStackAfterFatalErrorInDev() { - { - index = -1; - valueStack.length = 0; - fiberStack.length = 0; - } - } - - return { - createCursor: createCursor, - isEmpty: isEmpty, - pop: pop, - push: push, - checkThatStackIsEmpty: checkThatStackIsEmpty, - resetStackAfterFatalErrorInDev: resetStackAfterFatalErrorInDev - }; -}; - -var invokeGuardedCallback$2 = ReactErrorUtils.invokeGuardedCallback; -var hasCaughtError = ReactErrorUtils.hasCaughtError; -var clearCaughtError = ReactErrorUtils.clearCaughtError; - - -var didWarnAboutStateTransition = void 0; -var didWarnSetStateChildContext = void 0; -var warnAboutUpdateOnUnmounted = void 0; -var warnAboutInvalidUpdates = void 0; - -{ - didWarnAboutStateTransition = false; - didWarnSetStateChildContext = false; - var didWarnStateUpdateForUnmountedComponent = {}; - - warnAboutUpdateOnUnmounted = function (fiber) { - // We show the whole stack but dedupe on the top component's name because - // the problematic code almost always lies inside that component. - var componentName = getComponentName(fiber) || 'ReactClass'; - if (didWarnStateUpdateForUnmountedComponent[componentName]) { - return; - } - warning(false, "Can't call setState (or forceUpdate) on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in the ' + 'componentWillUnmount method.%s', getStackAddendumByWorkInProgressFiber(fiber)); - didWarnStateUpdateForUnmountedComponent[componentName] = true; - }; - - warnAboutInvalidUpdates = function (instance) { - switch (ReactDebugCurrentFiber.phase) { - case 'getChildContext': - if (didWarnSetStateChildContext) { - return; - } - warning(false, 'setState(...): Cannot call setState() inside getChildContext()'); - didWarnSetStateChildContext = true; - break; - case 'render': - if (didWarnAboutStateTransition) { - return; - } - warning(false, 'Cannot update during an existing state transition (such as within ' + "`render` or another component's constructor). Render methods should " + 'be a pure function of props and state; constructor side-effects are ' + 'an anti-pattern, but can be moved to `componentWillMount`.'); - didWarnAboutStateTransition = true; - break; - } - }; -} - -var ReactFiberScheduler = function (config) { - var stack = ReactFiberStack(); - var hostContext = ReactFiberHostContext(config, stack); - var legacyContext = ReactFiberLegacyContext(stack); - var newContext = ReactFiberNewContext(stack); - var popHostContext = hostContext.popHostContext, - popHostContainer = hostContext.popHostContainer; - var popTopLevelLegacyContextObject = legacyContext.popTopLevelContextObject, - popLegacyContextProvider = legacyContext.popContextProvider; - var popProvider = newContext.popProvider; - - var hydrationContext = ReactFiberHydrationContext(config); - - var _ReactFiberBeginWork = ReactFiberBeginWork(config, hostContext, legacyContext, newContext, hydrationContext, scheduleWork, computeExpirationForFiber), - beginWork = _ReactFiberBeginWork.beginWork; - - var _ReactFiberCompleteWo = ReactFiberCompleteWork(config, hostContext, legacyContext, newContext, hydrationContext), - completeWork = _ReactFiberCompleteWo.completeWork; - - var _ReactFiberUnwindWork = ReactFiberUnwindWork(hostContext, legacyContext, newContext, scheduleWork, isAlreadyFailedLegacyErrorBoundary), - throwException = _ReactFiberUnwindWork.throwException, - unwindWork = _ReactFiberUnwindWork.unwindWork, - unwindInterruptedWork = _ReactFiberUnwindWork.unwindInterruptedWork; - - var _ReactFiberCommitWork = ReactFiberCommitWork(config, onCommitPhaseError, scheduleWork, computeExpirationForFiber, markLegacyErrorBoundaryAsFailed, recalculateCurrentTime), - commitBeforeMutationLifeCycles = _ReactFiberCommitWork.commitBeforeMutationLifeCycles, - commitResetTextContent = _ReactFiberCommitWork.commitResetTextContent, - commitPlacement = _ReactFiberCommitWork.commitPlacement, - commitDeletion = _ReactFiberCommitWork.commitDeletion, - commitWork = _ReactFiberCommitWork.commitWork, - commitLifeCycles = _ReactFiberCommitWork.commitLifeCycles, - commitErrorLogging = _ReactFiberCommitWork.commitErrorLogging, - commitAttachRef = _ReactFiberCommitWork.commitAttachRef, - commitDetachRef = _ReactFiberCommitWork.commitDetachRef; - - var now = config.now, - scheduleDeferredCallback = config.scheduleDeferredCallback, - cancelDeferredCallback = config.cancelDeferredCallback, - prepareForCommit = config.prepareForCommit, - resetAfterCommit = config.resetAfterCommit; - - // Represents the current time in ms. - - var originalStartTimeMs = now(); - var mostRecentCurrentTime = msToExpirationTime(0); - var mostRecentCurrentTimeMs = originalStartTimeMs; - - // Used to ensure computeUniqueAsyncExpiration is monotonically increases. - var lastUniqueAsyncExpiration = 0; - - // Represents the expiration time that incoming updates should use. (If this - // is NoWork, use the default strategy: async updates in async mode, sync - // updates in sync mode.) - var expirationContext = NoWork; - - var isWorking = false; - - // The next work in progress fiber that we're currently working on. - var nextUnitOfWork = null; - var nextRoot = null; - // The time at which we're currently rendering work. - var nextRenderExpirationTime = NoWork; - - // The next fiber with an effect that we're currently committing. - var nextEffect = null; - - var isCommitting = false; - - var isRootReadyForCommit = false; - - var legacyErrorBoundariesThatAlreadyFailed = null; - - // Used for performance tracking. - var interruptedBy = null; - - var stashedWorkInProgressProperties = void 0; - var replayUnitOfWork = void 0; - var isReplayingFailedUnitOfWork = void 0; - var originalReplayError = void 0; - var rethrowOriginalError = void 0; - if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { - stashedWorkInProgressProperties = null; - isReplayingFailedUnitOfWork = false; - originalReplayError = null; - replayUnitOfWork = function (failedUnitOfWork, error, isAsync) { - // Restore the original state of the work-in-progress - assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties); - switch (failedUnitOfWork.tag) { - case HostRoot: - popHostContainer(failedUnitOfWork); - popTopLevelLegacyContextObject(failedUnitOfWork); - break; - case HostComponent: - popHostContext(failedUnitOfWork); - break; - case ClassComponent: - popLegacyContextProvider(failedUnitOfWork); - break; - case HostPortal: - popHostContainer(failedUnitOfWork); - break; - case ContextProvider: - popProvider(failedUnitOfWork); - break; - } - // Replay the begin phase. - isReplayingFailedUnitOfWork = true; - originalReplayError = error; - invokeGuardedCallback$2(null, workLoop, null, isAsync); - isReplayingFailedUnitOfWork = false; - originalReplayError = null; - if (hasCaughtError()) { - clearCaughtError(); - } else { - // If the begin phase did not fail the second time, set this pointer - // back to the original value. - nextUnitOfWork = failedUnitOfWork; - } - }; - rethrowOriginalError = function () { - throw originalReplayError; - }; - } - - function resetStack() { - if (nextUnitOfWork !== null) { - var interruptedWork = nextUnitOfWork['return']; - while (interruptedWork !== null) { - unwindInterruptedWork(interruptedWork); - interruptedWork = interruptedWork['return']; - } - } - - { - ReactStrictModeWarnings.discardPendingWarnings(); - stack.checkThatStackIsEmpty(); - } - - nextRoot = null; - nextRenderExpirationTime = NoWork; - nextUnitOfWork = null; - - isRootReadyForCommit = false; - } - - function commitAllHostEffects() { - while (nextEffect !== null) { - { - ReactDebugCurrentFiber.setCurrentFiber(nextEffect); - } - recordEffect(); - - var effectTag = nextEffect.effectTag; - - if (effectTag & ContentReset) { - commitResetTextContent(nextEffect); - } - - if (effectTag & Ref) { - var current = nextEffect.alternate; - if (current !== null) { - commitDetachRef(current); - } - } - - // The following switch statement is only concerned about placement, - // updates, and deletions. To avoid needing to add a case for every - // possible bitmap value, we remove the secondary effects from the - // effect tag and switch on that value. - var primaryEffectTag = effectTag & (Placement | Update | Deletion); - switch (primaryEffectTag) { - case Placement: - { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is inserted, before - // any life-cycles like componentDidMount gets called. - // TODO: findDOMNode doesn't rely on this any more but isMounted - // does and isMounted is deprecated anyway so we should be able - // to kill this. - nextEffect.effectTag &= ~Placement; - break; - } - case PlacementAndUpdate: - { - // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is inserted, before - // any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - - // Update - var _current = nextEffect.alternate; - commitWork(_current, nextEffect); - break; - } - case Update: - { - var _current2 = nextEffect.alternate; - commitWork(_current2, nextEffect); - break; - } - case Deletion: - { - commitDeletion(nextEffect); - break; - } - } - nextEffect = nextEffect.nextEffect; - } - - { - ReactDebugCurrentFiber.resetCurrentFiber(); - } - } - - function commitBeforeMutationLifecycles() { - while (nextEffect !== null) { - var effectTag = nextEffect.effectTag; - - if (effectTag & Snapshot) { - recordEffect(); - var current = nextEffect.alternate; - commitBeforeMutationLifeCycles(current, nextEffect); - } - - // Don't cleanup effects yet; - // This will be done by commitAllLifeCycles() - nextEffect = nextEffect.nextEffect; - } - } - - function commitAllLifeCycles(finishedRoot, currentTime, committedExpirationTime) { - { - ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); - - if (warnAboutDeprecatedLifecycles) { - ReactStrictModeWarnings.flushPendingDeprecationWarnings(); - } - } - while (nextEffect !== null) { - var effectTag = nextEffect.effectTag; - - if (effectTag & (Update | Callback)) { - recordEffect(); - var current = nextEffect.alternate; - commitLifeCycles(finishedRoot, current, nextEffect, currentTime, committedExpirationTime); - } - - if (effectTag & ErrLog) { - commitErrorLogging(nextEffect, onUncaughtError); - } - - if (effectTag & Ref) { - recordEffect(); - commitAttachRef(nextEffect); - } - - var next = nextEffect.nextEffect; - // Ensure that we clean these up so that we don't accidentally keep them. - // I'm not actually sure this matters because we can't reset firstEffect - // and lastEffect since they're on every node, not just the effectful - // ones. So we have to clean everything as we reuse nodes anyway. - nextEffect.nextEffect = null; - // Ensure that we reset the effectTag here so that we can rely on effect - // tags to reason about the current life-cycle. - nextEffect = next; - } - } - - function isAlreadyFailedLegacyErrorBoundary(instance) { - return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); - } - - function markLegacyErrorBoundaryAsFailed(instance) { - if (legacyErrorBoundariesThatAlreadyFailed === null) { - legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); - } else { - legacyErrorBoundariesThatAlreadyFailed.add(instance); - } - } - - function commitRoot(finishedWork) { - isWorking = true; - isCommitting = true; - startCommitTimer(); - - var root = finishedWork.stateNode; - !(root.current !== finishedWork) ? invariant(false, 'Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.') : void 0; - var committedExpirationTime = root.pendingCommitExpirationTime; - !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0; - root.pendingCommitExpirationTime = NoWork; - - var currentTime = recalculateCurrentTime(); - - // Reset this to null before calling lifecycles - ReactCurrentOwner.current = null; - - var firstEffect = void 0; - if (finishedWork.effectTag > PerformedWork) { - // A fiber's effect list consists only of its children, not itself. So if - // the root has an effect, we need to add it to the end of the list. The - // resulting list is the set that would belong to the root's parent, if - // it had one; that is, all the effects in the tree including the root. - if (finishedWork.lastEffect !== null) { - finishedWork.lastEffect.nextEffect = finishedWork; - firstEffect = finishedWork.firstEffect; - } else { - firstEffect = finishedWork; - } - } else { - // There is no effect on the root. - firstEffect = finishedWork.firstEffect; - } - - prepareForCommit(root.containerInfo); - - // Invoke instances of getSnapshotBeforeUpdate before mutation. - nextEffect = firstEffect; - startCommitSnapshotEffectsTimer(); - while (nextEffect !== null) { - var didError = false; - var error = void 0; - { - invokeGuardedCallback$2(null, commitBeforeMutationLifecycles, null); - if (hasCaughtError()) { - didError = true; - error = clearCaughtError(); - } - } - if (didError) { - !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; - onCommitPhaseError(nextEffect, error); - // Clean-up - if (nextEffect !== null) { - nextEffect = nextEffect.nextEffect; - } - } - } - stopCommitSnapshotEffectsTimer(); - - // Commit all the side-effects within a tree. We'll do this in two passes. - // The first pass performs all the host insertions, updates, deletions and - // ref unmounts. - nextEffect = firstEffect; - startCommitHostEffectsTimer(); - while (nextEffect !== null) { - var _didError = false; - var _error = void 0; - { - invokeGuardedCallback$2(null, commitAllHostEffects, null); - if (hasCaughtError()) { - _didError = true; - _error = clearCaughtError(); - } - } - if (_didError) { - !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; - onCommitPhaseError(nextEffect, _error); - // Clean-up - if (nextEffect !== null) { - nextEffect = nextEffect.nextEffect; - } - } - } - stopCommitHostEffectsTimer(); - - resetAfterCommit(root.containerInfo); - - // The work-in-progress tree is now the current tree. This must come after - // the first pass of the commit phase, so that the previous tree is still - // current during componentWillUnmount, but before the second pass, so that - // the finished work is current during componentDidMount/Update. - root.current = finishedWork; - - // In the second pass we'll perform all life-cycles and ref callbacks. - // Life-cycles happen as a separate pass so that all placements, updates, - // and deletions in the entire tree have already been invoked. - // This pass also triggers any renderer-specific initial effects. - nextEffect = firstEffect; - startCommitLifeCyclesTimer(); - while (nextEffect !== null) { - var _didError2 = false; - var _error2 = void 0; - { - invokeGuardedCallback$2(null, commitAllLifeCycles, null, root, currentTime, committedExpirationTime); - if (hasCaughtError()) { - _didError2 = true; - _error2 = clearCaughtError(); - } - } - if (_didError2) { - !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; - onCommitPhaseError(nextEffect, _error2); - if (nextEffect !== null) { - nextEffect = nextEffect.nextEffect; - } - } - } - - isCommitting = false; - isWorking = false; - stopCommitLifeCyclesTimer(); - stopCommitTimer(); - if (typeof onCommitRoot === 'function') { - onCommitRoot(finishedWork.stateNode); - } - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork); - } - - var remainingTime = root.current.expirationTime; - if (remainingTime === NoWork) { - // If there's no remaining work, we can clear the set of already failed - // error boundaries. - legacyErrorBoundariesThatAlreadyFailed = null; - } - return remainingTime; - } - - function resetExpirationTime(workInProgress, renderTime) { - if (renderTime !== Never && workInProgress.expirationTime === Never) { - // The children of this component are hidden. Don't bubble their - // expiration times. - return; - } - - // Check for pending updates. - var newExpirationTime = getUpdateExpirationTime(workInProgress); - - // TODO: Calls need to visit stateNode - - // Bubble up the earliest expiration time. - var child = workInProgress.child; - while (child !== null) { - if (child.expirationTime !== NoWork && (newExpirationTime === NoWork || newExpirationTime > child.expirationTime)) { - newExpirationTime = child.expirationTime; - } - child = child.sibling; - } - workInProgress.expirationTime = newExpirationTime; - } - - function completeUnitOfWork(workInProgress) { - // Attempt to complete the current unit of work, then move to the - // next sibling. If there are no more siblings, return to the - // parent fiber. - while (true) { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - var current = workInProgress.alternate; - { - ReactDebugCurrentFiber.setCurrentFiber(workInProgress); - } - - var returnFiber = workInProgress['return']; - var siblingFiber = workInProgress.sibling; - - if ((workInProgress.effectTag & Incomplete) === NoEffect) { - // This fiber completed. - var next = completeWork(current, workInProgress, nextRenderExpirationTime); - stopWorkTimer(workInProgress); - resetExpirationTime(workInProgress, nextRenderExpirationTime); - { - ReactDebugCurrentFiber.resetCurrentFiber(); - } - - if (next !== null) { - stopWorkTimer(workInProgress); - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); - } - // If completing this work spawned new work, do that next. We'll come - // back here again. - return next; - } - - if (returnFiber !== null && - // Do not append effects to parents if a sibling failed to complete - (returnFiber.effectTag & Incomplete) === NoEffect) { - // Append all the effects of the subtree and this fiber onto the effect - // list of the parent. The completion order of the children affects the - // side-effect order. - if (returnFiber.firstEffect === null) { - returnFiber.firstEffect = workInProgress.firstEffect; - } - if (workInProgress.lastEffect !== null) { - if (returnFiber.lastEffect !== null) { - returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; - } - returnFiber.lastEffect = workInProgress.lastEffect; - } - - // If this fiber had side-effects, we append it AFTER the children's - // side-effects. We can perform certain side-effects earlier if - // needed, by doing multiple passes over the effect list. We don't want - // to schedule our own side-effect on our own list because if end up - // reusing children we'll schedule this effect onto itself since we're - // at the end. - var effectTag = workInProgress.effectTag; - // Skip both NoWork and PerformedWork tags when creating the effect list. - // PerformedWork effect is read by React DevTools but shouldn't be committed. - if (effectTag > PerformedWork) { - if (returnFiber.lastEffect !== null) { - returnFiber.lastEffect.nextEffect = workInProgress; - } else { - returnFiber.firstEffect = workInProgress; - } - returnFiber.lastEffect = workInProgress; - } - } - - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); - } - - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - return siblingFiber; - } else if (returnFiber !== null) { - // If there's no more work in this returnFiber. Complete the returnFiber. - workInProgress = returnFiber; - continue; - } else { - // We've reached the root. - isRootReadyForCommit = true; - return null; - } - } else { - // This fiber did not complete because something threw. Pop values off - // the stack without entering the complete phase. If this is a boundary, - // capture values if possible. - var _next = unwindWork(workInProgress); - // Because this fiber did not complete, don't reset its expiration time. - if (workInProgress.effectTag & DidCapture) { - // Restarting an error boundary - stopFailedWorkTimer(workInProgress); - } else { - stopWorkTimer(workInProgress); - } - - { - ReactDebugCurrentFiber.resetCurrentFiber(); - } - - if (_next !== null) { - stopWorkTimer(workInProgress); - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); - } - // If completing this work spawned new work, do that next. We'll come - // back here again. - // Since we're restarting, remove anything that is not a host effect - // from the effect tag. - _next.effectTag &= HostEffectMask; - return _next; - } - - if (returnFiber !== null) { - // Mark the parent fiber as incomplete and clear its effect list. - returnFiber.firstEffect = returnFiber.lastEffect = null; - returnFiber.effectTag |= Incomplete; - } - - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); - } - - if (siblingFiber !== null) { - // If there is more work to do in this returnFiber, do that next. - return siblingFiber; - } else if (returnFiber !== null) { - // If there's no more work in this returnFiber. Complete the returnFiber. - workInProgress = returnFiber; - continue; - } else { - return null; - } - } - } - - // Without this explicit null return Flow complains of invalid return type - // TODO Remove the above while(true) loop - // eslint-disable-next-line no-unreachable - return null; - } - - function performUnitOfWork(workInProgress) { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - var current = workInProgress.alternate; - - // See if beginning this work spawns more work. - startWorkTimer(workInProgress); - { - ReactDebugCurrentFiber.setCurrentFiber(workInProgress); - } - - if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { - stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress); - } - var next = beginWork(current, workInProgress, nextRenderExpirationTime); - { - ReactDebugCurrentFiber.resetCurrentFiber(); - if (isReplayingFailedUnitOfWork) { - // Currently replaying a failed unit of work. This should be unreachable, - // because the render phase is meant to be idempotent, and it should - // have thrown again. Since it didn't, rethrow the original error, so - // React's internal stack is not misaligned. - rethrowOriginalError(); - } - } - if (true && ReactFiberInstrumentation_1.debugTool) { - ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress); - } - - if (next === null) { - // If this doesn't spawn new work, complete the current work. - next = completeUnitOfWork(workInProgress); - } - - ReactCurrentOwner.current = null; - - return next; - } - - function workLoop(isAsync) { - if (!isAsync) { - // Flush all expired work. - while (nextUnitOfWork !== null) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - } - } else { - // Flush asynchronous work until the deadline runs out of time. - while (nextUnitOfWork !== null && !shouldYield()) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - } - } - } - - function renderRoot(root, expirationTime, isAsync) { - !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0; - isWorking = true; - - // Check if we're starting from a fresh stack, or if we're resuming from - // previously yielded work. - if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) { - // Reset the stack and start working from the root. - resetStack(); - nextRoot = root; - nextRenderExpirationTime = expirationTime; - nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime); - root.pendingCommitExpirationTime = NoWork; - } - - var didFatal = false; - - startWorkLoopTimer(nextUnitOfWork); - - do { - try { - workLoop(isAsync); - } catch (thrownValue) { - if (nextUnitOfWork === null) { - // This is a fatal error. - didFatal = true; - onUncaughtError(thrownValue); - break; - } - - if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { - var failedUnitOfWork = nextUnitOfWork; - replayUnitOfWork(failedUnitOfWork, thrownValue, isAsync); - } - - var sourceFiber = nextUnitOfWork; - var returnFiber = sourceFiber['return']; - if (returnFiber === null) { - // This is the root. The root could capture its own errors. However, - // we don't know if it errors before or after we pushed the host - // context. This information is needed to avoid a stack mismatch. - // Because we're not sure, treat this as a fatal error. We could track - // which phase it fails in, but doesn't seem worth it. At least - // for now. - didFatal = true; - onUncaughtError(thrownValue); - break; - } - throwException(returnFiber, sourceFiber, thrownValue); - nextUnitOfWork = completeUnitOfWork(sourceFiber); - } - break; - } while (true); - - // We're done performing work. Time to clean up. - var didCompleteRoot = false; - isWorking = false; - - // Yield back to main thread. - if (didFatal) { - stopWorkLoopTimer(interruptedBy, didCompleteRoot); - interruptedBy = null; - // There was a fatal error. - { - stack.resetStackAfterFatalErrorInDev(); - } - return null; - } else if (nextUnitOfWork === null) { - // We reached the root. - if (isRootReadyForCommit) { - didCompleteRoot = true; - stopWorkLoopTimer(interruptedBy, didCompleteRoot); - interruptedBy = null; - // The root successfully completed. It's ready for commit. - root.pendingCommitExpirationTime = expirationTime; - var finishedWork = root.current.alternate; - return finishedWork; - } else { - // The root did not complete. - stopWorkLoopTimer(interruptedBy, didCompleteRoot); - interruptedBy = null; - invariant(false, 'Expired work should have completed. This error is likely caused by a bug in React. Please file an issue.'); - } - } else { - stopWorkLoopTimer(interruptedBy, didCompleteRoot); - interruptedBy = null; - // There's more work to do, but we ran out of time. Yield back to - // the renderer. - return null; - } - } - - function scheduleCapture(sourceFiber, boundaryFiber, value, expirationTime) { - // TODO: We only support dispatching errors. - var capturedValue = createCapturedValue(value, sourceFiber); - var update = { - expirationTime: expirationTime, - partialState: null, - callback: null, - isReplace: false, - isForced: false, - capturedValue: capturedValue, - next: null - }; - insertUpdateIntoFiber(boundaryFiber, update); - scheduleWork(boundaryFiber, expirationTime); - } - - function dispatch(sourceFiber, value, expirationTime) { - !(!isWorking || isCommitting) ? invariant(false, 'dispatch: Cannot dispatch during the render phase.') : void 0; - - // TODO: Handle arrays - - var fiber = sourceFiber['return']; - while (fiber !== null) { - switch (fiber.tag) { - case ClassComponent: - var ctor = fiber.type; - var instance = fiber.stateNode; - if (typeof ctor.getDerivedStateFromCatch === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { - scheduleCapture(sourceFiber, fiber, value, expirationTime); - return; - } - break; - // TODO: Handle async boundaries - case HostRoot: - scheduleCapture(sourceFiber, fiber, value, expirationTime); - return; - } - fiber = fiber['return']; - } - - if (sourceFiber.tag === HostRoot) { - // Error was thrown at the root. There is no parent, so the root - // itself should capture it. - scheduleCapture(sourceFiber, sourceFiber, value, expirationTime); - } - } - - function onCommitPhaseError(fiber, error) { - return dispatch(fiber, error, Sync); - } - - function computeAsyncExpiration(currentTime) { - // Given the current clock time, returns an expiration time. We use rounding - // to batch like updates together. - // Should complete within ~1000ms. 1200ms max. - var expirationMs = 5000; - var bucketSizeMs = 250; - return computeExpirationBucket(currentTime, expirationMs, bucketSizeMs); - } - - function computeInteractiveExpiration(currentTime) { - var expirationMs = void 0; - // We intentionally set a higher expiration time for interactive updates in - // dev than in production. - // If the main thread is being blocked so long that you hit the expiration, - // it's a problem that could be solved with better scheduling. - // People will be more likely to notice this and fix it with the long - // expiration time in development. - // In production we opt for better UX at the risk of masking scheduling - // problems, by expiring fast. - { - // Should complete within ~500ms. 600ms max. - expirationMs = 500; - } - var bucketSizeMs = 100; - return computeExpirationBucket(currentTime, expirationMs, bucketSizeMs); - } - - // Creates a unique async expiration time. - function computeUniqueAsyncExpiration() { - var currentTime = recalculateCurrentTime(); - var result = computeAsyncExpiration(currentTime); - if (result <= lastUniqueAsyncExpiration) { - // Since we assume the current time monotonically increases, we only hit - // this branch when computeUniqueAsyncExpiration is fired multiple times - // within a 200ms window (or whatever the async bucket size is). - result = lastUniqueAsyncExpiration + 1; - } - lastUniqueAsyncExpiration = result; - return lastUniqueAsyncExpiration; - } - - function computeExpirationForFiber(fiber) { - var expirationTime = void 0; - if (expirationContext !== NoWork) { - // An explicit expiration context was set; - expirationTime = expirationContext; - } else if (isWorking) { - if (isCommitting) { - // Updates that occur during the commit phase should have sync priority - // by default. - expirationTime = Sync; - } else { - // Updates during the render phase should expire at the same time as - // the work that is being rendered. - expirationTime = nextRenderExpirationTime; - } - } else { - // No explicit expiration context was set, and we're not currently - // performing work. Calculate a new expiration time. - if (fiber.mode & AsyncMode) { - if (isBatchingInteractiveUpdates) { - // This is an interactive update - var currentTime = recalculateCurrentTime(); - expirationTime = computeInteractiveExpiration(currentTime); - } else { - // This is an async update - var _currentTime = recalculateCurrentTime(); - expirationTime = computeAsyncExpiration(_currentTime); - } - } else { - // This is a sync update - expirationTime = Sync; - } - } - if (isBatchingInteractiveUpdates) { - // This is an interactive update. Keep track of the lowest pending - // interactive expiration time. This allows us to synchronously flush - // all interactive updates when needed. - if (lowestPendingInteractiveExpirationTime === NoWork || expirationTime > lowestPendingInteractiveExpirationTime) { - lowestPendingInteractiveExpirationTime = expirationTime; - } - } - return expirationTime; - } - - function scheduleWork(fiber, expirationTime) { - return scheduleWorkImpl(fiber, expirationTime, false); - } - - function scheduleWorkImpl(fiber, expirationTime, isErrorRecovery) { - recordScheduleUpdate(); - - { - if (!isErrorRecovery && fiber.tag === ClassComponent) { - var instance = fiber.stateNode; - warnAboutInvalidUpdates(instance); - } - } - - var node = fiber; - while (node !== null) { - // Walk the parent path to the root and update each node's - // expiration time. - if (node.expirationTime === NoWork || node.expirationTime > expirationTime) { - node.expirationTime = expirationTime; - } - if (node.alternate !== null) { - if (node.alternate.expirationTime === NoWork || node.alternate.expirationTime > expirationTime) { - node.alternate.expirationTime = expirationTime; - } - } - if (node['return'] === null) { - if (node.tag === HostRoot) { - var root = node.stateNode; - if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime < nextRenderExpirationTime) { - // This is an interruption. (Used for performance tracking.) - interruptedBy = fiber; - resetStack(); - } - if ( - // If we're in the render phase, we don't need to schedule this root - // for an update, because we'll do it before we exit... - !isWorking || isCommitting || - // ...unless this is a different root than the one we're rendering. - nextRoot !== root) { - // Add this root to the root schedule. - requestWork(root, expirationTime); - } - if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { - invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.'); - } - } else { - { - if (!isErrorRecovery && fiber.tag === ClassComponent) { - warnAboutUpdateOnUnmounted(fiber); - } - } - return; - } - } - node = node['return']; - } - } - - function recalculateCurrentTime() { - // Subtract initial time so it fits inside 32bits - mostRecentCurrentTimeMs = now() - originalStartTimeMs; - mostRecentCurrentTime = msToExpirationTime(mostRecentCurrentTimeMs); - return mostRecentCurrentTime; - } - - function deferredUpdates(fn) { - var previousExpirationContext = expirationContext; - var currentTime = recalculateCurrentTime(); - expirationContext = computeAsyncExpiration(currentTime); - try { - return fn(); - } finally { - expirationContext = previousExpirationContext; - } - } - function syncUpdates(fn, a, b, c, d) { - var previousExpirationContext = expirationContext; - expirationContext = Sync; - try { - return fn(a, b, c, d); - } finally { - expirationContext = previousExpirationContext; - } - } - - // TODO: Everything below this is written as if it has been lifted to the - // renderers. I'll do this in a follow-up. - - // Linked-list of roots - var firstScheduledRoot = null; - var lastScheduledRoot = null; - - var callbackExpirationTime = NoWork; - var callbackID = -1; - var isRendering = false; - var nextFlushedRoot = null; - var nextFlushedExpirationTime = NoWork; - var lowestPendingInteractiveExpirationTime = NoWork; - var deadlineDidExpire = false; - var hasUnhandledError = false; - var unhandledError = null; - var deadline = null; - - var isBatchingUpdates = false; - var isUnbatchingUpdates = false; - var isBatchingInteractiveUpdates = false; - - var completedBatches = null; - - // Use these to prevent an infinite loop of nested updates - var NESTED_UPDATE_LIMIT = 1000; - var nestedUpdateCount = 0; - - var timeHeuristicForUnitOfWork = 1; - - function scheduleCallbackWithExpiration(expirationTime) { - if (callbackExpirationTime !== NoWork) { - // A callback is already scheduled. Check its expiration time (timeout). - if (expirationTime > callbackExpirationTime) { - // Existing callback has sufficient timeout. Exit. - return; - } else { - // Existing callback has insufficient timeout. Cancel and schedule a - // new one. - cancelDeferredCallback(callbackID); - } - // The request callback timer is already running. Don't start a new one. - } else { - startRequestCallbackTimer(); - } - - // Compute a timeout for the given expiration time. - var currentMs = now() - originalStartTimeMs; - var expirationMs = expirationTimeToMs(expirationTime); - var timeout = expirationMs - currentMs; - - callbackExpirationTime = expirationTime; - callbackID = scheduleDeferredCallback(performAsyncWork, { timeout: timeout }); - } - - // requestWork is called by the scheduler whenever a root receives an update. - // It's up to the renderer to call renderRoot at some point in the future. - function requestWork(root, expirationTime) { - addRootToSchedule(root, expirationTime); - - if (isRendering) { - // Prevent reentrancy. Remaining work will be scheduled at the end of - // the currently rendering batch. - return; - } - - if (isBatchingUpdates) { - // Flush work at the end of the batch. - if (isUnbatchingUpdates) { - // ...unless we're inside unbatchedUpdates, in which case we should - // flush it now. - nextFlushedRoot = root; - nextFlushedExpirationTime = Sync; - performWorkOnRoot(root, Sync, false); - } - return; - } - - // TODO: Get rid of Sync and use current time? - if (expirationTime === Sync) { - performSyncWork(); - } else { - scheduleCallbackWithExpiration(expirationTime); - } - } - - function addRootToSchedule(root, expirationTime) { - // Add the root to the schedule. - // Check if this root is already part of the schedule. - if (root.nextScheduledRoot === null) { - // This root is not already scheduled. Add it. - root.remainingExpirationTime = expirationTime; - if (lastScheduledRoot === null) { - firstScheduledRoot = lastScheduledRoot = root; - root.nextScheduledRoot = root; - } else { - lastScheduledRoot.nextScheduledRoot = root; - lastScheduledRoot = root; - lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; - } - } else { - // This root is already scheduled, but its priority may have increased. - var remainingExpirationTime = root.remainingExpirationTime; - if (remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime) { - // Update the priority. - root.remainingExpirationTime = expirationTime; - } - } - } - - function findHighestPriorityRoot() { - var highestPriorityWork = NoWork; - var highestPriorityRoot = null; - if (lastScheduledRoot !== null) { - var previousScheduledRoot = lastScheduledRoot; - var root = firstScheduledRoot; - while (root !== null) { - var remainingExpirationTime = root.remainingExpirationTime; - if (remainingExpirationTime === NoWork) { - // This root no longer has work. Remove it from the scheduler. - - // TODO: This check is redudant, but Flow is confused by the branch - // below where we set lastScheduledRoot to null, even though we break - // from the loop right after. - !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0; - if (root === root.nextScheduledRoot) { - // This is the only root in the list. - root.nextScheduledRoot = null; - firstScheduledRoot = lastScheduledRoot = null; - break; - } else if (root === firstScheduledRoot) { - // This is the first root in the list. - var next = root.nextScheduledRoot; - firstScheduledRoot = next; - lastScheduledRoot.nextScheduledRoot = next; - root.nextScheduledRoot = null; - } else if (root === lastScheduledRoot) { - // This is the last root in the list. - lastScheduledRoot = previousScheduledRoot; - lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; - root.nextScheduledRoot = null; - break; - } else { - previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot; - root.nextScheduledRoot = null; - } - root = previousScheduledRoot.nextScheduledRoot; - } else { - if (highestPriorityWork === NoWork || remainingExpirationTime < highestPriorityWork) { - // Update the priority, if it's higher - highestPriorityWork = remainingExpirationTime; - highestPriorityRoot = root; - } - if (root === lastScheduledRoot) { - break; - } - previousScheduledRoot = root; - root = root.nextScheduledRoot; - } - } - } - - // If the next root is the same as the previous root, this is a nested - // update. To prevent an infinite loop, increment the nested update count. - var previousFlushedRoot = nextFlushedRoot; - if (previousFlushedRoot !== null && previousFlushedRoot === highestPriorityRoot && highestPriorityWork === Sync) { - nestedUpdateCount++; - } else { - // Reset whenever we switch roots. - nestedUpdateCount = 0; - } - nextFlushedRoot = highestPriorityRoot; - nextFlushedExpirationTime = highestPriorityWork; - } - - function performAsyncWork(dl) { - performWork(NoWork, true, dl); - } - - function performSyncWork() { - performWork(Sync, false, null); - } - - function performWork(minExpirationTime, isAsync, dl) { - deadline = dl; - - // Keep working on roots until there's no more work, or until the we reach - // the deadline. - findHighestPriorityRoot(); - - if (enableUserTimingAPI && deadline !== null) { - var didExpire = nextFlushedExpirationTime < recalculateCurrentTime(); - var timeout = expirationTimeToMs(nextFlushedExpirationTime); - stopRequestCallbackTimer(didExpire, timeout); - } - - if (isAsync) { - while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && (minExpirationTime === NoWork || minExpirationTime >= nextFlushedExpirationTime) && (!deadlineDidExpire || recalculateCurrentTime() >= nextFlushedExpirationTime)) { - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !deadlineDidExpire); - findHighestPriorityRoot(); - } - } else { - while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && (minExpirationTime === NoWork || minExpirationTime >= nextFlushedExpirationTime)) { - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); - findHighestPriorityRoot(); - } - } - - // We're done flushing work. Either we ran out of time in this callback, - // or there's no more work left with sufficient priority. - - // If we're inside a callback, set this to false since we just completed it. - if (deadline !== null) { - callbackExpirationTime = NoWork; - callbackID = -1; - } - // If there's work left over, schedule a new callback. - if (nextFlushedExpirationTime !== NoWork) { - scheduleCallbackWithExpiration(nextFlushedExpirationTime); - } - - // Clean-up. - deadline = null; - deadlineDidExpire = false; - - finishRendering(); - } - - function flushRoot(root, expirationTime) { - !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0; - // Perform work on root as if the given expiration time is the current time. - // This has the effect of synchronously flushing all work up to and - // including the given time. - nextFlushedRoot = root; - nextFlushedExpirationTime = expirationTime; - performWorkOnRoot(root, expirationTime, false); - // Flush any sync work that was scheduled by lifecycles - performSyncWork(); - finishRendering(); - } - - function finishRendering() { - nestedUpdateCount = 0; - - if (completedBatches !== null) { - var batches = completedBatches; - completedBatches = null; - for (var i = 0; i < batches.length; i++) { - var batch = batches[i]; - try { - batch._onComplete(); - } catch (error) { - if (!hasUnhandledError) { - hasUnhandledError = true; - unhandledError = error; - } - } - } - } - - if (hasUnhandledError) { - var error = unhandledError; - unhandledError = null; - hasUnhandledError = false; - throw error; - } - } - - function performWorkOnRoot(root, expirationTime, isAsync) { - !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0; - - isRendering = true; - - // Check if this is async work or sync/expired work. - if (!isAsync) { - // Flush sync work. - var finishedWork = root.finishedWork; - if (finishedWork !== null) { - // This root is already complete. We can commit it. - completeRoot(root, finishedWork, expirationTime); - } else { - root.finishedWork = null; - finishedWork = renderRoot(root, expirationTime, false); - if (finishedWork !== null) { - // We've completed the root. Commit it. - completeRoot(root, finishedWork, expirationTime); - } - } - } else { - // Flush async work. - var _finishedWork = root.finishedWork; - if (_finishedWork !== null) { - // This root is already complete. We can commit it. - completeRoot(root, _finishedWork, expirationTime); - } else { - root.finishedWork = null; - _finishedWork = renderRoot(root, expirationTime, true); - if (_finishedWork !== null) { - // We've completed the root. Check the deadline one more time - // before committing. - if (!shouldYield()) { - // Still time left. Commit the root. - completeRoot(root, _finishedWork, expirationTime); - } else { - // There's no time left. Mark this root as complete. We'll come - // back and commit it later. - root.finishedWork = _finishedWork; - } - } - } - } - - isRendering = false; - } - - function completeRoot(root, finishedWork, expirationTime) { - // Check if there's a batch that matches this expiration time. - var firstBatch = root.firstBatch; - if (firstBatch !== null && firstBatch._expirationTime <= expirationTime) { - if (completedBatches === null) { - completedBatches = [firstBatch]; - } else { - completedBatches.push(firstBatch); - } - if (firstBatch._defer) { - // This root is blocked from committing by a batch. Unschedule it until - // we receive another update. - root.finishedWork = finishedWork; - root.remainingExpirationTime = NoWork; - return; - } - } - - // Commit the root. - root.finishedWork = null; - root.remainingExpirationTime = commitRoot(finishedWork); - } - - // When working on async work, the reconciler asks the renderer if it should - // yield execution. For DOM, we implement this with requestIdleCallback. - function shouldYield() { - if (deadline === null) { - return false; - } - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { - // Disregard deadline.didTimeout. Only expired work should be flushed - // during a timeout. This path is only hit for non-expired work. - return false; - } - deadlineDidExpire = true; - return true; - } - - function onUncaughtError(error) { - !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0; - // Unschedule this root so we don't work on it again until there's - // another update. - nextFlushedRoot.remainingExpirationTime = NoWork; - if (!hasUnhandledError) { - hasUnhandledError = true; - unhandledError = error; - } - } - - // TODO: Batching should be implemented at the renderer level, not inside - // the reconciler. - function batchedUpdates(fn, a) { - var previousIsBatchingUpdates = isBatchingUpdates; - isBatchingUpdates = true; - try { - return fn(a); - } finally { - isBatchingUpdates = previousIsBatchingUpdates; - if (!isBatchingUpdates && !isRendering) { - performSyncWork(); - } - } - } - - // TODO: Batching should be implemented at the renderer level, not inside - // the reconciler. - function unbatchedUpdates(fn, a) { - if (isBatchingUpdates && !isUnbatchingUpdates) { - isUnbatchingUpdates = true; - try { - return fn(a); - } finally { - isUnbatchingUpdates = false; - } - } - return fn(a); - } - - // TODO: Batching should be implemented at the renderer level, not within - // the reconciler. - function flushSync(fn, a) { - !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0; - var previousIsBatchingUpdates = isBatchingUpdates; - isBatchingUpdates = true; - try { - return syncUpdates(fn, a); - } finally { - isBatchingUpdates = previousIsBatchingUpdates; - performSyncWork(); - } - } - - function interactiveUpdates(fn, a, b) { - if (isBatchingInteractiveUpdates) { - return fn(a, b); - } - // If there are any pending interactive updates, synchronously flush them. - // This needs to happen before we read any handlers, because the effect of - // the previous event may influence which handlers are called during - // this event. - if (!isBatchingUpdates && !isRendering && lowestPendingInteractiveExpirationTime !== NoWork) { - // Synchronously flush pending interactive updates. - performWork(lowestPendingInteractiveExpirationTime, false, null); - lowestPendingInteractiveExpirationTime = NoWork; - } - var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates; - var previousIsBatchingUpdates = isBatchingUpdates; - isBatchingInteractiveUpdates = true; - isBatchingUpdates = true; - try { - return fn(a, b); - } finally { - isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates; - isBatchingUpdates = previousIsBatchingUpdates; - if (!isBatchingUpdates && !isRendering) { - performSyncWork(); - } - } - } - - function flushInteractiveUpdates() { - if (!isRendering && lowestPendingInteractiveExpirationTime !== NoWork) { - // Synchronously flush pending interactive updates. - performWork(lowestPendingInteractiveExpirationTime, false, null); - lowestPendingInteractiveExpirationTime = NoWork; - } - } - - function flushControlled(fn) { - var previousIsBatchingUpdates = isBatchingUpdates; - isBatchingUpdates = true; - try { - syncUpdates(fn); - } finally { - isBatchingUpdates = previousIsBatchingUpdates; - if (!isBatchingUpdates && !isRendering) { - performWork(Sync, false, null); - } - } - } - - return { - recalculateCurrentTime: recalculateCurrentTime, - computeExpirationForFiber: computeExpirationForFiber, - scheduleWork: scheduleWork, - requestWork: requestWork, - flushRoot: flushRoot, - batchedUpdates: batchedUpdates, - unbatchedUpdates: unbatchedUpdates, - flushSync: flushSync, - flushControlled: flushControlled, - deferredUpdates: deferredUpdates, - syncUpdates: syncUpdates, - interactiveUpdates: interactiveUpdates, - flushInteractiveUpdates: flushInteractiveUpdates, - computeUniqueAsyncExpiration: computeUniqueAsyncExpiration, - legacyContext: legacyContext - }; -}; - -var didWarnAboutNestedUpdates = void 0; - -{ - didWarnAboutNestedUpdates = false; -} - -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. - - -var ReactFiberReconciler$1 = function (config) { - var getPublicInstance = config.getPublicInstance; - - var _ReactFiberScheduler = ReactFiberScheduler(config), - computeUniqueAsyncExpiration = _ReactFiberScheduler.computeUniqueAsyncExpiration, - recalculateCurrentTime = _ReactFiberScheduler.recalculateCurrentTime, - computeExpirationForFiber = _ReactFiberScheduler.computeExpirationForFiber, - scheduleWork = _ReactFiberScheduler.scheduleWork, - requestWork = _ReactFiberScheduler.requestWork, - flushRoot = _ReactFiberScheduler.flushRoot, - batchedUpdates = _ReactFiberScheduler.batchedUpdates, - unbatchedUpdates = _ReactFiberScheduler.unbatchedUpdates, - flushSync = _ReactFiberScheduler.flushSync, - flushControlled = _ReactFiberScheduler.flushControlled, - deferredUpdates = _ReactFiberScheduler.deferredUpdates, - syncUpdates = _ReactFiberScheduler.syncUpdates, - interactiveUpdates = _ReactFiberScheduler.interactiveUpdates, - flushInteractiveUpdates = _ReactFiberScheduler.flushInteractiveUpdates, - legacyContext = _ReactFiberScheduler.legacyContext; - - var findCurrentUnmaskedContext = legacyContext.findCurrentUnmaskedContext, - isContextProvider = legacyContext.isContextProvider, - processChildContext = legacyContext.processChildContext; - - - function getContextForSubtree(parentComponent) { - if (!parentComponent) { - return emptyObject; - } - - var fiber = get(parentComponent); - var parentContext = findCurrentUnmaskedContext(fiber); - return isContextProvider(fiber) ? processChildContext(fiber, parentContext) : parentContext; - } - - function scheduleRootUpdate(current, element, currentTime, expirationTime, callback) { - { - if (ReactDebugCurrentFiber.phase === 'render' && ReactDebugCurrentFiber.current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - warning(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(ReactDebugCurrentFiber.current) || 'Unknown'); - } - } - - callback = callback === undefined ? null : callback; - { - !(callback === null || typeof callback === 'function') ? warning(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0; - } - - var update = { - expirationTime: expirationTime, - partialState: { element: element }, - callback: callback, - isReplace: false, - isForced: false, - capturedValue: null, - next: null - }; - insertUpdateIntoFiber(current, update); - scheduleWork(current, expirationTime); - - return expirationTime; - } - - function updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback) { - // TODO: If this is a nested container, this won't be the root. - var current = container.current; - - { - if (ReactFiberInstrumentation_1.debugTool) { - if (current.alternate === null) { - ReactFiberInstrumentation_1.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); - } - } - } - - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - return scheduleRootUpdate(current, element, currentTime, expirationTime, callback); - } - - function findHostInstance(component) { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === 'function') { - invariant(false, 'Unable to find node on an unmounted component.'); - } else { - invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component)); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - } - - return { - createContainer: function (containerInfo, isAsync, hydrate) { - return createFiberRoot(containerInfo, isAsync, hydrate); - }, - updateContainer: function (element, container, parentComponent, callback) { - var current = container.current; - var currentTime = recalculateCurrentTime(); - var expirationTime = computeExpirationForFiber(current); - return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); - }, - updateContainerAtExpirationTime: function (element, container, parentComponent, expirationTime, callback) { - var currentTime = recalculateCurrentTime(); - return updateContainerAtExpirationTime(element, container, parentComponent, currentTime, expirationTime, callback); - }, - - - flushRoot: flushRoot, - - requestWork: requestWork, - - computeUniqueAsyncExpiration: computeUniqueAsyncExpiration, - - batchedUpdates: batchedUpdates, - - unbatchedUpdates: unbatchedUpdates, - - deferredUpdates: deferredUpdates, - - syncUpdates: syncUpdates, - - interactiveUpdates: interactiveUpdates, - - flushInteractiveUpdates: flushInteractiveUpdates, - - flushControlled: flushControlled, - - flushSync: flushSync, - - getPublicRootInstance: function (container) { - var containerFiber = container.current; - if (!containerFiber.child) { - return null; - } - switch (containerFiber.child.tag) { - case HostComponent: - return getPublicInstance(containerFiber.child.stateNode); - default: - return containerFiber.child.stateNode; - } - }, - - - findHostInstance: findHostInstance, - - findHostInstanceWithNoPortals: function (fiber) { - var hostFiber = findCurrentHostFiberWithNoPortals(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - }, - injectIntoDevTools: function (devToolsConfig) { - var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; - - return injectInternals(_assign({}, devToolsConfig, { - findHostInstanceByFiber: function (fiber) { - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; - }, - findFiberByHostInstance: function (instance) { - if (!findFiberByHostInstance) { - // Might not be implemented by the renderer. - return null; - } - return findFiberByHostInstance(instance); - } - })); - } - }; -}; - -var ReactFiberReconciler$2 = Object.freeze({ - default: ReactFiberReconciler$1 -}); - -var ReactFiberReconciler$3 = ( ReactFiberReconciler$2 && ReactFiberReconciler$1 ) || ReactFiberReconciler$2; - -// TODO: bundle Flow types with the package. - - - -// TODO: decide on the top-level export form. -// This is hacky but makes it work with both Rollup and Jest. -var reactReconciler = ReactFiberReconciler$3['default'] ? ReactFiberReconciler$3['default'] : ReactFiberReconciler$3; - -function createPortal$1(children, containerInfo, -// TODO: figure out the API for cross-renderer implementation. -implementation) { - var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - return { - // This tag allow us to uniquely identify this as a React Portal - $$typeof: REACT_PORTAL_TYPE, - key: key == null ? null : '' + key, - children: children, - containerInfo: containerInfo, - implementation: implementation - }; -} - -// TODO: this is special because it gets imported during build. - -var ReactVersion = '16.3.2'; - -// a requestAnimationFrame, storing the time for the start of the frame, then -// scheduling a postMessage which gets scheduled after paint. Within the -// postMessage handler do as much work as possible until time + frame rate. -// By separating the idle call into a separate event tick we ensure that -// layout, paint and other browser work is counted against the available time. -// The frame rate is dynamically adjusted. - -{ - if (ExecutionEnvironment.canUseDOM && typeof requestAnimationFrame !== 'function') { - warning(false, 'React depends on requestAnimationFrame. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); - } -} - -var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - -var now = void 0; -if (hasNativePerformanceNow) { - now = function () { - return performance.now(); - }; -} else { - now = function () { - return Date.now(); - }; -} - -// TODO: There's no way to cancel, because Fiber doesn't atm. -var rIC = void 0; -var cIC = void 0; - -if (!ExecutionEnvironment.canUseDOM) { - rIC = function (frameCallback) { - return setTimeout(function () { - frameCallback({ - timeRemaining: function () { - return Infinity; - }, - - didTimeout: false - }); - }); - }; - cIC = function (timeoutID) { - clearTimeout(timeoutID); - }; -} else if (alwaysUseRequestIdleCallbackPolyfill || typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') { - // Polyfill requestIdleCallback and cancelIdleCallback - - var scheduledRICCallback = null; - var isIdleScheduled = false; - var timeoutTime = -1; - - var isAnimationFrameScheduled = false; - - var frameDeadline = 0; - // We start out assuming that we run at 30fps but then the heuristic tracking - // will adjust this value to a faster fps if we get more frequent animation - // frames. - var previousFrameTime = 33; - var activeFrameTime = 33; - - var frameDeadlineObject = void 0; - if (hasNativePerformanceNow) { - frameDeadlineObject = { - didTimeout: false, - timeRemaining: function () { - // We assume that if we have a performance timer that the rAF callback - // gets a performance timer value. Not sure if this is always true. - var remaining = frameDeadline - performance.now(); - return remaining > 0 ? remaining : 0; - } - }; - } else { - frameDeadlineObject = { - didTimeout: false, - timeRemaining: function () { - // Fallback to Date.now() - var remaining = frameDeadline - Date.now(); - return remaining > 0 ? remaining : 0; - } - }; - } - - // We use the postMessage trick to defer idle work until after the repaint. - var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2); - var idleTick = function (event) { - if (event.source !== window || event.data !== messageKey) { - return; - } - - isIdleScheduled = false; - - var currentTime = now(); - if (frameDeadline - currentTime <= 0) { - // There's no time left in this idle period. Check if the callback has - // a timeout and whether it's been exceeded. - if (timeoutTime !== -1 && timeoutTime <= currentTime) { - // Exceeded the timeout. Invoke the callback even though there's no - // time left. - frameDeadlineObject.didTimeout = true; - } else { - // No timeout. - if (!isAnimationFrameScheduled) { - // Schedule another animation callback so we retry later. - isAnimationFrameScheduled = true; - requestAnimationFrame(animationTick); - } - // Exit without invoking the callback. - return; - } - } else { - // There's still time left in this idle period. - frameDeadlineObject.didTimeout = false; - } - - timeoutTime = -1; - var callback = scheduledRICCallback; - scheduledRICCallback = null; - if (callback !== null) { - callback(frameDeadlineObject); - } - }; - // Assumes that we have addEventListener in this environment. Might need - // something better for old IE. - window.addEventListener('message', idleTick, false); - - var animationTick = function (rafTime) { - isAnimationFrameScheduled = false; - var nextFrameTime = rafTime - frameDeadline + activeFrameTime; - if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) { - if (nextFrameTime < 8) { - // Defensive coding. We don't support higher frame rates than 120hz. - // If we get lower than that, it is probably a bug. - nextFrameTime = 8; - } - // If one frame goes long, then the next one can be short to catch up. - // If two frames are short in a row, then that's an indication that we - // actually have a higher frame rate than what we're currently optimizing. - // We adjust our heuristic dynamically accordingly. For example, if we're - // running on 120hz display or 90hz VR display. - // Take the max of the two in case one of them was an anomaly due to - // missed frame deadlines. - activeFrameTime = nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime; - } else { - previousFrameTime = nextFrameTime; - } - frameDeadline = rafTime + activeFrameTime; - if (!isIdleScheduled) { - isIdleScheduled = true; - window.postMessage(messageKey, '*'); - } - }; - - rIC = function (callback, options) { - // This assumes that we only schedule one callback at a time because that's - // how Fiber uses it. - scheduledRICCallback = callback; - if (options != null && typeof options.timeout === 'number') { - timeoutTime = now() + options.timeout; - } - if (!isAnimationFrameScheduled) { - // If rAF didn't already schedule one, we need to schedule a frame. - // TODO: If this rAF doesn't materialize because the browser throttles, we - // might want to still have setTimeout trigger rIC as a backup to ensure - // that we keep performing work. - isAnimationFrameScheduled = true; - requestAnimationFrame(animationTick); - } - return 0; - }; - - cIC = function () { - scheduledRICCallback = null; - isIdleScheduled = false; - timeoutTime = -1; - }; -} else { - rIC = window.requestIdleCallback; - cIC = window.cancelIdleCallback; -} - -var didWarnSelectedSetOnOption = false; - -function flattenChildren(children) { - var content = ''; - - // Flatten children and warn if they aren't strings or numbers; - // invalid types are ignored. - // We can silently skip them because invalid DOM nesting warning - // catches these cases in Fiber. - React.Children.forEach(children, function (child) { - if (child == null) { - return; - } - if (typeof child === 'string' || typeof child === 'number') { - content += child; - } - }); - - return content; -} - -/** - * Implements an