mirror of
https://github.com/hanzoui/mixlab-nodes.git
synced 2026-10-30 20:48:06 +00:00
41387 lines
1.5 MiB
Plaintext
41387 lines
1.5 MiB
Plaintext
/******/ (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] = {
|
|
/******/ exports: {},
|
|
/******/ id: moduleId,
|
|
/******/ loaded: false
|
|
/******/ };
|
|
/******/
|
|
/******/ // Execute the module function
|
|
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
|
|
/******/
|
|
/******/ // Flag the module as loaded
|
|
/******/ module.loaded = 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;
|
|
/******/
|
|
/******/ // __webpack_public_path__
|
|
/******/ __webpack_require__.p = "";
|
|
/******/
|
|
/******/ // Load entry module and return exports
|
|
/******/ return __webpack_require__(0);
|
|
/******/ })
|
|
/************************************************************************/
|
|
/******/ ([
|
|
/* 0 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var React = __webpack_require__(1);
|
|
var ReactDOM = __webpack_require__(158);
|
|
var url = __webpack_require__(159);
|
|
var defaults = __webpack_require__(191);
|
|
var autosaver_1 = __webpack_require__(192);
|
|
var app_1 = __webpack_require__(193);
|
|
var defaultSketchJS = __webpack_require__(207);
|
|
__webpack_require__(208);
|
|
__webpack_require__(212);
|
|
__webpack_require__(214);
|
|
function start() {
|
|
var embeddingPageURL = document.referrer;
|
|
var qs = url.parse(window.location.search, true).query;
|
|
var id = embeddingPageURL + '_' + qs['id'];
|
|
var baseSketchURL = qs['baseSketchURL'] || embeddingPageURL;
|
|
var autoplay = (qs['autoplay'] === 'on');
|
|
var initialContent = qs['sketch'] || defaultSketchJS;
|
|
var p5version = qs['p5version'] || defaults.P5_VERSION;
|
|
var previewWidth = parseInt(qs['previewWidth']);
|
|
var maxRunTime = parseInt(qs['maxRunTime']);
|
|
if (isNaN(previewWidth)) {
|
|
previewWidth = defaults.PREVIEW_WIDTH;
|
|
}
|
|
if (isNaN(maxRunTime)) {
|
|
maxRunTime = defaults.MAX_RUN_TIME;
|
|
}
|
|
initialContent = initialContent.replace(/\r\n/g, '\n').trim();
|
|
ReactDOM.render(React.createElement(app_1.default, {initialContent: initialContent, autosaver: new autosaver_1.SessionStorageAutosaver(id), baseSketchURL: baseSketchURL, p5version: p5version, previewWidth: previewWidth, maxRunTime: maxRunTime, autoplay: autoplay}), document.getElementById('app-holder'));
|
|
// 监听来自iframe的消息
|
|
window.addEventListener('message', function (event) {
|
|
var data = event.data;
|
|
// console.log("#main", data)
|
|
if (data.from === 'p5.widget' && data.status === 'save') {
|
|
var frames_1 = data.frames;
|
|
window.parent.postMessage({
|
|
frames: frames_1,
|
|
from: 'p5.widget',
|
|
status: 'save',
|
|
_from: "main"
|
|
}, '*');
|
|
}
|
|
});
|
|
}
|
|
window.addEventListener('load', start);
|
|
|
|
|
|
/***/ }),
|
|
/* 1 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
module.exports = __webpack_require__(2);
|
|
|
|
|
|
/***/ }),
|
|
/* 2 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule React
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDOM = __webpack_require__(3);
|
|
var ReactDOMServer = __webpack_require__(148);
|
|
var ReactIsomorphic = __webpack_require__(152);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var deprecated = __webpack_require__(157);
|
|
|
|
// `version` will be added here by ReactIsomorphic.
|
|
var React = {};
|
|
|
|
assign(React, ReactIsomorphic);
|
|
|
|
assign(React, {
|
|
// ReactDOM
|
|
findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode),
|
|
render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render),
|
|
unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode),
|
|
|
|
// ReactDOMServer
|
|
renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString),
|
|
renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup)
|
|
});
|
|
|
|
React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM;
|
|
React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer;
|
|
|
|
module.exports = React;
|
|
|
|
/***/ }),
|
|
/* 3 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOM
|
|
*/
|
|
|
|
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactDOMTextComponent = __webpack_require__(6);
|
|
var ReactDefaultInjection = __webpack_require__(71);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
var ReactVersion = __webpack_require__(146);
|
|
|
|
var findDOMNode = __webpack_require__(91);
|
|
var renderSubtreeIntoContainer = __webpack_require__(147);
|
|
var warning = __webpack_require__(25);
|
|
|
|
ReactDefaultInjection.inject();
|
|
|
|
var render = ReactPerf.measure('React', 'render', ReactMount.render);
|
|
|
|
var React = {
|
|
findDOMNode: findDOMNode,
|
|
render: render,
|
|
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
|
|
version: ReactVersion,
|
|
|
|
/* eslint-disable camelcase */
|
|
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
|
|
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
|
|
};
|
|
|
|
// Inject the runtime into a devtools global hook regardless of browser.
|
|
// Allows for debugging when the hook is injected on the page.
|
|
/* eslint-enable camelcase */
|
|
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
|
|
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
|
|
CurrentOwner: ReactCurrentOwner,
|
|
InstanceHandles: ReactInstanceHandles,
|
|
Mount: ReactMount,
|
|
Reconciler: ReactReconciler,
|
|
TextComponent: ReactDOMTextComponent
|
|
});
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
|
|
|
|
// First check if devtools is not installed
|
|
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
|
|
// If we're in Chrome or Firefox, provide a download link if not installed.
|
|
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
|
|
console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools');
|
|
}
|
|
}
|
|
|
|
// If we're in IE8, check to see if we are in compatibility mode and provide
|
|
// information on preventing compatibility mode
|
|
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
|
|
|
|
process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined;
|
|
|
|
var expectedFeatures = [
|
|
// shims
|
|
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim,
|
|
|
|
// shams
|
|
Object.create, Object.freeze];
|
|
|
|
for (var i = 0; i < expectedFeatures.length; i++) {
|
|
if (!expectedFeatures[i]) {
|
|
console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills');
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = React;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 4 */
|
|
/***/ (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; };
|
|
|
|
|
|
/***/ }),
|
|
/* 5 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactCurrentOwner
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Keeps track of the current owner.
|
|
*
|
|
* The current owner is the component who should own any components that are
|
|
* currently being constructed.
|
|
*/
|
|
var ReactCurrentOwner = {
|
|
|
|
/**
|
|
* @internal
|
|
* @type {ReactComponent}
|
|
*/
|
|
current: null
|
|
|
|
};
|
|
|
|
module.exports = ReactCurrentOwner;
|
|
|
|
/***/ }),
|
|
/* 6 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMTextComponent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMChildrenOperations = __webpack_require__(7);
|
|
var DOMPropertyOperations = __webpack_require__(22);
|
|
var ReactComponentBrowserEnvironment = __webpack_require__(26);
|
|
var ReactMount = __webpack_require__(28);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var escapeTextContentForBrowser = __webpack_require__(21);
|
|
var setTextContent = __webpack_require__(20);
|
|
var validateDOMNesting = __webpack_require__(70);
|
|
|
|
/**
|
|
* Text nodes violate a couple assumptions that React makes about components:
|
|
*
|
|
* - When mounting text into the DOM, adjacent text nodes are merged.
|
|
* - Text nodes cannot be assigned a React root ID.
|
|
*
|
|
* This component is used to wrap strings in elements so that they can undergo
|
|
* the same reconciliation that is applied to elements.
|
|
*
|
|
* TODO: Investigate representing React components in the DOM with text nodes.
|
|
*
|
|
* @class ReactDOMTextComponent
|
|
* @extends ReactComponent
|
|
* @internal
|
|
*/
|
|
var ReactDOMTextComponent = function (props) {
|
|
// This constructor and its argument is currently used by mocks.
|
|
};
|
|
|
|
assign(ReactDOMTextComponent.prototype, {
|
|
|
|
/**
|
|
* @param {ReactText} text
|
|
* @internal
|
|
*/
|
|
construct: function (text) {
|
|
// TODO: This is really a ReactText (ReactNode), not a ReactElement
|
|
this._currentElement = text;
|
|
this._stringText = '' + text;
|
|
|
|
// Properties
|
|
this._rootNodeID = null;
|
|
this._mountIndex = 0;
|
|
},
|
|
|
|
/**
|
|
* Creates the markup for this text node. This node is not intended to have
|
|
* any features besides containing text content.
|
|
*
|
|
* @param {string} rootID DOM ID of the root node.
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @return {string} Markup for this text node.
|
|
* @internal
|
|
*/
|
|
mountComponent: function (rootID, transaction, context) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (context[validateDOMNesting.ancestorInfoContextKey]) {
|
|
validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]);
|
|
}
|
|
}
|
|
|
|
this._rootNodeID = rootID;
|
|
if (transaction.useCreateElement) {
|
|
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
|
|
var el = ownerDocument.createElement('span');
|
|
DOMPropertyOperations.setAttributeForID(el, rootID);
|
|
// Populate node cache
|
|
ReactMount.getID(el);
|
|
setTextContent(el, this._stringText);
|
|
return el;
|
|
} else {
|
|
var escapedText = escapeTextContentForBrowser(this._stringText);
|
|
|
|
if (transaction.renderToStaticMarkup) {
|
|
// Normally we'd wrap this in a `span` for the reasons stated above, but
|
|
// since this is a situation where React won't take over (static pages),
|
|
// we can simply return the text as it is.
|
|
return escapedText;
|
|
}
|
|
|
|
return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>';
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Updates this component by updating the text content.
|
|
*
|
|
* @param {ReactText} nextText The next text content
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
*/
|
|
receiveComponent: function (nextText, transaction) {
|
|
if (nextText !== this._currentElement) {
|
|
this._currentElement = nextText;
|
|
var nextStringText = '' + nextText;
|
|
if (nextStringText !== this._stringText) {
|
|
// TODO: Save this as pending props and use performUpdateIfNecessary
|
|
// and/or updateComponent to do the actual update for consistency with
|
|
// other component types?
|
|
this._stringText = nextStringText;
|
|
var node = ReactMount.getNode(this._rootNodeID);
|
|
DOMChildrenOperations.updateTextContent(node, nextStringText);
|
|
}
|
|
}
|
|
},
|
|
|
|
unmountComponent: function () {
|
|
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
|
|
}
|
|
|
|
});
|
|
|
|
module.exports = ReactDOMTextComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 7 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule DOMChildrenOperations
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var Danger = __webpack_require__(8);
|
|
var ReactMultiChildUpdateTypes = __webpack_require__(16);
|
|
var ReactPerf = __webpack_require__(18);
|
|
|
|
var setInnerHTML = __webpack_require__(19);
|
|
var setTextContent = __webpack_require__(20);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Inserts `childNode` as a child of `parentNode` at the `index`.
|
|
*
|
|
* @param {DOMElement} parentNode Parent node in which to insert.
|
|
* @param {DOMElement} childNode Child node to insert.
|
|
* @param {number} index Index at which to insert the child.
|
|
* @internal
|
|
*/
|
|
function insertChildAt(parentNode, childNode, index) {
|
|
// By exploiting arrays returning `undefined` for an undefined index, we can
|
|
// rely exclusively on `insertBefore(node, null)` instead of also using
|
|
// `appendChild(node)`. However, using `undefined` is not allowed by all
|
|
// browsers so we must replace it with `null`.
|
|
|
|
// fix render order error in safari
|
|
// IE8 will throw error when index out of list size.
|
|
var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index);
|
|
|
|
parentNode.insertBefore(childNode, beforeChild);
|
|
}
|
|
|
|
/**
|
|
* Operations for updating with DOM children.
|
|
*/
|
|
var DOMChildrenOperations = {
|
|
|
|
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
|
|
|
|
updateTextContent: setTextContent,
|
|
|
|
/**
|
|
* Updates a component's children by processing a series of updates. The
|
|
* update configurations are each expected to have a `parentNode` property.
|
|
*
|
|
* @param {array<object>} updates List of update configurations.
|
|
* @param {array<string>} markupList List of markup strings.
|
|
* @internal
|
|
*/
|
|
processUpdates: function (updates, markupList) {
|
|
var update;
|
|
// Mapping from parent IDs to initial child orderings.
|
|
var initialChildren = null;
|
|
// List of children that will be moved or removed.
|
|
var updatedChildren = null;
|
|
|
|
for (var i = 0; i < updates.length; i++) {
|
|
update = updates[i];
|
|
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
|
|
var updatedIndex = update.fromIndex;
|
|
var updatedChild = update.parentNode.childNodes[updatedIndex];
|
|
var parentID = update.parentID;
|
|
|
|
!updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined;
|
|
|
|
initialChildren = initialChildren || {};
|
|
initialChildren[parentID] = initialChildren[parentID] || [];
|
|
initialChildren[parentID][updatedIndex] = updatedChild;
|
|
|
|
updatedChildren = updatedChildren || [];
|
|
updatedChildren.push(updatedChild);
|
|
}
|
|
}
|
|
|
|
var renderedMarkup;
|
|
// markupList is either a list of markup or just a list of elements
|
|
if (markupList.length && typeof markupList[0] === 'string') {
|
|
renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
|
|
} else {
|
|
renderedMarkup = markupList;
|
|
}
|
|
|
|
// Remove updated children first so that `toIndex` is consistent.
|
|
if (updatedChildren) {
|
|
for (var j = 0; j < updatedChildren.length; j++) {
|
|
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
|
|
}
|
|
}
|
|
|
|
for (var k = 0; k < updates.length; k++) {
|
|
update = updates[k];
|
|
switch (update.type) {
|
|
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
|
|
insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex);
|
|
break;
|
|
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
|
|
insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex);
|
|
break;
|
|
case ReactMultiChildUpdateTypes.SET_MARKUP:
|
|
setInnerHTML(update.parentNode, update.content);
|
|
break;
|
|
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
|
|
setTextContent(update.parentNode, update.content);
|
|
break;
|
|
case ReactMultiChildUpdateTypes.REMOVE_NODE:
|
|
// Already removed by the for-loop above.
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
|
|
updateTextContent: 'updateTextContent'
|
|
});
|
|
|
|
module.exports = DOMChildrenOperations;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 8 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule Danger
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var createNodesFromMarkup = __webpack_require__(10);
|
|
var emptyFunction = __webpack_require__(15);
|
|
var getMarkupWrap = __webpack_require__(14);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
|
|
var RESULT_INDEX_ATTR = 'data-danger-index';
|
|
|
|
/**
|
|
* Extracts the `nodeName` from a string of markup.
|
|
*
|
|
* NOTE: Extracting the `nodeName` does not require a regular expression match
|
|
* because we make assumptions about React-generated markup (i.e. there are no
|
|
* spaces surrounding the opening tag and there is at least one attribute).
|
|
*
|
|
* @param {string} markup String of markup.
|
|
* @return {string} Node name of the supplied markup.
|
|
* @see http://jsperf.com/extract-nodename
|
|
*/
|
|
function getNodeName(markup) {
|
|
return markup.substring(1, markup.indexOf(' '));
|
|
}
|
|
|
|
var Danger = {
|
|
|
|
/**
|
|
* Renders markup into an array of nodes. The markup is expected to render
|
|
* into a list of root nodes. Also, the length of `resultList` and
|
|
* `markupList` should be the same.
|
|
*
|
|
* @param {array<string>} markupList List of markup strings to render.
|
|
* @return {array<DOMElement>} List of rendered nodes.
|
|
* @internal
|
|
*/
|
|
dangerouslyRenderMarkup: function (markupList) {
|
|
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined;
|
|
var nodeName;
|
|
var markupByNodeName = {};
|
|
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
|
|
for (var i = 0; i < markupList.length; i++) {
|
|
!markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined;
|
|
nodeName = getNodeName(markupList[i]);
|
|
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
|
|
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
|
|
markupByNodeName[nodeName][i] = markupList[i];
|
|
}
|
|
var resultList = [];
|
|
var resultListAssignmentCount = 0;
|
|
for (nodeName in markupByNodeName) {
|
|
if (!markupByNodeName.hasOwnProperty(nodeName)) {
|
|
continue;
|
|
}
|
|
var markupListByNodeName = markupByNodeName[nodeName];
|
|
|
|
// This for-in loop skips the holes of the sparse array. The order of
|
|
// iteration should follow the order of assignment, which happens to match
|
|
// numerical index order, but we don't rely on that.
|
|
var resultIndex;
|
|
for (resultIndex in markupListByNodeName) {
|
|
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
|
|
var markup = markupListByNodeName[resultIndex];
|
|
|
|
// Push the requested markup with an additional RESULT_INDEX_ATTR
|
|
// attribute. If the markup does not start with a < character, it
|
|
// will be discarded below (with an appropriate console.error).
|
|
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP,
|
|
// This index will be parsed back out below.
|
|
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
|
|
}
|
|
}
|
|
|
|
// Render each group of markup with similar wrapping `nodeName`.
|
|
var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags.
|
|
);
|
|
|
|
for (var j = 0; j < renderNodes.length; ++j) {
|
|
var renderNode = renderNodes[j];
|
|
if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
|
|
|
|
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
|
|
renderNode.removeAttribute(RESULT_INDEX_ATTR);
|
|
|
|
!!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined;
|
|
|
|
resultList[resultIndex] = renderNode;
|
|
|
|
// This should match resultList.length and markupList.length when
|
|
// we're done.
|
|
resultListAssignmentCount += 1;
|
|
} else if (process.env.NODE_ENV !== 'production') {
|
|
console.error('Danger: Discarding unexpected node:', renderNode);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Although resultList was populated out of order, it should now be a dense
|
|
// array.
|
|
!(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined;
|
|
|
|
!(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined;
|
|
|
|
return resultList;
|
|
},
|
|
|
|
/**
|
|
* Replaces a node with a string of markup at its current position within its
|
|
* parent. The markup must render into a single root node.
|
|
*
|
|
* @param {DOMElement} oldChild Child node to replace.
|
|
* @param {string} markup Markup to render in place of the child node.
|
|
* @internal
|
|
*/
|
|
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
|
|
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
|
|
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined;
|
|
!(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined;
|
|
|
|
var newChild;
|
|
if (typeof markup === 'string') {
|
|
newChild = createNodesFromMarkup(markup, emptyFunction)[0];
|
|
} else {
|
|
newChild = markup;
|
|
}
|
|
oldChild.parentNode.replaceChild(newChild, oldChild);
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = Danger;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 9 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ExecutionEnvironment
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
|
|
|
|
/**
|
|
* Simple, lightweight module assisting with the detection and context of
|
|
* Worker. Helps avoid circular dependencies and allows code to reason about
|
|
* whether or not they are in a Worker, even if they never include the main
|
|
* `ReactWorker` dependency.
|
|
*/
|
|
var ExecutionEnvironment = {
|
|
|
|
canUseDOM: canUseDOM,
|
|
|
|
canUseWorkers: typeof Worker !== 'undefined',
|
|
|
|
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
|
|
|
|
canUseViewport: canUseDOM && !!window.screen,
|
|
|
|
isInWorker: !canUseDOM // For now, this is true - might change in the future.
|
|
|
|
};
|
|
|
|
module.exports = ExecutionEnvironment;
|
|
|
|
/***/ }),
|
|
/* 10 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule createNodesFromMarkup
|
|
* @typechecks
|
|
*/
|
|
|
|
/*eslint-disable fb-www/unsafe-html*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var createArrayFromMixed = __webpack_require__(11);
|
|
var getMarkupWrap = __webpack_require__(14);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Dummy container used to render all markup.
|
|
*/
|
|
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
|
|
|
|
/**
|
|
* Pattern used by `getNodeName`.
|
|
*/
|
|
var nodeNamePattern = /^\s*<(\w+)/;
|
|
|
|
/**
|
|
* Extracts the `nodeName` of the first element in a string of markup.
|
|
*
|
|
* @param {string} markup String of markup.
|
|
* @return {?string} Node name of the supplied markup.
|
|
*/
|
|
function getNodeName(markup) {
|
|
var nodeNameMatch = markup.match(nodeNamePattern);
|
|
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
|
|
}
|
|
|
|
/**
|
|
* Creates an array containing the nodes rendered from the supplied markup. The
|
|
* optionally supplied `handleScript` function will be invoked once for each
|
|
* <script> element that is rendered. If no `handleScript` function is supplied,
|
|
* an exception is thrown if any <script> elements are rendered.
|
|
*
|
|
* @param {string} markup A string of valid HTML markup.
|
|
* @param {?function} handleScript Invoked once for each rendered <script>.
|
|
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
|
|
*/
|
|
function createNodesFromMarkup(markup, handleScript) {
|
|
var node = dummyNode;
|
|
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined;
|
|
var nodeName = getNodeName(markup);
|
|
|
|
var wrap = nodeName && getMarkupWrap(nodeName);
|
|
if (wrap) {
|
|
node.innerHTML = wrap[1] + markup + wrap[2];
|
|
|
|
var wrapDepth = wrap[0];
|
|
while (wrapDepth--) {
|
|
node = node.lastChild;
|
|
}
|
|
} else {
|
|
node.innerHTML = markup;
|
|
}
|
|
|
|
var scripts = node.getElementsByTagName('script');
|
|
if (scripts.length) {
|
|
!handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined;
|
|
createArrayFromMixed(scripts).forEach(handleScript);
|
|
}
|
|
|
|
var nodes = createArrayFromMixed(node.childNodes);
|
|
while (node.lastChild) {
|
|
node.removeChild(node.lastChild);
|
|
}
|
|
return nodes;
|
|
}
|
|
|
|
module.exports = createNodesFromMarkup;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 11 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule createArrayFromMixed
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var toArray = __webpack_require__(12);
|
|
|
|
/**
|
|
* Perform a heuristic test to determine if an object is "array-like".
|
|
*
|
|
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
|
|
* Joshu replied: "Mu."
|
|
*
|
|
* This function determines if its argument has "array nature": it returns
|
|
* true if the argument is an actual array, an `arguments' object, or an
|
|
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
|
|
*
|
|
* It will return false for other array-like objects like Filelist.
|
|
*
|
|
* @param {*} obj
|
|
* @return {boolean}
|
|
*/
|
|
function hasArrayNature(obj) {
|
|
return(
|
|
// not null/false
|
|
!!obj && (
|
|
// arrays are objects, NodeLists are functions in Safari
|
|
typeof obj == 'object' || typeof obj == 'function') &&
|
|
// quacks like an array
|
|
'length' in obj &&
|
|
// not window
|
|
!('setInterval' in obj) &&
|
|
// no DOM node should be considered an array-like
|
|
// a 'select' element has 'length' and 'item' properties on IE8
|
|
typeof obj.nodeType != 'number' && (
|
|
// a real array
|
|
Array.isArray(obj) ||
|
|
// arguments
|
|
'callee' in obj ||
|
|
// HTMLCollection/NodeList
|
|
'item' in obj)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Ensure that the argument is an array by wrapping it in an array if it is not.
|
|
* Creates a copy of the argument if it is already an array.
|
|
*
|
|
* This is mostly useful idiomatically:
|
|
*
|
|
* var createArrayFromMixed = require('createArrayFromMixed');
|
|
*
|
|
* function takesOneOrMoreThings(things) {
|
|
* things = createArrayFromMixed(things);
|
|
* ...
|
|
* }
|
|
*
|
|
* This allows you to treat `things' as an array, but accept scalars in the API.
|
|
*
|
|
* If you need to convert an array-like object, like `arguments`, into an array
|
|
* use toArray instead.
|
|
*
|
|
* @param {*} obj
|
|
* @return {array}
|
|
*/
|
|
function createArrayFromMixed(obj) {
|
|
if (!hasArrayNature(obj)) {
|
|
return [obj];
|
|
} else if (Array.isArray(obj)) {
|
|
return obj.slice();
|
|
} else {
|
|
return toArray(obj);
|
|
}
|
|
}
|
|
|
|
module.exports = createArrayFromMixed;
|
|
|
|
/***/ }),
|
|
/* 12 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule toArray
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Convert array-like objects to arrays.
|
|
*
|
|
* This API assumes the caller knows the contents of the data type. For less
|
|
* well defined inputs use createArrayFromMixed.
|
|
*
|
|
* @param {object|function|filelist} obj
|
|
* @return {array}
|
|
*/
|
|
function toArray(obj) {
|
|
var length = obj.length;
|
|
|
|
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
|
|
// old versions of Safari).
|
|
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined;
|
|
|
|
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined;
|
|
|
|
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined;
|
|
|
|
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
|
|
// without method will throw during the slice call and skip straight to the
|
|
// fallback.
|
|
if (obj.hasOwnProperty) {
|
|
try {
|
|
return Array.prototype.slice.call(obj);
|
|
} catch (e) {
|
|
// IE < 9 does not support Array#slice on collections objects
|
|
}
|
|
}
|
|
|
|
// Fall back to copying key by key. This assumes all keys have a value,
|
|
// so will not preserve sparsely populated inputs.
|
|
var ret = Array(length);
|
|
for (var ii = 0; ii < length; ii++) {
|
|
ret[ii] = obj[ii];
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
module.exports = toArray;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 13 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule invariant
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
|
|
function invariant(condition, format, a, b, c, d, e, f) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (format === undefined) {
|
|
throw new Error('invariant requires an error message argument');
|
|
}
|
|
}
|
|
|
|
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__(4)))
|
|
|
|
/***/ }),
|
|
/* 14 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getMarkupWrap
|
|
*/
|
|
|
|
/*eslint-disable fb-www/unsafe-html */
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Dummy container used to detect which wraps are necessary.
|
|
*/
|
|
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
|
|
|
|
/**
|
|
* Some browsers cannot use `innerHTML` to render certain elements standalone,
|
|
* so we wrap them, render the wrapped nodes, then extract the desired node.
|
|
*
|
|
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
|
|
*/
|
|
|
|
var shouldWrap = {};
|
|
|
|
var selectWrap = [1, '<select multiple="true">', '</select>'];
|
|
var tableWrap = [1, '<table>', '</table>'];
|
|
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
|
|
|
|
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
|
|
|
|
var markupWrap = {
|
|
'*': [1, '?<div>', '</div>'],
|
|
|
|
'area': [1, '<map>', '</map>'],
|
|
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
|
|
'legend': [1, '<fieldset>', '</fieldset>'],
|
|
'param': [1, '<object>', '</object>'],
|
|
'tr': [2, '<table><tbody>', '</tbody></table>'],
|
|
|
|
'optgroup': selectWrap,
|
|
'option': selectWrap,
|
|
|
|
'caption': tableWrap,
|
|
'colgroup': tableWrap,
|
|
'tbody': tableWrap,
|
|
'tfoot': tableWrap,
|
|
'thead': tableWrap,
|
|
|
|
'td': trWrap,
|
|
'th': trWrap
|
|
};
|
|
|
|
// Initialize the SVG elements since we know they'll always need to be wrapped
|
|
// consistently. If they are created inside a <div> they will be initialized in
|
|
// the wrong namespace (and will not display).
|
|
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
|
|
svgElements.forEach(function (nodeName) {
|
|
markupWrap[nodeName] = svgWrap;
|
|
shouldWrap[nodeName] = true;
|
|
});
|
|
|
|
/**
|
|
* Gets the markup wrap configuration for the supplied `nodeName`.
|
|
*
|
|
* NOTE: This lazily detects which wraps are necessary for the current browser.
|
|
*
|
|
* @param {string} nodeName Lowercase `nodeName`.
|
|
* @return {?array} Markup wrap configuration, if applicable.
|
|
*/
|
|
function getMarkupWrap(nodeName) {
|
|
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined;
|
|
if (!markupWrap.hasOwnProperty(nodeName)) {
|
|
nodeName = '*';
|
|
}
|
|
if (!shouldWrap.hasOwnProperty(nodeName)) {
|
|
if (nodeName === '*') {
|
|
dummyNode.innerHTML = '<link />';
|
|
} else {
|
|
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
|
|
}
|
|
shouldWrap[nodeName] = !dummyNode.firstChild;
|
|
}
|
|
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
|
|
}
|
|
|
|
module.exports = getMarkupWrap;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 15 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule emptyFunction
|
|
*/
|
|
|
|
"use strict";
|
|
|
|
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.
|
|
*/
|
|
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;
|
|
|
|
/***/ }),
|
|
/* 16 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactMultiChildUpdateTypes
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var keyMirror = __webpack_require__(17);
|
|
|
|
/**
|
|
* When a component's children are updated, a series of update configuration
|
|
* objects are created in order to batch and serialize the required changes.
|
|
*
|
|
* Enumerates all the possible types of update configurations.
|
|
*
|
|
* @internal
|
|
*/
|
|
var ReactMultiChildUpdateTypes = keyMirror({
|
|
INSERT_MARKUP: null,
|
|
MOVE_EXISTING: null,
|
|
REMOVE_NODE: null,
|
|
SET_MARKUP: null,
|
|
TEXT_CONTENT: null
|
|
});
|
|
|
|
module.exports = ReactMultiChildUpdateTypes;
|
|
|
|
/***/ }),
|
|
/* 17 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule keyMirror
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Constructs an enumeration with keys equal to their value.
|
|
*
|
|
* For example:
|
|
*
|
|
* var COLORS = keyMirror({blue: null, red: null});
|
|
* var myColor = COLORS.blue;
|
|
* var isColorValid = !!COLORS[myColor];
|
|
*
|
|
* The last line could not be performed if the values of the generated enum were
|
|
* not equal to their keys.
|
|
*
|
|
* Input: {key1: val1, key2: val2}
|
|
* Output: {key1: key1, key2: key2}
|
|
*
|
|
* @param {object} obj
|
|
* @return {object}
|
|
*/
|
|
var keyMirror = function (obj) {
|
|
var ret = {};
|
|
var key;
|
|
!(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
|
|
for (key in obj) {
|
|
if (!obj.hasOwnProperty(key)) {
|
|
continue;
|
|
}
|
|
ret[key] = key;
|
|
}
|
|
return ret;
|
|
};
|
|
|
|
module.exports = keyMirror;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 18 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactPerf
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* ReactPerf is a general AOP system designed to measure performance. This
|
|
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
|
|
*/
|
|
var ReactPerf = {
|
|
/**
|
|
* Boolean to enable/disable measurement. Set to false by default to prevent
|
|
* accidental logging and perf loss.
|
|
*/
|
|
enableMeasure: false,
|
|
|
|
/**
|
|
* Holds onto the measure function in use. By default, don't measure
|
|
* anything, but we'll override this if we inject a measure function.
|
|
*/
|
|
storedMeasure: _noMeasure,
|
|
|
|
/**
|
|
* @param {object} object
|
|
* @param {string} objectName
|
|
* @param {object<string>} methodNames
|
|
*/
|
|
measureMethods: function (object, objectName, methodNames) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
for (var key in methodNames) {
|
|
if (!methodNames.hasOwnProperty(key)) {
|
|
continue;
|
|
}
|
|
object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]);
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Use this to wrap methods you want to measure. Zero overhead in production.
|
|
*
|
|
* @param {string} objName
|
|
* @param {string} fnName
|
|
* @param {function} func
|
|
* @return {function}
|
|
*/
|
|
measure: function (objName, fnName, func) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var measuredFunc = null;
|
|
var wrapper = function () {
|
|
if (ReactPerf.enableMeasure) {
|
|
if (!measuredFunc) {
|
|
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
|
|
}
|
|
return measuredFunc.apply(this, arguments);
|
|
}
|
|
return func.apply(this, arguments);
|
|
};
|
|
wrapper.displayName = objName + '_' + fnName;
|
|
return wrapper;
|
|
}
|
|
return func;
|
|
},
|
|
|
|
injection: {
|
|
/**
|
|
* @param {function} measure
|
|
*/
|
|
injectMeasure: function (measure) {
|
|
ReactPerf.storedMeasure = measure;
|
|
}
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Simply passes through the measured function, without measuring it.
|
|
*
|
|
* @param {string} objName
|
|
* @param {string} fnName
|
|
* @param {function} func
|
|
* @return {function}
|
|
*/
|
|
function _noMeasure(objName, fnName, func) {
|
|
return func;
|
|
}
|
|
|
|
module.exports = ReactPerf;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 19 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule setInnerHTML
|
|
*/
|
|
|
|
/* globals MSApp */
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
|
|
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
|
|
|
|
/**
|
|
* Set the innerHTML property of a node, ensuring that whitespace is preserved
|
|
* even in IE8.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @param {string} html
|
|
* @internal
|
|
*/
|
|
var setInnerHTML = function (node, html) {
|
|
node.innerHTML = html;
|
|
};
|
|
|
|
// Win8 apps: Allow all html to be inserted
|
|
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
|
|
setInnerHTML = function (node, html) {
|
|
MSApp.execUnsafeLocalFunction(function () {
|
|
node.innerHTML = html;
|
|
});
|
|
};
|
|
}
|
|
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
// IE8: When updating a just created node with innerHTML only leading
|
|
// whitespace is removed. When updating an existing node with innerHTML
|
|
// whitespace in root TextNodes is also collapsed.
|
|
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
|
|
|
|
// Feature detection; only IE8 is known to behave improperly like this.
|
|
var testElement = document.createElement('div');
|
|
testElement.innerHTML = ' ';
|
|
if (testElement.innerHTML === '') {
|
|
setInnerHTML = function (node, html) {
|
|
// Magic theory: IE8 supposedly differentiates between added and updated
|
|
// nodes when processing innerHTML, innerHTML on updated nodes suffers
|
|
// from worse whitespace behavior. Re-adding a node like this triggers
|
|
// the initial and more favorable whitespace behavior.
|
|
// TODO: What to do on a detached node?
|
|
if (node.parentNode) {
|
|
node.parentNode.replaceChild(node, node);
|
|
}
|
|
|
|
// We also implement a workaround for non-visible tags disappearing into
|
|
// thin air on IE8, this only happens if there is no visible text
|
|
// in-front of the non-visible tags. Piggyback on the whitespace fix
|
|
// and simply check if any non-visible tags appear in the source.
|
|
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
|
|
// Recover leading whitespace by temporarily prepending any character.
|
|
// \uFEFF has the potential advantage of being zero-width/invisible.
|
|
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
|
|
// in hopes that this is preserved even if "\uFEFF" is transformed to
|
|
// the actual Unicode character (by Babel, for example).
|
|
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
|
|
node.innerHTML = String.fromCharCode(0xFEFF) + html;
|
|
|
|
// deleteData leaves an empty `TextNode` which offsets the index of all
|
|
// children. Definitely want to avoid this.
|
|
var textNode = node.firstChild;
|
|
if (textNode.data.length === 1) {
|
|
node.removeChild(textNode);
|
|
} else {
|
|
textNode.deleteData(0, 1);
|
|
}
|
|
} else {
|
|
node.innerHTML = html;
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = setInnerHTML;
|
|
|
|
/***/ }),
|
|
/* 20 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule setTextContent
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var escapeTextContentForBrowser = __webpack_require__(21);
|
|
var setInnerHTML = __webpack_require__(19);
|
|
|
|
/**
|
|
* Set the textContent property of a node, ensuring that whitespace is preserved
|
|
* even in IE8. innerText is a poor substitute for textContent and, among many
|
|
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
|
|
* as it should.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @param {string} text
|
|
* @internal
|
|
*/
|
|
var setTextContent = function (node, text) {
|
|
node.textContent = text;
|
|
};
|
|
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
if (!('textContent' in document.documentElement)) {
|
|
setTextContent = function (node, text) {
|
|
setInnerHTML(node, escapeTextContentForBrowser(text));
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = setTextContent;
|
|
|
|
/***/ }),
|
|
/* 21 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule escapeTextContentForBrowser
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ESCAPE_LOOKUP = {
|
|
'&': '&',
|
|
'>': '>',
|
|
'<': '<',
|
|
'"': '"',
|
|
'\'': '''
|
|
};
|
|
|
|
var ESCAPE_REGEX = /[&><"']/g;
|
|
|
|
function escaper(match) {
|
|
return ESCAPE_LOOKUP[match];
|
|
}
|
|
|
|
/**
|
|
* Escapes text to prevent scripting attacks.
|
|
*
|
|
* @param {*} text Text value to escape.
|
|
* @return {string} An escaped string.
|
|
*/
|
|
function escapeTextContentForBrowser(text) {
|
|
return ('' + text).replace(ESCAPE_REGEX, escaper);
|
|
}
|
|
|
|
module.exports = escapeTextContentForBrowser;
|
|
|
|
/***/ }),
|
|
/* 22 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule DOMPropertyOperations
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
var ReactPerf = __webpack_require__(18);
|
|
|
|
var quoteAttributeValueForBrowser = __webpack_require__(24);
|
|
var warning = __webpack_require__(25);
|
|
|
|
// Simplified subset
|
|
var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/;
|
|
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;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined;
|
|
return false;
|
|
}
|
|
|
|
function shouldIgnoreValue(propertyInfo, value) {
|
|
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var reactProps = {
|
|
children: true,
|
|
dangerouslySetInnerHTML: true,
|
|
key: true,
|
|
ref: true
|
|
};
|
|
var warnedProperties = {};
|
|
|
|
var warnUnknownProperty = function (name) {
|
|
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
|
|
return;
|
|
}
|
|
|
|
warnedProperties[name] = true;
|
|
var lowerCasedName = name.toLowerCase();
|
|
|
|
// data-* attributes should be lowercase; suggest the lowercase version
|
|
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
|
|
|
|
// For now, only warn when we have a suggested correction. This prevents
|
|
// logging too much when using transferPropsTo.
|
|
process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Operations for dealing with DOM properties.
|
|
*/
|
|
var DOMPropertyOperations = {
|
|
|
|
/**
|
|
* Creates markup for the ID property.
|
|
*
|
|
* @param {string} id Unescaped ID.
|
|
* @return {string} Markup string.
|
|
*/
|
|
createMarkupForID: function (id) {
|
|
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
|
|
},
|
|
|
|
setAttributeForID: function (node, id) {
|
|
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
|
|
},
|
|
|
|
/**
|
|
* Creates markup for a property.
|
|
*
|
|
* @param {string} name
|
|
* @param {*} value
|
|
* @return {?string} Markup string, or null if the property was invalid.
|
|
*/
|
|
createMarkupForProperty: function (name, value) {
|
|
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
|
|
if (propertyInfo) {
|
|
if (shouldIgnoreValue(propertyInfo, value)) {
|
|
return '';
|
|
}
|
|
var attributeName = propertyInfo.attributeName;
|
|
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
|
|
return attributeName + '=""';
|
|
}
|
|
return attributeName + '=' + quoteAttributeValueForBrowser(value);
|
|
} else if (DOMProperty.isCustomAttribute(name)) {
|
|
if (value == null) {
|
|
return '';
|
|
}
|
|
return name + '=' + quoteAttributeValueForBrowser(value);
|
|
} else if (process.env.NODE_ENV !== 'production') {
|
|
warnUnknownProperty(name);
|
|
}
|
|
return null;
|
|
},
|
|
|
|
/**
|
|
* Creates markup for a custom property.
|
|
*
|
|
* @param {string} name
|
|
* @param {*} value
|
|
* @return {string} Markup string, or empty string if the property was invalid.
|
|
*/
|
|
createMarkupForCustomAttribute: function (name, value) {
|
|
if (!isAttributeNameSafe(name) || value == null) {
|
|
return '';
|
|
}
|
|
return name + '=' + quoteAttributeValueForBrowser(value);
|
|
},
|
|
|
|
/**
|
|
* Sets the value for a property on a node.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @param {string} name
|
|
* @param {*} value
|
|
*/
|
|
setValueForProperty: function (node, name, value) {
|
|
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
|
|
if (propertyInfo) {
|
|
var mutationMethod = propertyInfo.mutationMethod;
|
|
if (mutationMethod) {
|
|
mutationMethod(node, value);
|
|
} else if (shouldIgnoreValue(propertyInfo, value)) {
|
|
this.deleteValueForProperty(node, name);
|
|
} else if (propertyInfo.mustUseAttribute) {
|
|
var attributeName = propertyInfo.attributeName;
|
|
var namespace = propertyInfo.attributeNamespace;
|
|
// `setAttribute` with objects becomes only `[object]` in IE8/9,
|
|
// ('' + value) makes it output the correct toString()-value.
|
|
if (namespace) {
|
|
node.setAttributeNS(namespace, attributeName, '' + value);
|
|
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
|
|
node.setAttribute(attributeName, '');
|
|
} else {
|
|
node.setAttribute(attributeName, '' + value);
|
|
}
|
|
} else {
|
|
var propName = propertyInfo.propertyName;
|
|
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
|
|
// property type before comparing; only `value` does and is string.
|
|
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) {
|
|
// Contrary to `setAttribute`, object properties are properly
|
|
// `toString`ed by IE8/9.
|
|
node[propName] = value;
|
|
}
|
|
}
|
|
} else if (DOMProperty.isCustomAttribute(name)) {
|
|
DOMPropertyOperations.setValueForAttribute(node, name, value);
|
|
} else if (process.env.NODE_ENV !== 'production') {
|
|
warnUnknownProperty(name);
|
|
}
|
|
},
|
|
|
|
setValueForAttribute: function (node, name, value) {
|
|
if (!isAttributeNameSafe(name)) {
|
|
return;
|
|
}
|
|
if (value == null) {
|
|
node.removeAttribute(name);
|
|
} else {
|
|
node.setAttribute(name, '' + value);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Deletes the value for a property on a node.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @param {string} name
|
|
*/
|
|
deleteValueForProperty: function (node, name) {
|
|
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
|
|
if (propertyInfo) {
|
|
var mutationMethod = propertyInfo.mutationMethod;
|
|
if (mutationMethod) {
|
|
mutationMethod(node, undefined);
|
|
} else if (propertyInfo.mustUseAttribute) {
|
|
node.removeAttribute(propertyInfo.attributeName);
|
|
} else {
|
|
var propName = propertyInfo.propertyName;
|
|
var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName);
|
|
if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) {
|
|
node[propName] = defaultValue;
|
|
}
|
|
}
|
|
} else if (DOMProperty.isCustomAttribute(name)) {
|
|
node.removeAttribute(name);
|
|
} else if (process.env.NODE_ENV !== 'production') {
|
|
warnUnknownProperty(name);
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
|
|
setValueForProperty: 'setValueForProperty',
|
|
setValueForAttribute: 'setValueForAttribute',
|
|
deleteValueForProperty: 'deleteValueForProperty'
|
|
});
|
|
|
|
module.exports = DOMPropertyOperations;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 23 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule DOMProperty
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
function checkMask(value, bitmask) {
|
|
return (value & bitmask) === bitmask;
|
|
}
|
|
|
|
var DOMPropertyInjection = {
|
|
/**
|
|
* Mapping from normalized, camelcased property names to a configuration that
|
|
* specifies how the associated DOM property should be accessed or rendered.
|
|
*/
|
|
MUST_USE_ATTRIBUTE: 0x1,
|
|
MUST_USE_PROPERTY: 0x2,
|
|
HAS_SIDE_EFFECTS: 0x4,
|
|
HAS_BOOLEAN_VALUE: 0x8,
|
|
HAS_NUMERIC_VALUE: 0x10,
|
|
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
|
|
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
|
|
|
|
/**
|
|
* Inject some specialized knowledge about the DOM. This takes a config object
|
|
* with the following properties:
|
|
*
|
|
* isCustomAttribute: function that given an attribute name will return true
|
|
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
|
|
* attributes where it's impossible to enumerate all of the possible
|
|
* attribute names,
|
|
*
|
|
* Properties: object mapping DOM property name to one of the
|
|
* DOMPropertyInjection constants or null. If your attribute isn't in here,
|
|
* it won't get written to the DOM.
|
|
*
|
|
* DOMAttributeNames: object mapping React attribute name to the DOM
|
|
* attribute name. Attribute names not specified use the **lowercase**
|
|
* normalized name.
|
|
*
|
|
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
|
|
* attribute namespace URL. (Attribute names not specified use no namespace.)
|
|
*
|
|
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
|
|
* Property names not specified use the normalized name.
|
|
*
|
|
* DOMMutationMethods: Properties that require special mutation methods. If
|
|
* `value` is undefined, the mutation method should unset the property.
|
|
*
|
|
* @param {object} domPropertyConfig the config as described above.
|
|
*/
|
|
injectDOMPropertyConfig: function (domPropertyConfig) {
|
|
var Injection = DOMPropertyInjection;
|
|
var Properties = domPropertyConfig.Properties || {};
|
|
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
|
|
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
|
|
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
|
|
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
|
|
|
|
if (domPropertyConfig.isCustomAttribute) {
|
|
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
|
|
}
|
|
|
|
for (var propName in Properties) {
|
|
!!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined;
|
|
|
|
var lowerCased = propName.toLowerCase();
|
|
var propConfig = Properties[propName];
|
|
|
|
var propertyInfo = {
|
|
attributeName: lowerCased,
|
|
attributeNamespace: null,
|
|
propertyName: propName,
|
|
mutationMethod: null,
|
|
|
|
mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE),
|
|
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
|
|
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
|
|
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
|
|
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
|
|
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
|
|
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
|
|
};
|
|
|
|
!(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined;
|
|
!(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined;
|
|
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
DOMProperty.getPossibleStandardName[lowerCased] = propName;
|
|
}
|
|
|
|
if (DOMAttributeNames.hasOwnProperty(propName)) {
|
|
var attributeName = DOMAttributeNames[propName];
|
|
propertyInfo.attributeName = attributeName;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
DOMProperty.getPossibleStandardName[attributeName] = propName;
|
|
}
|
|
}
|
|
|
|
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
|
|
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
|
|
}
|
|
|
|
if (DOMPropertyNames.hasOwnProperty(propName)) {
|
|
propertyInfo.propertyName = DOMPropertyNames[propName];
|
|
}
|
|
|
|
if (DOMMutationMethods.hasOwnProperty(propName)) {
|
|
propertyInfo.mutationMethod = DOMMutationMethods[propName];
|
|
}
|
|
|
|
DOMProperty.properties[propName] = propertyInfo;
|
|
}
|
|
}
|
|
};
|
|
var defaultValueCache = {};
|
|
|
|
/**
|
|
* DOMProperty exports lookup objects that can be used like functions:
|
|
*
|
|
* > DOMProperty.isValid['id']
|
|
* true
|
|
* > DOMProperty.isValid['foobar']
|
|
* undefined
|
|
*
|
|
* Although this may be confusing, it performs better in general.
|
|
*
|
|
* @see http://jsperf.com/key-exists
|
|
* @see http://jsperf.com/key-missing
|
|
*/
|
|
var DOMProperty = {
|
|
|
|
ID_ATTRIBUTE_NAME: 'data-reactid',
|
|
|
|
/**
|
|
* Map from property "standard name" to an object with info about how to set
|
|
* the property in the DOM. Each object contains:
|
|
*
|
|
* attributeName:
|
|
* Used when rendering markup or with `*Attribute()`.
|
|
* attributeNamespace
|
|
* propertyName:
|
|
* Used on DOM node instances. (This includes properties that mutate due to
|
|
* external factors.)
|
|
* mutationMethod:
|
|
* If non-null, used instead of the property or `setAttribute()` after
|
|
* initial render.
|
|
* mustUseAttribute:
|
|
* Whether the property must be accessed and mutated using `*Attribute()`.
|
|
* (This includes anything that fails `<propName> in <element>`.)
|
|
* mustUseProperty:
|
|
* Whether the property must be accessed and mutated as an object property.
|
|
* hasSideEffects:
|
|
* Whether or not setting a value causes side effects such as triggering
|
|
* resources to be loaded or text selection changes. If true, we read from
|
|
* the DOM before updating to ensure that the value is only set if it has
|
|
* changed.
|
|
* hasBooleanValue:
|
|
* Whether the property should be removed when set to a falsey value.
|
|
* hasNumericValue:
|
|
* Whether the property must be numeric or parse as a numeric and should be
|
|
* removed when set to a falsey value.
|
|
* hasPositiveNumericValue:
|
|
* Whether the property must be positive numeric or parse as a positive
|
|
* numeric and should be removed when set to a falsey value.
|
|
* hasOverloadedBooleanValue:
|
|
* Whether the property can be used as a flag as well as with a value.
|
|
* Removed when strictly equal to false; present without a value when
|
|
* strictly equal to true; present with a value otherwise.
|
|
*/
|
|
properties: {},
|
|
|
|
/**
|
|
* Mapping from lowercase property names to the properly cased version, used
|
|
* to warn in the case of missing properties. Available only in __DEV__.
|
|
* @type {Object}
|
|
*/
|
|
getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null,
|
|
|
|
/**
|
|
* All of the isCustomAttribute() functions that have been injected.
|
|
*/
|
|
_isCustomAttributeFunctions: [],
|
|
|
|
/**
|
|
* Checks whether a property name is a custom attribute.
|
|
* @method
|
|
*/
|
|
isCustomAttribute: function (attributeName) {
|
|
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
|
|
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
|
|
if (isCustomAttributeFn(attributeName)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
},
|
|
|
|
/**
|
|
* Returns the default property value for a DOM property (i.e., not an
|
|
* attribute). Most default values are '' or false, but not all. Worse yet,
|
|
* some (in particular, `type`) vary depending on the type of element.
|
|
*
|
|
* TODO: Is it better to grab all the possible properties when creating an
|
|
* element to avoid having to create the same element twice?
|
|
*/
|
|
getDefaultValueForProperty: function (nodeName, prop) {
|
|
var nodeDefaults = defaultValueCache[nodeName];
|
|
var testElement;
|
|
if (!nodeDefaults) {
|
|
defaultValueCache[nodeName] = nodeDefaults = {};
|
|
}
|
|
if (!(prop in nodeDefaults)) {
|
|
testElement = document.createElement(nodeName);
|
|
nodeDefaults[prop] = testElement[prop];
|
|
}
|
|
return nodeDefaults[prop];
|
|
},
|
|
|
|
injection: DOMPropertyInjection
|
|
};
|
|
|
|
module.exports = DOMProperty;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 24 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule quoteAttributeValueForBrowser
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var escapeTextContentForBrowser = __webpack_require__(21);
|
|
|
|
/**
|
|
* Escapes attribute value to prevent scripting attacks.
|
|
*
|
|
* @param {*} value Value to escape.
|
|
* @return {string} An escaped string.
|
|
*/
|
|
function quoteAttributeValueForBrowser(value) {
|
|
return '"' + escapeTextContentForBrowser(value) + '"';
|
|
}
|
|
|
|
module.exports = quoteAttributeValueForBrowser;
|
|
|
|
/***/ }),
|
|
/* 25 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule warning
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var emptyFunction = __webpack_require__(15);
|
|
|
|
/**
|
|
* 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') {
|
|
warning = function (condition, format) {
|
|
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
|
args[_key - 2] = arguments[_key];
|
|
}
|
|
|
|
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) {
|
|
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) {}
|
|
}
|
|
};
|
|
}
|
|
|
|
module.exports = warning;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 26 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactComponentBrowserEnvironment
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDOMIDOperations = __webpack_require__(27);
|
|
var ReactMount = __webpack_require__(28);
|
|
|
|
/**
|
|
* Abstracts away all functionality of the reconciler that requires knowledge of
|
|
* the browser context. TODO: These callers should be refactored to avoid the
|
|
* need for this injection.
|
|
*/
|
|
var ReactComponentBrowserEnvironment = {
|
|
|
|
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
|
|
|
|
replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
|
|
|
|
/**
|
|
* If a particular environment requires that some resources be cleaned up,
|
|
* specify this in the injected Mixin. In the DOM, we would likely want to
|
|
* purge any cached node ID lookups.
|
|
*
|
|
* @private
|
|
*/
|
|
unmountIDFromEnvironment: function (rootNodeID) {
|
|
ReactMount.purgeID(rootNodeID);
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactComponentBrowserEnvironment;
|
|
|
|
/***/ }),
|
|
/* 27 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMIDOperations
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMChildrenOperations = __webpack_require__(7);
|
|
var DOMPropertyOperations = __webpack_require__(22);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactPerf = __webpack_require__(18);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Errors for properties that should not be updated with `updatePropertyByID()`.
|
|
*
|
|
* @type {object}
|
|
* @private
|
|
*/
|
|
var INVALID_PROPERTY_ERRORS = {
|
|
dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
|
|
style: '`style` must be set using `updateStylesByID()`.'
|
|
};
|
|
|
|
/**
|
|
* Operations used to process updates to DOM nodes.
|
|
*/
|
|
var ReactDOMIDOperations = {
|
|
|
|
/**
|
|
* Updates a DOM node with new property values. This should only be used to
|
|
* update DOM properties in `DOMProperty`.
|
|
*
|
|
* @param {string} id ID of the node to update.
|
|
* @param {string} name A valid property name, see `DOMProperty`.
|
|
* @param {*} value New value of the property.
|
|
* @internal
|
|
*/
|
|
updatePropertyByID: function (id, name, value) {
|
|
var node = ReactMount.getNode(id);
|
|
!!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined;
|
|
|
|
// If we're updating to null or undefined, we should remove the property
|
|
// from the DOM node instead of inadvertantly setting to a string. This
|
|
// brings us in line with the same behavior we have on initial render.
|
|
if (value != null) {
|
|
DOMPropertyOperations.setValueForProperty(node, name, value);
|
|
} else {
|
|
DOMPropertyOperations.deleteValueForProperty(node, name);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Replaces a DOM node that exists in the document with markup.
|
|
*
|
|
* @param {string} id ID of child to be replaced.
|
|
* @param {string} markup Dangerous markup to inject in place of child.
|
|
* @internal
|
|
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
|
|
*/
|
|
dangerouslyReplaceNodeWithMarkupByID: function (id, markup) {
|
|
var node = ReactMount.getNode(id);
|
|
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
|
|
},
|
|
|
|
/**
|
|
* Updates a component's children by processing a series of updates.
|
|
*
|
|
* @param {array<object>} updates List of update configurations.
|
|
* @param {array<string>} markup List of markup strings.
|
|
* @internal
|
|
*/
|
|
dangerouslyProcessChildrenUpdates: function (updates, markup) {
|
|
for (var i = 0; i < updates.length; i++) {
|
|
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
|
|
}
|
|
DOMChildrenOperations.processUpdates(updates, markup);
|
|
}
|
|
};
|
|
|
|
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
|
|
dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID',
|
|
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
|
|
});
|
|
|
|
module.exports = ReactDOMIDOperations;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 28 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactMount
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
var ReactBrowserEventEmitter = __webpack_require__(29);
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactDOMFeatureFlags = __webpack_require__(41);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactEmptyComponentRegistry = __webpack_require__(44);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
var ReactInstanceMap = __webpack_require__(47);
|
|
var ReactMarkupChecksum = __webpack_require__(48);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
var ReactUpdateQueue = __webpack_require__(53);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyObject = __webpack_require__(58);
|
|
var containsNode = __webpack_require__(59);
|
|
var instantiateReactComponent = __webpack_require__(62);
|
|
var invariant = __webpack_require__(13);
|
|
var setInnerHTML = __webpack_require__(19);
|
|
var shouldUpdateReactComponent = __webpack_require__(67);
|
|
var validateDOMNesting = __webpack_require__(70);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
|
|
var nodeCache = {};
|
|
|
|
var ELEMENT_NODE_TYPE = 1;
|
|
var DOC_NODE_TYPE = 9;
|
|
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
|
|
|
|
var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2);
|
|
|
|
/** Mapping from reactRootID to React component instance. */
|
|
var instancesByReactRootID = {};
|
|
|
|
/** Mapping from reactRootID to `container` nodes. */
|
|
var containersByReactRootID = {};
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
/** __DEV__-only mapping from reactRootID to root elements. */
|
|
var rootElementsByReactRootID = {};
|
|
}
|
|
|
|
// Used to store breadth-first search state in findComponentRoot.
|
|
var findComponentRootReusableArray = [];
|
|
|
|
/**
|
|
* Finds the index of the first character
|
|
* that's not common between the two given strings.
|
|
*
|
|
* @return {number} the index of the character where the strings diverge
|
|
*/
|
|
function firstDifferenceIndex(string1, string2) {
|
|
var minLen = Math.min(string1.length, string2.length);
|
|
for (var i = 0; i < minLen; i++) {
|
|
if (string1.charAt(i) !== string2.charAt(i)) {
|
|
return i;
|
|
}
|
|
}
|
|
return string1.length === string2.length ? -1 : minLen;
|
|
}
|
|
|
|
/**
|
|
* @param {DOMElement|DOMDocument} container DOM element that may contain
|
|
* a React component
|
|
* @return {?*} DOM element that may have the reactRoot ID, or null.
|
|
*/
|
|
function getReactRootElementInContainer(container) {
|
|
if (!container) {
|
|
return null;
|
|
}
|
|
|
|
if (container.nodeType === DOC_NODE_TYPE) {
|
|
return container.documentElement;
|
|
} else {
|
|
return container.firstChild;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param {DOMElement} container DOM element that may contain a React component.
|
|
* @return {?string} A "reactRoot" ID, if a React component is rendered.
|
|
*/
|
|
function getReactRootID(container) {
|
|
var rootElement = getReactRootElementInContainer(container);
|
|
return rootElement && ReactMount.getID(rootElement);
|
|
}
|
|
|
|
/**
|
|
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
|
|
* element can return its control whose name or ID equals ATTR_NAME. All
|
|
* DOM nodes support `getAttributeNode` but this can also get called on
|
|
* other objects so just return '' if we're given something other than a
|
|
* DOM node (such as window).
|
|
*
|
|
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
|
|
* @return {string} ID of the supplied `domNode`.
|
|
*/
|
|
function getID(node) {
|
|
var id = internalGetID(node);
|
|
if (id) {
|
|
if (nodeCache.hasOwnProperty(id)) {
|
|
var cached = nodeCache[id];
|
|
if (cached !== node) {
|
|
!!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined;
|
|
|
|
nodeCache[id] = node;
|
|
}
|
|
} else {
|
|
nodeCache[id] = node;
|
|
}
|
|
}
|
|
|
|
return id;
|
|
}
|
|
|
|
function internalGetID(node) {
|
|
// If node is something like a window, document, or text node, none of
|
|
// which support attributes or a .getAttribute method, gracefully return
|
|
// the empty string, as if the attribute were missing.
|
|
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
|
|
}
|
|
|
|
/**
|
|
* Sets the React-specific ID of the given node.
|
|
*
|
|
* @param {DOMElement} node The DOM node whose ID will be set.
|
|
* @param {string} id The value of the ID attribute.
|
|
*/
|
|
function setID(node, id) {
|
|
var oldID = internalGetID(node);
|
|
if (oldID !== id) {
|
|
delete nodeCache[oldID];
|
|
}
|
|
node.setAttribute(ATTR_NAME, id);
|
|
nodeCache[id] = node;
|
|
}
|
|
|
|
/**
|
|
* Finds the node with the supplied React-generated DOM ID.
|
|
*
|
|
* @param {string} id A React-generated DOM ID.
|
|
* @return {DOMElement} DOM node with the suppled `id`.
|
|
* @internal
|
|
*/
|
|
function getNode(id) {
|
|
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
|
|
nodeCache[id] = ReactMount.findReactNodeByID(id);
|
|
}
|
|
return nodeCache[id];
|
|
}
|
|
|
|
/**
|
|
* Finds the node with the supplied public React instance.
|
|
*
|
|
* @param {*} instance A public React instance.
|
|
* @return {?DOMElement} DOM node with the suppled `id`.
|
|
* @internal
|
|
*/
|
|
function getNodeFromInstance(instance) {
|
|
var id = ReactInstanceMap.get(instance)._rootNodeID;
|
|
if (ReactEmptyComponentRegistry.isNullComponentID(id)) {
|
|
return null;
|
|
}
|
|
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
|
|
nodeCache[id] = ReactMount.findReactNodeByID(id);
|
|
}
|
|
return nodeCache[id];
|
|
}
|
|
|
|
/**
|
|
* A node is "valid" if it is contained by a currently mounted container.
|
|
*
|
|
* This means that the node does not have to be contained by a document in
|
|
* order to be considered valid.
|
|
*
|
|
* @param {?DOMElement} node The candidate DOM node.
|
|
* @param {string} id The expected ID of the node.
|
|
* @return {boolean} Whether the node is contained by a mounted container.
|
|
*/
|
|
function isValid(node, id) {
|
|
if (node) {
|
|
!(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined;
|
|
|
|
var container = ReactMount.findReactContainerForID(id);
|
|
if (container && containsNode(container, node)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Causes the cache to forget about one React-specific ID.
|
|
*
|
|
* @param {string} id The ID to forget.
|
|
*/
|
|
function purgeID(id) {
|
|
delete nodeCache[id];
|
|
}
|
|
|
|
var deepestNodeSoFar = null;
|
|
function findDeepestCachedAncestorImpl(ancestorID) {
|
|
var ancestor = nodeCache[ancestorID];
|
|
if (ancestor && isValid(ancestor, ancestorID)) {
|
|
deepestNodeSoFar = ancestor;
|
|
} else {
|
|
// This node isn't populated in the cache, so presumably none of its
|
|
// descendants are. Break out of the loop.
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Return the deepest cached node whose ID is a prefix of `targetID`.
|
|
*/
|
|
function findDeepestCachedAncestor(targetID) {
|
|
deepestNodeSoFar = null;
|
|
ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl);
|
|
|
|
var foundNode = deepestNodeSoFar;
|
|
deepestNodeSoFar = null;
|
|
return foundNode;
|
|
}
|
|
|
|
/**
|
|
* Mounts this component and inserts it into the DOM.
|
|
*
|
|
* @param {ReactComponent} componentInstance The instance to mount.
|
|
* @param {string} rootID DOM ID of the root node.
|
|
* @param {DOMElement} container DOM element to mount into.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {boolean} shouldReuseMarkup If true, do not insert markup
|
|
*/
|
|
function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) {
|
|
if (ReactDOMFeatureFlags.useCreateElement) {
|
|
context = assign({}, context);
|
|
if (container.nodeType === DOC_NODE_TYPE) {
|
|
context[ownerDocumentContextKey] = container;
|
|
} else {
|
|
context[ownerDocumentContextKey] = container.ownerDocument;
|
|
}
|
|
}
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (context === emptyObject) {
|
|
context = {};
|
|
}
|
|
var tag = container.nodeName.toLowerCase();
|
|
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null);
|
|
}
|
|
var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context);
|
|
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
|
|
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction);
|
|
}
|
|
|
|
/**
|
|
* Batched mount.
|
|
*
|
|
* @param {ReactComponent} componentInstance The instance to mount.
|
|
* @param {string} rootID DOM ID of the root node.
|
|
* @param {DOMElement} container DOM element to mount into.
|
|
* @param {boolean} shouldReuseMarkup If true, do not insert markup
|
|
*/
|
|
function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) {
|
|
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
|
|
/* forceHTML */shouldReuseMarkup);
|
|
transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context);
|
|
ReactUpdates.ReactReconcileTransaction.release(transaction);
|
|
}
|
|
|
|
/**
|
|
* Unmounts a component and removes it from the DOM.
|
|
*
|
|
* @param {ReactComponent} instance React component instance.
|
|
* @param {DOMElement} container DOM element to unmount from.
|
|
* @final
|
|
* @internal
|
|
* @see {ReactMount.unmountComponentAtNode}
|
|
*/
|
|
function unmountComponentFromNode(instance, container) {
|
|
ReactReconciler.unmountComponent(instance);
|
|
|
|
if (container.nodeType === DOC_NODE_TYPE) {
|
|
container = container.documentElement;
|
|
}
|
|
|
|
// http://jsperf.com/emptying-a-node
|
|
while (container.lastChild) {
|
|
container.removeChild(container.lastChild);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* True if the supplied DOM node has a direct React-rendered child that is
|
|
* not a React root element. Useful for warning in `render`,
|
|
* `unmountComponentAtNode`, etc.
|
|
*
|
|
* @param {?DOMElement} node The candidate DOM node.
|
|
* @return {boolean} True if the DOM element contains a direct child that was
|
|
* rendered by React but is not a root element.
|
|
* @internal
|
|
*/
|
|
function hasNonRootReactChild(node) {
|
|
var reactRootID = getReactRootID(node);
|
|
return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false;
|
|
}
|
|
|
|
/**
|
|
* Returns the first (deepest) ancestor of a node which is rendered by this copy
|
|
* of React.
|
|
*/
|
|
function findFirstReactDOMImpl(node) {
|
|
// This node might be from another React instance, so we make sure not to
|
|
// examine the node cache here
|
|
for (; node && node.parentNode !== node; node = node.parentNode) {
|
|
if (node.nodeType !== 1) {
|
|
// Not a DOMElement, therefore not a React component
|
|
continue;
|
|
}
|
|
var nodeID = internalGetID(node);
|
|
if (!nodeID) {
|
|
continue;
|
|
}
|
|
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
|
|
|
|
// If containersByReactRootID contains the container we find by crawling up
|
|
// the tree, we know that this instance of React rendered the node.
|
|
// nb. isValid's strategy (with containsNode) does not work because render
|
|
// trees may be nested and we don't want a false positive in that case.
|
|
var current = node;
|
|
var lastID;
|
|
do {
|
|
lastID = internalGetID(current);
|
|
current = current.parentNode;
|
|
if (current == null) {
|
|
// The passed-in node has been detached from the container it was
|
|
// originally rendered into.
|
|
return null;
|
|
}
|
|
} while (lastID !== reactRootID);
|
|
|
|
if (current === containersByReactRootID[reactRootID]) {
|
|
return node;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Temporary (?) hack so that we can store all top-level pending updates on
|
|
* composites instead of having to worry about different types of components
|
|
* here.
|
|
*/
|
|
var TopLevelWrapper = function () {};
|
|
TopLevelWrapper.prototype.isReactComponent = {};
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
TopLevelWrapper.displayName = 'TopLevelWrapper';
|
|
}
|
|
TopLevelWrapper.prototype.render = function () {
|
|
// this.props is actually a ReactElement
|
|
return this.props;
|
|
};
|
|
|
|
/**
|
|
* Mounting is the process of initializing a React component by creating its
|
|
* representative DOM elements and inserting them into a supplied `container`.
|
|
* Any prior content inside `container` is destroyed in the process.
|
|
*
|
|
* ReactMount.render(
|
|
* component,
|
|
* document.getElementById('container')
|
|
* );
|
|
*
|
|
* <div id="container"> <-- Supplied `container`.
|
|
* <div data-reactid=".3"> <-- Rendered reactRoot of React
|
|
* // ... component.
|
|
* </div>
|
|
* </div>
|
|
*
|
|
* Inside of `container`, the first element rendered is the "reactRoot".
|
|
*/
|
|
var ReactMount = {
|
|
|
|
TopLevelWrapper: TopLevelWrapper,
|
|
|
|
/** Exposed for debugging purposes **/
|
|
_instancesByReactRootID: instancesByReactRootID,
|
|
|
|
/**
|
|
* This is a hook provided to support rendering React components while
|
|
* ensuring that the apparent scroll position of its `container` does not
|
|
* change.
|
|
*
|
|
* @param {DOMElement} container The `container` being rendered into.
|
|
* @param {function} renderCallback This must be called once to do the render.
|
|
*/
|
|
scrollMonitor: function (container, renderCallback) {
|
|
renderCallback();
|
|
},
|
|
|
|
/**
|
|
* Take a component that's already mounted into the DOM and replace its props
|
|
* @param {ReactComponent} prevComponent component instance already in the DOM
|
|
* @param {ReactElement} nextElement component instance to render
|
|
* @param {DOMElement} container container to render into
|
|
* @param {?function} callback function triggered on completion
|
|
*/
|
|
_updateRootComponent: function (prevComponent, nextElement, container, callback) {
|
|
ReactMount.scrollMonitor(container, function () {
|
|
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
|
|
if (callback) {
|
|
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
|
|
}
|
|
});
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// Record the root element in case it later gets transplanted.
|
|
rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container);
|
|
}
|
|
|
|
return prevComponent;
|
|
},
|
|
|
|
/**
|
|
* Register a component into the instance map and starts scroll value
|
|
* monitoring
|
|
* @param {ReactComponent} nextComponent component instance to render
|
|
* @param {DOMElement} container container to render into
|
|
* @return {string} reactRoot ID prefix
|
|
*/
|
|
_registerComponent: function (nextComponent, container) {
|
|
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined;
|
|
|
|
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
|
|
|
|
var reactRootID = ReactMount.registerContainer(container);
|
|
instancesByReactRootID[reactRootID] = nextComponent;
|
|
return reactRootID;
|
|
},
|
|
|
|
/**
|
|
* Render a new component into the DOM.
|
|
* @param {ReactElement} nextElement element to render
|
|
* @param {DOMElement} container container to render into
|
|
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
|
|
* @return {ReactComponent} nextComponent
|
|
*/
|
|
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
|
|
// Various parts of our code (such as ReactCompositeComponent's
|
|
// _renderValidatedComponent) assume that calls to render aren't nested;
|
|
// verify that that's the case.
|
|
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): 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. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
|
|
|
|
var componentInstance = instantiateReactComponent(nextElement, null);
|
|
var reactRootID = ReactMount._registerComponent(componentInstance, container);
|
|
|
|
// The initial render is synchronous but any updates that happen during
|
|
// rendering, in componentWillMount or componentDidMount, will be batched
|
|
// according to the current batching strategy.
|
|
|
|
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// Record the root element in case it later gets transplanted.
|
|
rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container);
|
|
}
|
|
|
|
return componentInstance;
|
|
},
|
|
|
|
/**
|
|
* Renders a React component into the DOM in the supplied `container`.
|
|
*
|
|
* If the React component was previously rendered into `container`, this will
|
|
* perform an update on it and only mutate the DOM as necessary to reflect the
|
|
* latest React component.
|
|
*
|
|
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
|
|
* @param {ReactElement} nextElement Component element to render.
|
|
* @param {DOMElement} container DOM element to render into.
|
|
* @param {?function} callback function triggered on completion
|
|
* @return {ReactComponent} Component instance rendered in `container`.
|
|
*/
|
|
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
|
|
!(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined;
|
|
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
|
|
},
|
|
|
|
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
|
|
!ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' :
|
|
// Check if it quacks like an element
|
|
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined;
|
|
|
|
process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined;
|
|
|
|
var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
|
|
|
|
var prevComponent = instancesByReactRootID[getReactRootID(container)];
|
|
|
|
if (prevComponent) {
|
|
var prevWrappedElement = prevComponent._currentElement;
|
|
var prevElement = prevWrappedElement.props;
|
|
if (shouldUpdateReactComponent(prevElement, nextElement)) {
|
|
var publicInst = prevComponent._renderedComponent.getPublicInstance();
|
|
var updatedCallback = callback && function () {
|
|
callback.call(publicInst);
|
|
};
|
|
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback);
|
|
return publicInst;
|
|
} else {
|
|
ReactMount.unmountComponentAtNode(container);
|
|
}
|
|
}
|
|
|
|
var reactRootElement = getReactRootElementInContainer(container);
|
|
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
|
|
var containerHasNonRootReactChild = hasNonRootReactChild(container);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined;
|
|
|
|
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
|
|
var rootElementSibling = reactRootElement;
|
|
while (rootElementSibling) {
|
|
if (internalGetID(rootElementSibling)) {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined;
|
|
break;
|
|
}
|
|
rootElementSibling = rootElementSibling.nextSibling;
|
|
}
|
|
}
|
|
}
|
|
|
|
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
|
|
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance();
|
|
if (callback) {
|
|
callback.call(component);
|
|
}
|
|
return component;
|
|
},
|
|
|
|
/**
|
|
* Renders a React component into the DOM in the supplied `container`.
|
|
*
|
|
* If the React component was previously rendered into `container`, this will
|
|
* perform an update on it and only mutate the DOM as necessary to reflect the
|
|
* latest React component.
|
|
*
|
|
* @param {ReactElement} nextElement Component element to render.
|
|
* @param {DOMElement} container DOM element to render into.
|
|
* @param {?function} callback function triggered on completion
|
|
* @return {ReactComponent} Component instance rendered in `container`.
|
|
*/
|
|
render: function (nextElement, container, callback) {
|
|
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
|
|
},
|
|
|
|
/**
|
|
* Registers a container node into which React components will be rendered.
|
|
* This also creates the "reactRoot" ID that will be assigned to the element
|
|
* rendered within.
|
|
*
|
|
* @param {DOMElement} container DOM element to register as a container.
|
|
* @return {string} The "reactRoot" ID of elements rendered within.
|
|
*/
|
|
registerContainer: function (container) {
|
|
var reactRootID = getReactRootID(container);
|
|
if (reactRootID) {
|
|
// If one exists, make sure it is a valid "reactRoot" ID.
|
|
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
|
|
}
|
|
if (!reactRootID) {
|
|
// No valid "reactRoot" ID found, create one.
|
|
reactRootID = ReactInstanceHandles.createReactRootID();
|
|
}
|
|
containersByReactRootID[reactRootID] = container;
|
|
return reactRootID;
|
|
},
|
|
|
|
/**
|
|
* Unmounts and destroys the React component rendered in the `container`.
|
|
*
|
|
* @param {DOMElement} container DOM element containing a React component.
|
|
* @return {boolean} True if a component was found in and unmounted from
|
|
* `container`
|
|
*/
|
|
unmountComponentAtNode: function (container) {
|
|
// Various parts of our code (such as ReactCompositeComponent's
|
|
// _renderValidatedComponent) assume that calls to render aren't nested;
|
|
// verify that that's the case. (Strictly speaking, unmounting won't cause a
|
|
// render but we still don't expect to be in a render call here.)
|
|
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): 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. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
|
|
|
|
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined;
|
|
|
|
var reactRootID = getReactRootID(container);
|
|
var component = instancesByReactRootID[reactRootID];
|
|
if (!component) {
|
|
// Check if the node being unmounted was rendered by React, but isn't a
|
|
// root node.
|
|
var containerHasNonRootReactChild = hasNonRootReactChild(container);
|
|
|
|
// Check if the container itself is a React root node.
|
|
var containerID = internalGetID(container);
|
|
var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container);
|
|
delete instancesByReactRootID[reactRootID];
|
|
delete containersByReactRootID[reactRootID];
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
delete rootElementsByReactRootID[reactRootID];
|
|
}
|
|
return true;
|
|
},
|
|
|
|
/**
|
|
* Finds the container DOM element that contains React component to which the
|
|
* supplied DOM `id` belongs.
|
|
*
|
|
* @param {string} id The ID of an element rendered by a React component.
|
|
* @return {?DOMElement} DOM element that contains the `id`.
|
|
*/
|
|
findReactContainerForID: function (id) {
|
|
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
|
|
var container = containersByReactRootID[reactRootID];
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var rootElement = rootElementsByReactRootID[reactRootID];
|
|
if (rootElement && rootElement.parentNode !== container) {
|
|
process.env.NODE_ENV !== 'production' ? warning(
|
|
// Call internalGetID here because getID calls isValid which calls
|
|
// findReactContainerForID (this function).
|
|
internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined;
|
|
var containerChild = container.firstChild;
|
|
if (containerChild && reactRootID === internalGetID(containerChild)) {
|
|
// If the container has a new child with the same ID as the old
|
|
// root element, then rootElementsByReactRootID[reactRootID] is
|
|
// just stale and needs to be updated. The case that deserves a
|
|
// warning is when the container is empty.
|
|
rootElementsByReactRootID[reactRootID] = containerChild;
|
|
} else {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
return container;
|
|
},
|
|
|
|
/**
|
|
* Finds an element rendered by React with the supplied ID.
|
|
*
|
|
* @param {string} id ID of a DOM node in the React component.
|
|
* @return {DOMElement} Root DOM node of the React component.
|
|
*/
|
|
findReactNodeByID: function (id) {
|
|
var reactRoot = ReactMount.findReactContainerForID(id);
|
|
return ReactMount.findComponentRoot(reactRoot, id);
|
|
},
|
|
|
|
/**
|
|
* Traverses up the ancestors of the supplied node to find a node that is a
|
|
* DOM representation of a React component rendered by this copy of React.
|
|
*
|
|
* @param {*} node
|
|
* @return {?DOMEventTarget}
|
|
* @internal
|
|
*/
|
|
getFirstReactDOM: function (node) {
|
|
return findFirstReactDOMImpl(node);
|
|
},
|
|
|
|
/**
|
|
* Finds a node with the supplied `targetID` inside of the supplied
|
|
* `ancestorNode`. Exploits the ID naming scheme to perform the search
|
|
* quickly.
|
|
*
|
|
* @param {DOMEventTarget} ancestorNode Search from this root.
|
|
* @pararm {string} targetID ID of the DOM representation of the component.
|
|
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
|
|
* @internal
|
|
*/
|
|
findComponentRoot: function (ancestorNode, targetID) {
|
|
var firstChildren = findComponentRootReusableArray;
|
|
var childIndex = 0;
|
|
|
|
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// This will throw on the next line; give an early warning
|
|
process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined;
|
|
}
|
|
|
|
firstChildren[0] = deepestAncestor.firstChild;
|
|
firstChildren.length = 1;
|
|
|
|
while (childIndex < firstChildren.length) {
|
|
var child = firstChildren[childIndex++];
|
|
var targetChild;
|
|
|
|
while (child) {
|
|
var childID = ReactMount.getID(child);
|
|
if (childID) {
|
|
// Even if we find the node we're looking for, we finish looping
|
|
// through its siblings to ensure they're cached so that we don't have
|
|
// to revisit this node again. Otherwise, we make n^2 calls to getID
|
|
// when visiting the many children of a single node in order.
|
|
|
|
if (targetID === childID) {
|
|
targetChild = child;
|
|
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
|
|
// If we find a child whose ID is an ancestor of the given ID,
|
|
// then we can be sure that we only want to search the subtree
|
|
// rooted at this child, so we can throw out the rest of the
|
|
// search state.
|
|
firstChildren.length = childIndex = 0;
|
|
firstChildren.push(child.firstChild);
|
|
}
|
|
} else {
|
|
// If this child had no ID, then there's a chance that it was
|
|
// injected automatically by the browser, as when a `<table>`
|
|
// element sprouts an extra `<tbody>` child as a side effect of
|
|
// `.innerHTML` parsing. Optimistically continue down this
|
|
// branch, but not before examining the other siblings.
|
|
firstChildren.push(child.firstChild);
|
|
}
|
|
|
|
child = child.nextSibling;
|
|
}
|
|
|
|
if (targetChild) {
|
|
// Emptying firstChildren/findComponentRootReusableArray is
|
|
// not necessary for correctness, but it helps the GC reclaim
|
|
// any nodes that were left at the end of the search.
|
|
firstChildren.length = 0;
|
|
|
|
return targetChild;
|
|
}
|
|
}
|
|
|
|
firstChildren.length = 0;
|
|
|
|
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined;
|
|
},
|
|
|
|
_mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) {
|
|
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined;
|
|
|
|
if (shouldReuseMarkup) {
|
|
var rootElement = getReactRootElementInContainer(container);
|
|
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
|
|
return;
|
|
} else {
|
|
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
|
|
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
|
|
|
|
var rootMarkup = rootElement.outerHTML;
|
|
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
|
|
|
|
var normalizedMarkup = markup;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// because rootMarkup is retrieved from the DOM, various normalizations
|
|
// will have occurred which will not be present in `markup`. Here,
|
|
// insert markup into a <div> or <iframe> depending on the container
|
|
// type to perform the same normalizations before comparing.
|
|
var normalizer;
|
|
if (container.nodeType === ELEMENT_NODE_TYPE) {
|
|
normalizer = document.createElement('div');
|
|
normalizer.innerHTML = markup;
|
|
normalizedMarkup = normalizer.innerHTML;
|
|
} else {
|
|
normalizer = document.createElement('iframe');
|
|
document.body.appendChild(normalizer);
|
|
normalizer.contentDocument.write(markup);
|
|
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
|
|
document.body.removeChild(normalizer);
|
|
}
|
|
}
|
|
|
|
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
|
|
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
|
|
|
|
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
|
|
|
|
if (transaction.useCreateElement) {
|
|
while (container.lastChild) {
|
|
container.removeChild(container.lastChild);
|
|
}
|
|
container.appendChild(markup);
|
|
} else {
|
|
setInnerHTML(container, markup);
|
|
}
|
|
},
|
|
|
|
ownerDocumentContextKey: ownerDocumentContextKey,
|
|
|
|
/**
|
|
* React ID utilities.
|
|
*/
|
|
|
|
getReactRootID: getReactRootID,
|
|
|
|
getID: getID,
|
|
|
|
setID: setID,
|
|
|
|
getNode: getNode,
|
|
|
|
getNodeFromInstance: getNodeFromInstance,
|
|
|
|
isValid: isValid,
|
|
|
|
purgeID: purgeID
|
|
};
|
|
|
|
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
|
|
_renderNewRootComponent: '_renderNewRootComponent',
|
|
_mountImageIntoNode: '_mountImageIntoNode'
|
|
});
|
|
|
|
module.exports = ReactMount;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 29 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactBrowserEventEmitter
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPluginHub = __webpack_require__(31);
|
|
var EventPluginRegistry = __webpack_require__(32);
|
|
var ReactEventEmitterMixin = __webpack_require__(37);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ViewportMetrics = __webpack_require__(38);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var isEventSupported = __webpack_require__(40);
|
|
|
|
/**
|
|
* 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
|
|
* ReactEventListener, 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 isMonitoringScrollValue = false;
|
|
var reactTopListenersCounter = 0;
|
|
|
|
// For events like 'submit' 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 topEventMapping = {
|
|
topAbort: 'abort',
|
|
topBlur: 'blur',
|
|
topCanPlay: 'canplay',
|
|
topCanPlayThrough: 'canplaythrough',
|
|
topChange: 'change',
|
|
topClick: 'click',
|
|
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',
|
|
topDurationChange: 'durationchange',
|
|
topEmptied: 'emptied',
|
|
topEncrypted: 'encrypted',
|
|
topEnded: 'ended',
|
|
topError: 'error',
|
|
topFocus: 'focus',
|
|
topInput: 'input',
|
|
topKeyDown: 'keydown',
|
|
topKeyPress: 'keypress',
|
|
topKeyUp: 'keyup',
|
|
topLoadedData: 'loadeddata',
|
|
topLoadedMetadata: 'loadedmetadata',
|
|
topLoadStart: 'loadstart',
|
|
topMouseDown: 'mousedown',
|
|
topMouseMove: 'mousemove',
|
|
topMouseOut: 'mouseout',
|
|
topMouseOver: 'mouseover',
|
|
topMouseUp: 'mouseup',
|
|
topPaste: 'paste',
|
|
topPause: 'pause',
|
|
topPlay: 'play',
|
|
topPlaying: 'playing',
|
|
topProgress: 'progress',
|
|
topRateChange: 'ratechange',
|
|
topScroll: 'scroll',
|
|
topSeeked: 'seeked',
|
|
topSeeking: 'seeking',
|
|
topSelectionChange: 'selectionchange',
|
|
topStalled: 'stalled',
|
|
topSuspend: 'suspend',
|
|
topTextInput: 'textInput',
|
|
topTimeUpdate: 'timeupdate',
|
|
topTouchCancel: 'touchcancel',
|
|
topTouchEnd: 'touchend',
|
|
topTouchMove: 'touchmove',
|
|
topTouchStart: 'touchstart',
|
|
topVolumeChange: 'volumechange',
|
|
topWaiting: 'waiting',
|
|
topWheel: 'wheel'
|
|
};
|
|
|
|
/**
|
|
* To ensure no conflicts with other potential React instances on the page
|
|
*/
|
|
var topListenersIDKey = '_reactListenersID' + String(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]];
|
|
}
|
|
|
|
/**
|
|
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
|
|
* example:
|
|
*
|
|
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
|
|
*
|
|
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
|
|
*
|
|
* @internal
|
|
*/
|
|
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
|
|
|
|
/**
|
|
* Injectable event backend
|
|
*/
|
|
ReactEventListener: null,
|
|
|
|
injection: {
|
|
/**
|
|
* @param {object} ReactEventListener
|
|
*/
|
|
injectReactEventListener: function (ReactEventListener) {
|
|
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
|
|
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Sets whether or not any created callbacks should be enabled.
|
|
*
|
|
* @param {boolean} enabled True if callbacks should be enabled.
|
|
*/
|
|
setEnabled: function (enabled) {
|
|
if (ReactBrowserEventEmitter.ReactEventListener) {
|
|
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* @return {boolean} True if callbacks are enabled.
|
|
*/
|
|
isEnabled: function () {
|
|
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
|
|
},
|
|
|
|
/**
|
|
* 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
|
|
*/
|
|
listenTo: function (registrationName, contentDocumentHandle) {
|
|
var mountAt = contentDocumentHandle;
|
|
var isListening = getListeningForDocument(mountAt);
|
|
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
for (var i = 0; i < dependencies.length; i++) {
|
|
var dependency = dependencies[i];
|
|
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
|
|
if (dependency === topLevelTypes.topWheel) {
|
|
if (isEventSupported('wheel')) {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
|
|
} else if (isEventSupported('mousewheel')) {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
|
|
} else {
|
|
// Firefox needs to capture a different mouse scroll event.
|
|
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
|
|
}
|
|
} else if (dependency === topLevelTypes.topScroll) {
|
|
|
|
if (isEventSupported('scroll', true)) {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
|
|
} else {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
|
|
}
|
|
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
|
|
|
|
if (isEventSupported('focus', true)) {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
|
|
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
|
|
} else if (isEventSupported('focusin')) {
|
|
// IE has `focusin` and `focusout` events which bubble.
|
|
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
|
|
}
|
|
|
|
// to make sure blur and focus event listeners are only attached once
|
|
isListening[topLevelTypes.topBlur] = true;
|
|
isListening[topLevelTypes.topFocus] = true;
|
|
} else if (topEventMapping.hasOwnProperty(dependency)) {
|
|
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
|
|
}
|
|
|
|
isListening[dependency] = true;
|
|
}
|
|
}
|
|
},
|
|
|
|
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
|
|
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
|
|
},
|
|
|
|
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
|
|
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
|
|
},
|
|
|
|
/**
|
|
* Listens to window scroll and resize events. We cache scroll values so that
|
|
* application code can access them without triggering reflows.
|
|
*
|
|
* NOTE: Scroll events do not bubble.
|
|
*
|
|
* @see http://www.quirksmode.org/dom/events/scroll.html
|
|
*/
|
|
ensureScrollValueMonitoring: function () {
|
|
if (!isMonitoringScrollValue) {
|
|
var refresh = ViewportMetrics.refreshScrollValues;
|
|
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
|
|
isMonitoringScrollValue = true;
|
|
}
|
|
},
|
|
|
|
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
|
|
|
|
registrationNameModules: EventPluginHub.registrationNameModules,
|
|
|
|
putListener: EventPluginHub.putListener,
|
|
|
|
getListener: EventPluginHub.getListener,
|
|
|
|
deleteListener: EventPluginHub.deleteListener,
|
|
|
|
deleteAllListeners: EventPluginHub.deleteAllListeners
|
|
|
|
});
|
|
|
|
ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', {
|
|
putListener: 'putListener',
|
|
deleteListener: 'deleteListener'
|
|
});
|
|
|
|
module.exports = ReactBrowserEventEmitter;
|
|
|
|
/***/ }),
|
|
/* 30 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EventConstants
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var keyMirror = __webpack_require__(17);
|
|
|
|
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
|
|
|
|
/**
|
|
* Types of raw signals from the browser caught at the top level.
|
|
*/
|
|
var topLevelTypes = keyMirror({
|
|
topAbort: null,
|
|
topBlur: null,
|
|
topCanPlay: null,
|
|
topCanPlayThrough: null,
|
|
topChange: null,
|
|
topClick: null,
|
|
topCompositionEnd: null,
|
|
topCompositionStart: null,
|
|
topCompositionUpdate: null,
|
|
topContextMenu: null,
|
|
topCopy: null,
|
|
topCut: null,
|
|
topDoubleClick: null,
|
|
topDrag: null,
|
|
topDragEnd: null,
|
|
topDragEnter: null,
|
|
topDragExit: null,
|
|
topDragLeave: null,
|
|
topDragOver: null,
|
|
topDragStart: null,
|
|
topDrop: null,
|
|
topDurationChange: null,
|
|
topEmptied: null,
|
|
topEncrypted: null,
|
|
topEnded: null,
|
|
topError: null,
|
|
topFocus: null,
|
|
topInput: null,
|
|
topKeyDown: null,
|
|
topKeyPress: null,
|
|
topKeyUp: null,
|
|
topLoad: null,
|
|
topLoadedData: null,
|
|
topLoadedMetadata: null,
|
|
topLoadStart: null,
|
|
topMouseDown: null,
|
|
topMouseMove: null,
|
|
topMouseOut: null,
|
|
topMouseOver: null,
|
|
topMouseUp: null,
|
|
topPaste: null,
|
|
topPause: null,
|
|
topPlay: null,
|
|
topPlaying: null,
|
|
topProgress: null,
|
|
topRateChange: null,
|
|
topReset: null,
|
|
topScroll: null,
|
|
topSeeked: null,
|
|
topSeeking: null,
|
|
topSelectionChange: null,
|
|
topStalled: null,
|
|
topSubmit: null,
|
|
topSuspend: null,
|
|
topTextInput: null,
|
|
topTimeUpdate: null,
|
|
topTouchCancel: null,
|
|
topTouchEnd: null,
|
|
topTouchMove: null,
|
|
topTouchStart: null,
|
|
topVolumeChange: null,
|
|
topWaiting: null,
|
|
topWheel: null
|
|
});
|
|
|
|
var EventConstants = {
|
|
topLevelTypes: topLevelTypes,
|
|
PropagationPhases: PropagationPhases
|
|
};
|
|
|
|
module.exports = EventConstants;
|
|
|
|
/***/ }),
|
|
/* 31 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EventPluginHub
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventPluginRegistry = __webpack_require__(32);
|
|
var EventPluginUtils = __webpack_require__(33);
|
|
var ReactErrorUtils = __webpack_require__(34);
|
|
|
|
var accumulateInto = __webpack_require__(35);
|
|
var forEachAccumulated = __webpack_require__(36);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* Internal store for event listeners
|
|
*/
|
|
var listenerBank = {};
|
|
|
|
/**
|
|
* Internal queue of events that have accumulated their dispatches and are
|
|
* waiting to have their dispatches executed.
|
|
*/
|
|
var eventQueue = null;
|
|
|
|
/**
|
|
* Dispatches an event and releases it back into the pool, unless persistent.
|
|
*
|
|
* @param {?object} event Synthetic event to be dispatched.
|
|
* @param {boolean} simulated If the event is simulated (changes exn behavior)
|
|
* @private
|
|
*/
|
|
var executeDispatchesAndRelease = function (event, simulated) {
|
|
if (event) {
|
|
EventPluginUtils.executeDispatchesInOrder(event, simulated);
|
|
|
|
if (!event.isPersistent()) {
|
|
event.constructor.release(event);
|
|
}
|
|
}
|
|
};
|
|
var executeDispatchesAndReleaseSimulated = function (e) {
|
|
return executeDispatchesAndRelease(e, true);
|
|
};
|
|
var executeDispatchesAndReleaseTopLevel = function (e) {
|
|
return executeDispatchesAndRelease(e, false);
|
|
};
|
|
|
|
/**
|
|
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
|
|
* hierarchy given ids of the logical DOM elements involved.
|
|
*/
|
|
var InstanceHandle = null;
|
|
|
|
function validateInstanceHandle() {
|
|
var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave;
|
|
process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined;
|
|
}
|
|
|
|
/**
|
|
* This is a unified interface for event plugins to be installed and configured.
|
|
*
|
|
* Event plugins can implement the following properties:
|
|
*
|
|
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
|
|
* Required. When a top-level event is fired, this method is expected to
|
|
* extract synthetic events that will in turn be queued and dispatched.
|
|
*
|
|
* `eventTypes` {object}
|
|
* Optional, plugins that fire events must publish a mapping of registration
|
|
* names that are used to register listeners. Values of this mapping must
|
|
* be objects that contain `registrationName` or `phasedRegistrationNames`.
|
|
*
|
|
* `executeDispatch` {function(object, function, string)}
|
|
* Optional, allows plugins to override how an event gets dispatched. By
|
|
* default, the listener is simply invoked.
|
|
*
|
|
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
|
|
*
|
|
* @public
|
|
*/
|
|
var EventPluginHub = {
|
|
|
|
/**
|
|
* Methods for injecting dependencies.
|
|
*/
|
|
injection: {
|
|
|
|
/**
|
|
* @param {object} InjectedMount
|
|
* @public
|
|
*/
|
|
injectMount: EventPluginUtils.injection.injectMount,
|
|
|
|
/**
|
|
* @param {object} InjectedInstanceHandle
|
|
* @public
|
|
*/
|
|
injectInstanceHandle: function (InjectedInstanceHandle) {
|
|
InstanceHandle = InjectedInstanceHandle;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateInstanceHandle();
|
|
}
|
|
},
|
|
|
|
getInstanceHandle: function () {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateInstanceHandle();
|
|
}
|
|
return InstanceHandle;
|
|
},
|
|
|
|
/**
|
|
* @param {array} InjectedEventPluginOrder
|
|
* @public
|
|
*/
|
|
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
|
|
|
|
/**
|
|
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
|
|
*/
|
|
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
|
|
|
|
},
|
|
|
|
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
|
|
|
|
registrationNameModules: EventPluginRegistry.registrationNameModules,
|
|
|
|
/**
|
|
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
|
|
*
|
|
* @param {string} id ID of the DOM element.
|
|
* @param {string} registrationName Name of listener (e.g. `onClick`).
|
|
* @param {?function} listener The callback to store.
|
|
*/
|
|
putListener: function (id, registrationName, listener) {
|
|
!(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined;
|
|
|
|
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
|
|
bankForRegistrationName[id] = listener;
|
|
|
|
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
|
|
if (PluginModule && PluginModule.didPutListener) {
|
|
PluginModule.didPutListener(id, registrationName, listener);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* @param {string} id ID of the DOM element.
|
|
* @param {string} registrationName Name of listener (e.g. `onClick`).
|
|
* @return {?function} The stored callback.
|
|
*/
|
|
getListener: function (id, registrationName) {
|
|
var bankForRegistrationName = listenerBank[registrationName];
|
|
return bankForRegistrationName && bankForRegistrationName[id];
|
|
},
|
|
|
|
/**
|
|
* Deletes a listener from the registration bank.
|
|
*
|
|
* @param {string} id ID of the DOM element.
|
|
* @param {string} registrationName Name of listener (e.g. `onClick`).
|
|
*/
|
|
deleteListener: function (id, registrationName) {
|
|
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
|
|
if (PluginModule && PluginModule.willDeleteListener) {
|
|
PluginModule.willDeleteListener(id, registrationName);
|
|
}
|
|
|
|
var bankForRegistrationName = listenerBank[registrationName];
|
|
// TODO: This should never be null -- when is it?
|
|
if (bankForRegistrationName) {
|
|
delete bankForRegistrationName[id];
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Deletes all listeners for the DOM element with the supplied ID.
|
|
*
|
|
* @param {string} id ID of the DOM element.
|
|
*/
|
|
deleteAllListeners: function (id) {
|
|
for (var registrationName in listenerBank) {
|
|
if (!listenerBank[registrationName][id]) {
|
|
continue;
|
|
}
|
|
|
|
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
|
|
if (PluginModule && PluginModule.willDeleteListener) {
|
|
PluginModule.willDeleteListener(id, registrationName);
|
|
}
|
|
|
|
delete listenerBank[registrationName][id];
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Allows registered plugins an opportunity to extract events from top-level
|
|
* native browser events.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @internal
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
var events;
|
|
var plugins = EventPluginRegistry.plugins;
|
|
for (var i = 0; i < plugins.length; i++) {
|
|
// Not every plugin in the ordering may be loaded at runtime.
|
|
var possiblePlugin = plugins[i];
|
|
if (possiblePlugin) {
|
|
var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
|
|
if (extractedEvents) {
|
|
events = accumulateInto(events, extractedEvents);
|
|
}
|
|
}
|
|
}
|
|
return events;
|
|
},
|
|
|
|
/**
|
|
* Enqueues a synthetic event that should be dispatched when
|
|
* `processEventQueue` is invoked.
|
|
*
|
|
* @param {*} events An accumulation of synthetic events.
|
|
* @internal
|
|
*/
|
|
enqueueEvents: function (events) {
|
|
if (events) {
|
|
eventQueue = accumulateInto(eventQueue, events);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Dispatches all synthetic events on the event queue.
|
|
*
|
|
* @internal
|
|
*/
|
|
processEventQueue: function (simulated) {
|
|
// Set `eventQueue` to null before processing it so that we can tell if more
|
|
// events get enqueued while processing.
|
|
var processingEventQueue = eventQueue;
|
|
eventQueue = null;
|
|
if (simulated) {
|
|
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
|
|
} else {
|
|
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
|
|
}
|
|
!!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined;
|
|
// This would be a good time to rethrow if any of the event handlers threw.
|
|
ReactErrorUtils.rethrowCaughtError();
|
|
},
|
|
|
|
/**
|
|
* These are needed for tests only. Do not use!
|
|
*/
|
|
__purge: function () {
|
|
listenerBank = {};
|
|
},
|
|
|
|
__getListenerBank: function () {
|
|
return listenerBank;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = EventPluginHub;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 32 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EventPluginRegistry
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Injectable ordering of event plugins.
|
|
*/
|
|
var EventPluginOrder = null;
|
|
|
|
/**
|
|
* Injectable mapping from names to event plugin modules.
|
|
*/
|
|
var namesToPlugins = {};
|
|
|
|
/**
|
|
* Recomputes the plugin list using the injected plugins and plugin ordering.
|
|
*
|
|
* @private
|
|
*/
|
|
function recomputePluginOrdering() {
|
|
if (!EventPluginOrder) {
|
|
// Wait until an `EventPluginOrder` is injected.
|
|
return;
|
|
}
|
|
for (var pluginName in namesToPlugins) {
|
|
var PluginModule = namesToPlugins[pluginName];
|
|
var pluginIndex = EventPluginOrder.indexOf(pluginName);
|
|
!(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined;
|
|
if (EventPluginRegistry.plugins[pluginIndex]) {
|
|
continue;
|
|
}
|
|
!PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined;
|
|
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
|
|
var publishedEvents = PluginModule.eventTypes;
|
|
for (var eventName in publishedEvents) {
|
|
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Publishes an event so that it can be dispatched by the supplied plugin.
|
|
*
|
|
* @param {object} dispatchConfig Dispatch configuration for the event.
|
|
* @param {object} PluginModule Plugin publishing the event.
|
|
* @return {boolean} True if the event was successfully published.
|
|
* @private
|
|
*/
|
|
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
|
|
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined;
|
|
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
|
|
|
|
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
|
|
if (phasedRegistrationNames) {
|
|
for (var phaseName in phasedRegistrationNames) {
|
|
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
|
|
var phasedRegistrationName = phasedRegistrationNames[phaseName];
|
|
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
|
|
}
|
|
}
|
|
return true;
|
|
} else if (dispatchConfig.registrationName) {
|
|
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Publishes a registration name that is used to identify dispatched events and
|
|
* can be used with `EventPluginHub.putListener` to register listeners.
|
|
*
|
|
* @param {string} registrationName Registration name to add.
|
|
* @param {object} PluginModule Plugin publishing the event.
|
|
* @private
|
|
*/
|
|
function publishRegistrationName(registrationName, PluginModule, eventName) {
|
|
!!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined;
|
|
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
|
|
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
|
|
}
|
|
|
|
/**
|
|
* Registers plugins so that they can extract and dispatch events.
|
|
*
|
|
* @see {EventPluginHub}
|
|
*/
|
|
var EventPluginRegistry = {
|
|
|
|
/**
|
|
* Ordered list of injected plugins.
|
|
*/
|
|
plugins: [],
|
|
|
|
/**
|
|
* Mapping from event name to dispatch config
|
|
*/
|
|
eventNameDispatchConfigs: {},
|
|
|
|
/**
|
|
* Mapping from registration name to plugin module
|
|
*/
|
|
registrationNameModules: {},
|
|
|
|
/**
|
|
* Mapping from registration name to event name
|
|
*/
|
|
registrationNameDependencies: {},
|
|
|
|
/**
|
|
* Injects an ordering of plugins (by plugin name). This allows the ordering
|
|
* to be decoupled from injection of the actual plugins so that ordering is
|
|
* always deterministic regardless of packaging, on-the-fly injection, etc.
|
|
*
|
|
* @param {array} InjectedEventPluginOrder
|
|
* @internal
|
|
* @see {EventPluginHub.injection.injectEventPluginOrder}
|
|
*/
|
|
injectEventPluginOrder: function (InjectedEventPluginOrder) {
|
|
!!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined;
|
|
// Clone the ordering so it cannot be dynamically mutated.
|
|
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
|
|
recomputePluginOrdering();
|
|
},
|
|
|
|
/**
|
|
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
|
|
* in the ordering injected by `injectEventPluginOrder`.
|
|
*
|
|
* Plugins can be injected as part of page initialization or on-the-fly.
|
|
*
|
|
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
|
|
* @internal
|
|
* @see {EventPluginHub.injection.injectEventPluginsByName}
|
|
*/
|
|
injectEventPluginsByName: function (injectedNamesToPlugins) {
|
|
var isOrderingDirty = false;
|
|
for (var pluginName in injectedNamesToPlugins) {
|
|
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
|
|
continue;
|
|
}
|
|
var PluginModule = injectedNamesToPlugins[pluginName];
|
|
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
|
|
!!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined;
|
|
namesToPlugins[pluginName] = PluginModule;
|
|
isOrderingDirty = true;
|
|
}
|
|
}
|
|
if (isOrderingDirty) {
|
|
recomputePluginOrdering();
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Looks up the plugin for the supplied event.
|
|
*
|
|
* @param {object} event A synthetic event.
|
|
* @return {?object} The plugin that created the supplied event.
|
|
* @internal
|
|
*/
|
|
getPluginModuleForEvent: function (event) {
|
|
var dispatchConfig = event.dispatchConfig;
|
|
if (dispatchConfig.registrationName) {
|
|
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
|
|
}
|
|
for (var phase in dispatchConfig.phasedRegistrationNames) {
|
|
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
|
|
continue;
|
|
}
|
|
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
|
|
if (PluginModule) {
|
|
return PluginModule;
|
|
}
|
|
}
|
|
return null;
|
|
},
|
|
|
|
/**
|
|
* Exposed for unit testing.
|
|
* @private
|
|
*/
|
|
_resetEventPlugins: function () {
|
|
EventPluginOrder = null;
|
|
for (var pluginName in namesToPlugins) {
|
|
if (namesToPlugins.hasOwnProperty(pluginName)) {
|
|
delete namesToPlugins[pluginName];
|
|
}
|
|
}
|
|
EventPluginRegistry.plugins.length = 0;
|
|
|
|
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
|
|
for (var eventName in eventNameDispatchConfigs) {
|
|
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
|
|
delete eventNameDispatchConfigs[eventName];
|
|
}
|
|
}
|
|
|
|
var registrationNameModules = EventPluginRegistry.registrationNameModules;
|
|
for (var registrationName in registrationNameModules) {
|
|
if (registrationNameModules.hasOwnProperty(registrationName)) {
|
|
delete registrationNameModules[registrationName];
|
|
}
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = EventPluginRegistry;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 33 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EventPluginUtils
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var ReactErrorUtils = __webpack_require__(34);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* Injected dependencies:
|
|
*/
|
|
|
|
/**
|
|
* - `Mount`: [required] Module that can convert between React dom IDs and
|
|
* actual node references.
|
|
*/
|
|
var injection = {
|
|
Mount: null,
|
|
injectMount: function (InjectedMount) {
|
|
injection.Mount = InjectedMount;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined;
|
|
}
|
|
}
|
|
};
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
|
|
function isEndish(topLevelType) {
|
|
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
|
|
}
|
|
|
|
function isMoveish(topLevelType) {
|
|
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
|
|
}
|
|
function isStartish(topLevelType) {
|
|
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
|
|
}
|
|
|
|
var validateEventDispatches;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateEventDispatches = function (event) {
|
|
var dispatchListeners = event._dispatchListeners;
|
|
var dispatchIDs = event._dispatchIDs;
|
|
|
|
var listenersIsArr = Array.isArray(dispatchListeners);
|
|
var idsIsArr = Array.isArray(dispatchIDs);
|
|
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
|
|
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
|
|
|
|
process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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 {string} domID DOM id to pass to the callback.
|
|
*/
|
|
function executeDispatch(event, simulated, listener, domID) {
|
|
var type = event.type || 'unknown-event';
|
|
event.currentTarget = injection.Mount.getNode(domID);
|
|
if (simulated) {
|
|
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID);
|
|
} else {
|
|
ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
|
|
}
|
|
event.currentTarget = null;
|
|
}
|
|
|
|
/**
|
|
* Standard/simple iteration through an event's collected dispatches.
|
|
*/
|
|
function executeDispatchesInOrder(event, simulated) {
|
|
var dispatchListeners = event._dispatchListeners;
|
|
var dispatchIDs = event._dispatchIDs;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateEventDispatches(event);
|
|
}
|
|
if (Array.isArray(dispatchListeners)) {
|
|
for (var i = 0; i < dispatchListeners.length; i++) {
|
|
if (event.isPropagationStopped()) {
|
|
break;
|
|
}
|
|
// Listeners and IDs are two parallel arrays that are always in sync.
|
|
executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]);
|
|
}
|
|
} else if (dispatchListeners) {
|
|
executeDispatch(event, simulated, dispatchListeners, dispatchIDs);
|
|
}
|
|
event._dispatchListeners = null;
|
|
event._dispatchIDs = null;
|
|
}
|
|
|
|
/**
|
|
* Standard/simple iteration through an event's collected dispatches, but stops
|
|
* at the first dispatch execution returning true, and returns that id.
|
|
*
|
|
* @return {?string} id of the first dispatch execution who's listener returns
|
|
* true, or null if no listener returned true.
|
|
*/
|
|
function executeDispatchesInOrderStopAtTrueImpl(event) {
|
|
var dispatchListeners = event._dispatchListeners;
|
|
var dispatchIDs = event._dispatchIDs;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateEventDispatches(event);
|
|
}
|
|
if (Array.isArray(dispatchListeners)) {
|
|
for (var i = 0; i < dispatchListeners.length; i++) {
|
|
if (event.isPropagationStopped()) {
|
|
break;
|
|
}
|
|
// Listeners and IDs are two parallel arrays that are always in sync.
|
|
if (dispatchListeners[i](event, dispatchIDs[i])) {
|
|
return dispatchIDs[i];
|
|
}
|
|
}
|
|
} else if (dispatchListeners) {
|
|
if (dispatchListeners(event, dispatchIDs)) {
|
|
return dispatchIDs;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @see executeDispatchesInOrderStopAtTrueImpl
|
|
*/
|
|
function executeDispatchesInOrderStopAtTrue(event) {
|
|
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
|
|
event._dispatchIDs = null;
|
|
event._dispatchListeners = null;
|
|
return ret;
|
|
}
|
|
|
|
/**
|
|
* Execution of a "direct" dispatch - there must be at most one dispatch
|
|
* accumulated on the event or it is considered an error. It doesn't really make
|
|
* sense for an event with multiple dispatches (bubbled) to keep track of the
|
|
* return values at each dispatch execution, but it does tend to make sense when
|
|
* dealing with "direct" dispatches.
|
|
*
|
|
* @return {*} The return value of executing the single dispatch.
|
|
*/
|
|
function executeDirectDispatch(event) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateEventDispatches(event);
|
|
}
|
|
var dispatchListener = event._dispatchListeners;
|
|
var dispatchID = event._dispatchIDs;
|
|
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined;
|
|
var res = dispatchListener ? dispatchListener(event, dispatchID) : null;
|
|
event._dispatchListeners = null;
|
|
event._dispatchIDs = null;
|
|
return res;
|
|
}
|
|
|
|
/**
|
|
* @param {SyntheticEvent} event
|
|
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
|
|
*/
|
|
function hasDispatches(event) {
|
|
return !!event._dispatchListeners;
|
|
}
|
|
|
|
/**
|
|
* General utilities that are useful in creating custom Event Plugins.
|
|
*/
|
|
var EventPluginUtils = {
|
|
isEndish: isEndish,
|
|
isMoveish: isMoveish,
|
|
isStartish: isStartish,
|
|
|
|
executeDirectDispatch: executeDirectDispatch,
|
|
executeDispatchesInOrder: executeDispatchesInOrder,
|
|
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
|
|
hasDispatches: hasDispatches,
|
|
|
|
getNode: function (id) {
|
|
return injection.Mount.getNode(id);
|
|
},
|
|
getID: function (node) {
|
|
return injection.Mount.getID(node);
|
|
},
|
|
|
|
injection: injection
|
|
};
|
|
|
|
module.exports = EventPluginUtils;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 34 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactErrorUtils
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var caughtError = null;
|
|
|
|
/**
|
|
* Call a function while guarding against errors that happens within it.
|
|
*
|
|
* @param {?String} name of the guard to use for logging or debugging
|
|
* @param {Function} func The function to invoke
|
|
* @param {*} a First argument
|
|
* @param {*} b Second argument
|
|
*/
|
|
function invokeGuardedCallback(name, func, a, b) {
|
|
try {
|
|
return func(a, b);
|
|
} catch (x) {
|
|
if (caughtError === null) {
|
|
caughtError = x;
|
|
}
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
var ReactErrorUtils = {
|
|
invokeGuardedCallback: invokeGuardedCallback,
|
|
|
|
/**
|
|
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
|
|
* handler are sure to be rethrown by rethrowCaughtError.
|
|
*/
|
|
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
|
|
|
|
/**
|
|
* During execution of guarded functions we will capture the first error which
|
|
* we will rethrow to be handled by the top level error handler.
|
|
*/
|
|
rethrowCaughtError: function () {
|
|
if (caughtError) {
|
|
var error = caughtError;
|
|
caughtError = null;
|
|
throw error;
|
|
}
|
|
}
|
|
};
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
/**
|
|
* To help development we can get better devtools integration by simulating a
|
|
* real browser event.
|
|
*/
|
|
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
|
|
var fakeNode = document.createElement('react');
|
|
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
|
|
var boundFunc = func.bind(null, a, b);
|
|
var evtType = 'react-' + name;
|
|
fakeNode.addEventListener(evtType, boundFunc, false);
|
|
var evt = document.createEvent('Event');
|
|
evt.initEvent(evtType, false, false);
|
|
fakeNode.dispatchEvent(evt);
|
|
fakeNode.removeEventListener(evtType, boundFunc, false);
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = ReactErrorUtils;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 35 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule accumulateInto
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
*
|
|
* Accumulates items that must not be null or undefined into the first one. This
|
|
* is used to conserve memory by avoiding array allocations, and thus sacrifices
|
|
* API cleanness. Since `current` can be null before being passed in and not
|
|
* null after this function, make sure to assign it back to `current`:
|
|
*
|
|
* `a = accumulateInto(a, b);`
|
|
*
|
|
* This API should be sparingly used. Try `accumulate` for something cleaner.
|
|
*
|
|
* @return {*|array<*>} An accumulation of items.
|
|
*/
|
|
|
|
function accumulateInto(current, next) {
|
|
!(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined;
|
|
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).
|
|
var currentIsArray = Array.isArray(current);
|
|
var nextIsArray = Array.isArray(next);
|
|
|
|
if (currentIsArray && nextIsArray) {
|
|
current.push.apply(current, next);
|
|
return current;
|
|
}
|
|
|
|
if (currentIsArray) {
|
|
current.push(next);
|
|
return current;
|
|
}
|
|
|
|
if (nextIsArray) {
|
|
// A bit too dangerous to mutate `next`.
|
|
return [current].concat(next);
|
|
}
|
|
|
|
return [current, next];
|
|
}
|
|
|
|
module.exports = accumulateInto;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 36 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule forEachAccumulated
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* @param {array} arr an "accumulation" of items which is either an Array or
|
|
* a single item. Useful when paired with the `accumulate` module. This is a
|
|
* simple utility that allows us to reason about a collection of items, but
|
|
* handling the case when there is exactly one item (and we do not need to
|
|
* allocate an array).
|
|
*/
|
|
var forEachAccumulated = function (arr, cb, scope) {
|
|
if (Array.isArray(arr)) {
|
|
arr.forEach(cb, scope);
|
|
} else if (arr) {
|
|
cb.call(scope, arr);
|
|
}
|
|
};
|
|
|
|
module.exports = forEachAccumulated;
|
|
|
|
/***/ }),
|
|
/* 37 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactEventEmitterMixin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventPluginHub = __webpack_require__(31);
|
|
|
|
function runEventQueueInBatch(events) {
|
|
EventPluginHub.enqueueEvents(events);
|
|
EventPluginHub.processEventQueue(false);
|
|
}
|
|
|
|
var ReactEventEmitterMixin = {
|
|
|
|
/**
|
|
* Streams a fired top-level event to `EventPluginHub` where plugins have the
|
|
* opportunity to create `ReactEvent`s to be dispatched.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {object} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native environment event.
|
|
*/
|
|
handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
|
|
runEventQueueInBatch(events);
|
|
}
|
|
};
|
|
|
|
module.exports = ReactEventEmitterMixin;
|
|
|
|
/***/ }),
|
|
/* 38 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ViewportMetrics
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ViewportMetrics = {
|
|
|
|
currentScrollLeft: 0,
|
|
|
|
currentScrollTop: 0,
|
|
|
|
refreshScrollValues: function (scrollPosition) {
|
|
ViewportMetrics.currentScrollLeft = scrollPosition.x;
|
|
ViewportMetrics.currentScrollTop = scrollPosition.y;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ViewportMetrics;
|
|
|
|
/***/ }),
|
|
/* 39 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule Object.assign
|
|
*/
|
|
|
|
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
|
|
|
|
'use strict';
|
|
|
|
function assign(target, sources) {
|
|
if (target == null) {
|
|
throw new TypeError('Object.assign target cannot be null or undefined');
|
|
}
|
|
|
|
var to = Object(target);
|
|
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
|
|
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
|
|
var nextSource = arguments[nextIndex];
|
|
if (nextSource == null) {
|
|
continue;
|
|
}
|
|
|
|
var from = Object(nextSource);
|
|
|
|
// We don't currently support accessors nor proxies. Therefore this
|
|
// copy cannot throw. If we ever supported this then we must handle
|
|
// exceptions and side-effects. We don't support symbols so they won't
|
|
// be transferred.
|
|
|
|
for (var key in from) {
|
|
if (hasOwnProperty.call(from, key)) {
|
|
to[key] = from[key];
|
|
}
|
|
}
|
|
}
|
|
|
|
return to;
|
|
}
|
|
|
|
module.exports = assign;
|
|
|
|
/***/ }),
|
|
/* 40 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule isEventSupported
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var useHasFeature;
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
useHasFeature = document.implementation && document.implementation.hasFeature &&
|
|
// always returns true in newer browsers as per the standard.
|
|
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
|
|
document.implementation.hasFeature('', '') !== true;
|
|
}
|
|
|
|
/**
|
|
* 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';
|
|
}
|
|
|
|
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
|
|
// This is the only way to test support for the `wheel` event in IE9+.
|
|
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
|
|
}
|
|
|
|
return isSupported;
|
|
}
|
|
|
|
module.exports = isEventSupported;
|
|
|
|
/***/ }),
|
|
/* 41 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMFeatureFlags
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDOMFeatureFlags = {
|
|
useCreateElement: false
|
|
};
|
|
|
|
module.exports = ReactDOMFeatureFlags;
|
|
|
|
/***/ }),
|
|
/* 42 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactElement
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var canDefineProperty = __webpack_require__(43);
|
|
|
|
// The Symbol used to tag the ReactElement type. If there is no native Symbol
|
|
// nor polyfill, then a plain number is used for performance.
|
|
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
|
|
|
|
var RESERVED_PROPS = {
|
|
key: true,
|
|
ref: true,
|
|
__self: true,
|
|
__source: true
|
|
};
|
|
|
|
/**
|
|
* Base constructor for all React elements. This is only used to make this
|
|
* work with a dynamic instanceof check. Nothing should live on this prototype.
|
|
*
|
|
* @param {*} type
|
|
* @param {*} key
|
|
* @param {string|object} ref
|
|
* @param {*} self A *temporary* helper to detect places where `this` is
|
|
* different from the `owner` when React.createElement is called, so that we
|
|
* can warn. We want to get rid of owner and replace string `ref`s with arrow
|
|
* functions, and as long as `this` and owner are the same, there will be no
|
|
* change in behavior.
|
|
* @param {*} source An annotation object (added by a transpiler or otherwise)
|
|
* indicating filename, line number, and/or other information.
|
|
* @param {*} owner
|
|
* @param {*} props
|
|
* @internal
|
|
*/
|
|
var ReactElement = function (type, key, ref, self, source, owner, props) {
|
|
var element = {
|
|
// This tag allow us to uniquely identify this as a React Element
|
|
$$typeof: REACT_ELEMENT_TYPE,
|
|
|
|
// Built-in properties that belong on the element
|
|
type: type,
|
|
key: key,
|
|
ref: ref,
|
|
props: props,
|
|
|
|
// Record the component responsible for creating this element.
|
|
_owner: owner
|
|
};
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// The validation flag is currently mutative. We put it on
|
|
// an external backing store so that we can freeze the whole object.
|
|
// This can be replaced with a WeakMap once they are implemented in
|
|
// commonly used development environments.
|
|
element._store = {};
|
|
|
|
// To make comparing ReactElements easier for testing purposes, we make
|
|
// the validation flag non-enumerable (where possible, which should
|
|
// include every environment we run tests in), so the test framework
|
|
// ignores it.
|
|
if (canDefineProperty) {
|
|
Object.defineProperty(element._store, 'validated', {
|
|
configurable: false,
|
|
enumerable: false,
|
|
writable: true,
|
|
value: false
|
|
});
|
|
// self and source are DEV only properties.
|
|
Object.defineProperty(element, '_self', {
|
|
configurable: false,
|
|
enumerable: false,
|
|
writable: false,
|
|
value: self
|
|
});
|
|
// Two elements created in two different places should be considered
|
|
// equal for testing purposes and therefore we hide it from enumeration.
|
|
Object.defineProperty(element, '_source', {
|
|
configurable: false,
|
|
enumerable: false,
|
|
writable: false,
|
|
value: source
|
|
});
|
|
} else {
|
|
element._store.validated = false;
|
|
element._self = self;
|
|
element._source = source;
|
|
}
|
|
Object.freeze(element.props);
|
|
Object.freeze(element);
|
|
}
|
|
|
|
return element;
|
|
};
|
|
|
|
ReactElement.createElement = function (type, config, children) {
|
|
var propName;
|
|
|
|
// Reserved names are extracted
|
|
var props = {};
|
|
|
|
var key = null;
|
|
var ref = null;
|
|
var self = null;
|
|
var source = null;
|
|
|
|
if (config != null) {
|
|
ref = config.ref === undefined ? null : config.ref;
|
|
key = config.key === undefined ? null : '' + config.key;
|
|
self = config.__self === undefined ? null : config.__self;
|
|
source = config.__source === undefined ? null : config.__source;
|
|
// Remaining properties are added to a new props object
|
|
for (propName in config) {
|
|
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
|
|
props[propName] = config[propName];
|
|
}
|
|
}
|
|
}
|
|
|
|
// Children can be more than one argument, and those are transferred onto
|
|
// the newly allocated props object.
|
|
var childrenLength = arguments.length - 2;
|
|
if (childrenLength === 1) {
|
|
props.children = children;
|
|
} else if (childrenLength > 1) {
|
|
var childArray = Array(childrenLength);
|
|
for (var i = 0; i < childrenLength; i++) {
|
|
childArray[i] = arguments[i + 2];
|
|
}
|
|
props.children = childArray;
|
|
}
|
|
|
|
// Resolve default props
|
|
if (type && type.defaultProps) {
|
|
var defaultProps = type.defaultProps;
|
|
for (propName in defaultProps) {
|
|
if (typeof props[propName] === 'undefined') {
|
|
props[propName] = defaultProps[propName];
|
|
}
|
|
}
|
|
}
|
|
|
|
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
|
|
};
|
|
|
|
ReactElement.createFactory = function (type) {
|
|
var factory = ReactElement.createElement.bind(null, type);
|
|
// Expose the type on the factory and the prototype so that it can be
|
|
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
|
|
// This should not be named `constructor` since this may not be the function
|
|
// that created the element, and it may not even be a constructor.
|
|
// Legacy hook TODO: Warn if this is accessed
|
|
factory.type = type;
|
|
return factory;
|
|
};
|
|
|
|
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
|
|
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
|
|
|
|
return newElement;
|
|
};
|
|
|
|
ReactElement.cloneAndReplaceProps = function (oldElement, newProps) {
|
|
var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// If the key on the original is valid, then the clone is valid
|
|
newElement._store.validated = oldElement._store.validated;
|
|
}
|
|
|
|
return newElement;
|
|
};
|
|
|
|
ReactElement.cloneElement = function (element, config, children) {
|
|
var propName;
|
|
|
|
// Original props are copied
|
|
var props = assign({}, element.props);
|
|
|
|
// Reserved names are extracted
|
|
var key = element.key;
|
|
var ref = element.ref;
|
|
// Self is preserved since the owner is preserved.
|
|
var self = element._self;
|
|
// Source is preserved since cloneElement is unlikely to be targeted by a
|
|
// transpiler, and the original source is probably a better indicator of the
|
|
// true owner.
|
|
var source = element._source;
|
|
|
|
// Owner will be preserved, unless ref is overridden
|
|
var owner = element._owner;
|
|
|
|
if (config != null) {
|
|
if (config.ref !== undefined) {
|
|
// Silently steal the ref from the parent.
|
|
ref = config.ref;
|
|
owner = ReactCurrentOwner.current;
|
|
}
|
|
if (config.key !== undefined) {
|
|
key = '' + config.key;
|
|
}
|
|
// Remaining properties override existing props
|
|
for (propName in config) {
|
|
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
|
|
props[propName] = config[propName];
|
|
}
|
|
}
|
|
}
|
|
|
|
// Children can be more than one argument, and those are transferred onto
|
|
// the newly allocated props object.
|
|
var childrenLength = arguments.length - 2;
|
|
if (childrenLength === 1) {
|
|
props.children = children;
|
|
} else if (childrenLength > 1) {
|
|
var childArray = Array(childrenLength);
|
|
for (var i = 0; i < childrenLength; i++) {
|
|
childArray[i] = arguments[i + 2];
|
|
}
|
|
props.children = childArray;
|
|
}
|
|
|
|
return ReactElement(element.type, key, ref, self, source, owner, props);
|
|
};
|
|
|
|
/**
|
|
* @param {?object} object
|
|
* @return {boolean} True if `object` is a valid component.
|
|
* @final
|
|
*/
|
|
ReactElement.isValidElement = function (object) {
|
|
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
|
|
};
|
|
|
|
module.exports = ReactElement;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 43 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule canDefineProperty
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var canDefineProperty = false;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
try {
|
|
Object.defineProperty({}, 'x', { get: function () {} });
|
|
canDefineProperty = true;
|
|
} catch (x) {
|
|
// IE will fail on defineProperty
|
|
}
|
|
}
|
|
|
|
module.exports = canDefineProperty;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 44 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactEmptyComponentRegistry
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
// This registry keeps track of the React IDs of the components that rendered to
|
|
// `null` (in reality a placeholder such as `noscript`)
|
|
var nullComponentIDsRegistry = {};
|
|
|
|
/**
|
|
* @param {string} id Component's `_rootNodeID`.
|
|
* @return {boolean} True if the component is rendered to null.
|
|
*/
|
|
function isNullComponentID(id) {
|
|
return !!nullComponentIDsRegistry[id];
|
|
}
|
|
|
|
/**
|
|
* Mark the component as having rendered to null.
|
|
* @param {string} id Component's `_rootNodeID`.
|
|
*/
|
|
function registerNullComponentID(id) {
|
|
nullComponentIDsRegistry[id] = true;
|
|
}
|
|
|
|
/**
|
|
* Unmark the component as having rendered to null: it renders to something now.
|
|
* @param {string} id Component's `_rootNodeID`.
|
|
*/
|
|
function deregisterNullComponentID(id) {
|
|
delete nullComponentIDsRegistry[id];
|
|
}
|
|
|
|
var ReactEmptyComponentRegistry = {
|
|
isNullComponentID: isNullComponentID,
|
|
registerNullComponentID: registerNullComponentID,
|
|
deregisterNullComponentID: deregisterNullComponentID
|
|
};
|
|
|
|
module.exports = ReactEmptyComponentRegistry;
|
|
|
|
/***/ }),
|
|
/* 45 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactInstanceHandles
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactRootIndex = __webpack_require__(46);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var SEPARATOR = '.';
|
|
var SEPARATOR_LENGTH = SEPARATOR.length;
|
|
|
|
/**
|
|
* Maximum depth of traversals before we consider the possibility of a bad ID.
|
|
*/
|
|
var MAX_TREE_DEPTH = 10000;
|
|
|
|
/**
|
|
* Creates a DOM ID prefix to use when mounting React components.
|
|
*
|
|
* @param {number} index A unique integer
|
|
* @return {string} React root ID.
|
|
* @internal
|
|
*/
|
|
function getReactRootIDString(index) {
|
|
return SEPARATOR + index.toString(36);
|
|
}
|
|
|
|
/**
|
|
* Checks if a character in the supplied ID is a separator or the end.
|
|
*
|
|
* @param {string} id A React DOM ID.
|
|
* @param {number} index Index of the character to check.
|
|
* @return {boolean} True if the character is a separator or end of the ID.
|
|
* @private
|
|
*/
|
|
function isBoundary(id, index) {
|
|
return id.charAt(index) === SEPARATOR || index === id.length;
|
|
}
|
|
|
|
/**
|
|
* Checks if the supplied string is a valid React DOM ID.
|
|
*
|
|
* @param {string} id A React DOM ID, maybe.
|
|
* @return {boolean} True if the string is a valid React DOM ID.
|
|
* @private
|
|
*/
|
|
function isValidID(id) {
|
|
return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR;
|
|
}
|
|
|
|
/**
|
|
* Checks if the first ID is an ancestor of or equal to the second ID.
|
|
*
|
|
* @param {string} ancestorID
|
|
* @param {string} descendantID
|
|
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
|
|
* @internal
|
|
*/
|
|
function isAncestorIDOf(ancestorID, descendantID) {
|
|
return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length);
|
|
}
|
|
|
|
/**
|
|
* Gets the parent ID of the supplied React DOM ID, `id`.
|
|
*
|
|
* @param {string} id ID of a component.
|
|
* @return {string} ID of the parent, or an empty string.
|
|
* @private
|
|
*/
|
|
function getParentID(id) {
|
|
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
|
|
}
|
|
|
|
/**
|
|
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
|
|
* supplied `destinationID`. If they are equal, the ID is returned.
|
|
*
|
|
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
|
|
* @param {string} destinationID ID of the destination node.
|
|
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
|
|
* @private
|
|
*/
|
|
function getNextDescendantID(ancestorID, destinationID) {
|
|
!(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined;
|
|
!isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined;
|
|
if (ancestorID === destinationID) {
|
|
return ancestorID;
|
|
}
|
|
// Skip over the ancestor and the immediate separator. Traverse until we hit
|
|
// another separator or we reach the end of `destinationID`.
|
|
var start = ancestorID.length + SEPARATOR_LENGTH;
|
|
var i;
|
|
for (i = start; i < destinationID.length; i++) {
|
|
if (isBoundary(destinationID, i)) {
|
|
break;
|
|
}
|
|
}
|
|
return destinationID.substr(0, i);
|
|
}
|
|
|
|
/**
|
|
* Gets the nearest common ancestor ID of two IDs.
|
|
*
|
|
* Using this ID scheme, the nearest common ancestor ID is the longest common
|
|
* prefix of the two IDs that immediately preceded a "marker" in both strings.
|
|
*
|
|
* @param {string} oneID
|
|
* @param {string} twoID
|
|
* @return {string} Nearest common ancestor ID, or the empty string if none.
|
|
* @private
|
|
*/
|
|
function getFirstCommonAncestorID(oneID, twoID) {
|
|
var minLength = Math.min(oneID.length, twoID.length);
|
|
if (minLength === 0) {
|
|
return '';
|
|
}
|
|
var lastCommonMarkerIndex = 0;
|
|
// Use `<=` to traverse until the "EOL" of the shorter string.
|
|
for (var i = 0; i <= minLength; i++) {
|
|
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
|
|
lastCommonMarkerIndex = i;
|
|
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
|
|
break;
|
|
}
|
|
}
|
|
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
|
|
!isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined;
|
|
return longestCommonID;
|
|
}
|
|
|
|
/**
|
|
* Traverses the parent path between two IDs (either up or down). The IDs must
|
|
* not be the same, and there must exist a parent path between them. If the
|
|
* callback returns `false`, traversal is stopped.
|
|
*
|
|
* @param {?string} start ID at which to start traversal.
|
|
* @param {?string} stop ID at which to end traversal.
|
|
* @param {function} cb Callback to invoke each ID with.
|
|
* @param {*} arg Argument to invoke the callback with.
|
|
* @param {?boolean} skipFirst Whether or not to skip the first node.
|
|
* @param {?boolean} skipLast Whether or not to skip the last node.
|
|
* @private
|
|
*/
|
|
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
|
|
start = start || '';
|
|
stop = stop || '';
|
|
!(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined;
|
|
var traverseUp = isAncestorIDOf(stop, start);
|
|
!(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined;
|
|
// Traverse from `start` to `stop` one depth at a time.
|
|
var depth = 0;
|
|
var traverse = traverseUp ? getParentID : getNextDescendantID;
|
|
for (var id = start;; /* until break */id = traverse(id, stop)) {
|
|
var ret;
|
|
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
|
|
ret = cb(id, traverseUp, arg);
|
|
}
|
|
if (ret === false || id === stop) {
|
|
// Only break //after// visiting `stop`.
|
|
break;
|
|
}
|
|
!(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Manages the IDs assigned to DOM representations of React components. This
|
|
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
|
|
* order to simulate events).
|
|
*
|
|
* @internal
|
|
*/
|
|
var ReactInstanceHandles = {
|
|
|
|
/**
|
|
* Constructs a React root ID
|
|
* @return {string} A React root ID.
|
|
*/
|
|
createReactRootID: function () {
|
|
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
|
|
},
|
|
|
|
/**
|
|
* Constructs a React ID by joining a root ID with a name.
|
|
*
|
|
* @param {string} rootID Root ID of a parent component.
|
|
* @param {string} name A component's name (as flattened children).
|
|
* @return {string} A React ID.
|
|
* @internal
|
|
*/
|
|
createReactID: function (rootID, name) {
|
|
return rootID + name;
|
|
},
|
|
|
|
/**
|
|
* Gets the DOM ID of the React component that is the root of the tree that
|
|
* contains the React component with the supplied DOM ID.
|
|
*
|
|
* @param {string} id DOM ID of a React component.
|
|
* @return {?string} DOM ID of the React component that is the root.
|
|
* @internal
|
|
*/
|
|
getReactRootIDFromNodeID: function (id) {
|
|
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
|
|
var index = id.indexOf(SEPARATOR, 1);
|
|
return index > -1 ? id.substr(0, index) : id;
|
|
}
|
|
return null;
|
|
},
|
|
|
|
/**
|
|
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
|
|
* should would receive a `mouseEnter` or `mouseLeave` event.
|
|
*
|
|
* NOTE: Does not invoke the callback on the nearest common ancestor because
|
|
* nothing "entered" or "left" that element.
|
|
*
|
|
* @param {string} leaveID ID being left.
|
|
* @param {string} enterID ID being entered.
|
|
* @param {function} cb Callback to invoke on each entered/left ID.
|
|
* @param {*} upArg Argument to invoke the callback with on left IDs.
|
|
* @param {*} downArg Argument to invoke the callback with on entered IDs.
|
|
* @internal
|
|
*/
|
|
traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) {
|
|
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
|
|
if (ancestorID !== leaveID) {
|
|
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
|
|
}
|
|
if (ancestorID !== enterID) {
|
|
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
|
|
*
|
|
* NOTE: This traversal happens on IDs without touching the DOM.
|
|
*
|
|
* @param {string} targetID ID of the target node.
|
|
* @param {function} cb Callback to invoke.
|
|
* @param {*} arg Argument to invoke the callback with.
|
|
* @internal
|
|
*/
|
|
traverseTwoPhase: function (targetID, cb, arg) {
|
|
if (targetID) {
|
|
traverseParentPath('', targetID, cb, arg, true, false);
|
|
traverseParentPath(targetID, '', cb, arg, false, true);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Same as `traverseTwoPhase` but skips the `targetID`.
|
|
*/
|
|
traverseTwoPhaseSkipTarget: function (targetID, cb, arg) {
|
|
if (targetID) {
|
|
traverseParentPath('', targetID, cb, arg, true, true);
|
|
traverseParentPath(targetID, '', cb, arg, true, true);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
|
|
* example, passing `.0.$row-0.1` would result in `cb` getting called
|
|
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
|
|
*
|
|
* NOTE: This traversal happens on IDs without touching the DOM.
|
|
*
|
|
* @param {string} targetID ID of the target node.
|
|
* @param {function} cb Callback to invoke.
|
|
* @param {*} arg Argument to invoke the callback with.
|
|
* @internal
|
|
*/
|
|
traverseAncestors: function (targetID, cb, arg) {
|
|
traverseParentPath('', targetID, cb, arg, true, false);
|
|
},
|
|
|
|
getFirstCommonAncestorID: getFirstCommonAncestorID,
|
|
|
|
/**
|
|
* Exposed for unit testing.
|
|
* @private
|
|
*/
|
|
_getNextDescendantID: getNextDescendantID,
|
|
|
|
isAncestorIDOf: isAncestorIDOf,
|
|
|
|
SEPARATOR: SEPARATOR
|
|
|
|
};
|
|
|
|
module.exports = ReactInstanceHandles;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 46 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactRootIndex
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactRootIndexInjection = {
|
|
/**
|
|
* @param {function} _createReactRootIndex
|
|
*/
|
|
injectCreateReactRootIndex: function (_createReactRootIndex) {
|
|
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
|
|
}
|
|
};
|
|
|
|
var ReactRootIndex = {
|
|
createReactRootIndex: null,
|
|
injection: ReactRootIndexInjection
|
|
};
|
|
|
|
module.exports = ReactRootIndex;
|
|
|
|
/***/ }),
|
|
/* 47 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactInstanceMap
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* `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.
|
|
*/
|
|
|
|
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
|
|
var ReactInstanceMap = {
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
remove: function (key) {
|
|
key._reactInternalInstance = undefined;
|
|
},
|
|
|
|
get: function (key) {
|
|
return key._reactInternalInstance;
|
|
},
|
|
|
|
has: function (key) {
|
|
return key._reactInternalInstance !== undefined;
|
|
},
|
|
|
|
set: function (key, value) {
|
|
key._reactInternalInstance = value;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactInstanceMap;
|
|
|
|
/***/ }),
|
|
/* 48 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactMarkupChecksum
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var adler32 = __webpack_require__(49);
|
|
|
|
var TAG_END = /\/?>/;
|
|
|
|
var ReactMarkupChecksum = {
|
|
CHECKSUM_ATTR_NAME: 'data-react-checksum',
|
|
|
|
/**
|
|
* @param {string} markup Markup string
|
|
* @return {string} Markup string with checksum attribute attached
|
|
*/
|
|
addChecksumToMarkup: function (markup) {
|
|
var checksum = adler32(markup);
|
|
|
|
// Add checksum (handle both parent tags and self-closing tags)
|
|
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
|
|
},
|
|
|
|
/**
|
|
* @param {string} markup to use
|
|
* @param {DOMElement} element root React element
|
|
* @returns {boolean} whether or not the markup is the same
|
|
*/
|
|
canReuseMarkup: function (markup, element) {
|
|
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
|
|
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
|
|
var markupChecksum = adler32(markup);
|
|
return markupChecksum === existingChecksum;
|
|
}
|
|
};
|
|
|
|
module.exports = ReactMarkupChecksum;
|
|
|
|
/***/ }),
|
|
/* 49 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule adler32
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var MOD = 65521;
|
|
|
|
// adler32 is not cryptographically strong, and is only used to sanity check that
|
|
// markup generated on the server matches the markup generated on the client.
|
|
// This implementation (a modified version of the SheetJS version) has been optimized
|
|
// for our use case, at the expense of conforming to the adler32 specification
|
|
// for non-ascii inputs.
|
|
function adler32(data) {
|
|
var a = 1;
|
|
var b = 0;
|
|
var i = 0;
|
|
var l = data.length;
|
|
var m = l & ~0x3;
|
|
while (i < m) {
|
|
for (; i < Math.min(i + 4096, m); i += 4) {
|
|
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
|
|
}
|
|
a %= MOD;
|
|
b %= MOD;
|
|
}
|
|
for (; i < l; i++) {
|
|
b += a += data.charCodeAt(i);
|
|
}
|
|
a %= MOD;
|
|
b %= MOD;
|
|
return a | b << 16;
|
|
}
|
|
|
|
module.exports = adler32;
|
|
|
|
/***/ }),
|
|
/* 50 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactReconciler
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactRef = __webpack_require__(51);
|
|
|
|
/**
|
|
* Helper to call ReactRef.attachRefs with this composite component, split out
|
|
* to avoid allocations in the transaction mount-ready queue.
|
|
*/
|
|
function attachRefs() {
|
|
ReactRef.attachRefs(this, this._currentElement);
|
|
}
|
|
|
|
var ReactReconciler = {
|
|
|
|
/**
|
|
* Initializes the component, renders markup, and registers event listeners.
|
|
*
|
|
* @param {ReactComponent} internalInstance
|
|
* @param {string} rootID DOM ID of the root node.
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @return {?string} Rendered markup to be inserted into the DOM.
|
|
* @final
|
|
* @internal
|
|
*/
|
|
mountComponent: function (internalInstance, rootID, transaction, context) {
|
|
var markup = internalInstance.mountComponent(rootID, transaction, context);
|
|
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
|
|
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
|
|
}
|
|
return markup;
|
|
},
|
|
|
|
/**
|
|
* Releases any resources allocated by `mountComponent`.
|
|
*
|
|
* @final
|
|
* @internal
|
|
*/
|
|
unmountComponent: function (internalInstance) {
|
|
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
|
|
internalInstance.unmountComponent();
|
|
},
|
|
|
|
/**
|
|
* Update a component using a new element.
|
|
*
|
|
* @param {ReactComponent} internalInstance
|
|
* @param {ReactElement} nextElement
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {object} context
|
|
* @internal
|
|
*/
|
|
receiveComponent: function (internalInstance, nextElement, transaction, context) {
|
|
var prevElement = internalInstance._currentElement;
|
|
|
|
if (nextElement === prevElement && context === internalInstance._context) {
|
|
// Since elements are immutable after the owner is rendered,
|
|
// we can do a cheap identity compare here to determine if this is a
|
|
// superfluous reconcile. It's possible for state to be mutable but such
|
|
// change should trigger an update of the owner which would recreate
|
|
// the element. We explicitly check for the existence of an owner since
|
|
// it's possible for an element created outside a composite to be
|
|
// deeply mutated and reused.
|
|
|
|
// TODO: Bailing out early is just a perf optimization right?
|
|
// TODO: Removing the return statement should affect correctness?
|
|
return;
|
|
}
|
|
|
|
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
|
|
|
|
if (refsChanged) {
|
|
ReactRef.detachRefs(internalInstance, prevElement);
|
|
}
|
|
|
|
internalInstance.receiveComponent(nextElement, transaction, context);
|
|
|
|
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
|
|
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Flush any dirty changes in a component.
|
|
*
|
|
* @param {ReactComponent} internalInstance
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
*/
|
|
performUpdateIfNecessary: function (internalInstance, transaction) {
|
|
internalInstance.performUpdateIfNecessary(transaction);
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactReconciler;
|
|
|
|
/***/ }),
|
|
/* 51 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactRef
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactOwner = __webpack_require__(52);
|
|
|
|
var ReactRef = {};
|
|
|
|
function attachRef(ref, component, owner) {
|
|
if (typeof ref === 'function') {
|
|
ref(component.getPublicInstance());
|
|
} else {
|
|
// Legacy ref
|
|
ReactOwner.addComponentAsRefTo(component, ref, owner);
|
|
}
|
|
}
|
|
|
|
function detachRef(ref, component, owner) {
|
|
if (typeof ref === 'function') {
|
|
ref(null);
|
|
} else {
|
|
// Legacy ref
|
|
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
|
|
}
|
|
}
|
|
|
|
ReactRef.attachRefs = function (instance, element) {
|
|
if (element === null || element === false) {
|
|
return;
|
|
}
|
|
var ref = element.ref;
|
|
if (ref != null) {
|
|
attachRef(ref, instance, element._owner);
|
|
}
|
|
};
|
|
|
|
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
|
|
// If either the owner or a `ref` has changed, make sure the newest owner
|
|
// has stored a reference to `this`, and the previous owner (if different)
|
|
// has forgotten the reference to `this`. We use the element instead
|
|
// of the public this.props because the post processing cannot determine
|
|
// a ref. The ref conceptually lives on the element.
|
|
|
|
// TODO: Should this even be possible? The owner cannot change because
|
|
// it's forbidden by shouldUpdateReactComponent. The ref can change
|
|
// if you swap the keys of but not the refs. Reconsider where this check
|
|
// is made. It probably belongs where the key checking and
|
|
// instantiateReactComponent is done.
|
|
|
|
var prevEmpty = prevElement === null || prevElement === false;
|
|
var nextEmpty = nextElement === null || nextElement === false;
|
|
|
|
return(
|
|
// This has a few false positives w/r/t empty components.
|
|
prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref
|
|
);
|
|
};
|
|
|
|
ReactRef.detachRefs = function (instance, element) {
|
|
if (element === null || element === false) {
|
|
return;
|
|
}
|
|
var ref = element.ref;
|
|
if (ref != null) {
|
|
detachRef(ref, instance, element._owner);
|
|
}
|
|
};
|
|
|
|
module.exports = ReactRef;
|
|
|
|
/***/ }),
|
|
/* 52 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactOwner
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* ReactOwners are capable of storing references to owned components.
|
|
*
|
|
* All components are capable of //being// referenced by owner components, but
|
|
* only ReactOwner components are capable of //referencing// owned components.
|
|
* The named reference is known as a "ref".
|
|
*
|
|
* Refs are available when mounted and updated during reconciliation.
|
|
*
|
|
* var MyComponent = React.createClass({
|
|
* render: function() {
|
|
* return (
|
|
* <div onClick={this.handleClick}>
|
|
* <CustomComponent ref="custom" />
|
|
* </div>
|
|
* );
|
|
* },
|
|
* handleClick: function() {
|
|
* this.refs.custom.handleClick();
|
|
* },
|
|
* componentDidMount: function() {
|
|
* this.refs.custom.initialize();
|
|
* }
|
|
* });
|
|
*
|
|
* Refs should rarely be used. When refs are used, they should only be done to
|
|
* control data that is not handled by React's data flow.
|
|
*
|
|
* @class ReactOwner
|
|
*/
|
|
var ReactOwner = {
|
|
|
|
/**
|
|
* @param {?object} object
|
|
* @return {boolean} True if `object` is a valid owner.
|
|
* @final
|
|
*/
|
|
isValidOwner: function (object) {
|
|
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
|
|
},
|
|
|
|
/**
|
|
* Adds a component by ref to an owner component.
|
|
*
|
|
* @param {ReactComponent} component Component to reference.
|
|
* @param {string} ref Name by which to refer to the component.
|
|
* @param {ReactOwner} owner Component on which to record the ref.
|
|
* @final
|
|
* @internal
|
|
*/
|
|
addComponentAsRefTo: function (component, ref, owner) {
|
|
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
|
|
owner.attachRef(ref, component);
|
|
},
|
|
|
|
/**
|
|
* Removes a component by ref from an owner component.
|
|
*
|
|
* @param {ReactComponent} component Component to dereference.
|
|
* @param {string} ref Name of the ref to remove.
|
|
* @param {ReactOwner} owner Component on which the ref is recorded.
|
|
* @final
|
|
* @internal
|
|
*/
|
|
removeComponentAsRefFrom: function (component, ref, owner) {
|
|
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
|
|
// Check that `component` is still the current ref because we do not want to
|
|
// detach the ref if another component stole it.
|
|
if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
|
|
owner.detachRef(ref);
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactOwner;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 53 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactUpdateQueue
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactInstanceMap = __webpack_require__(47);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
function enqueueUpdate(internalInstance) {
|
|
ReactUpdates.enqueueUpdate(internalInstance);
|
|
}
|
|
|
|
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
|
|
var internalInstance = ReactInstanceMap.get(publicInstance);
|
|
if (!internalInstance) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// Only warn when we have a callerName. Otherwise we should be silent.
|
|
// We're probably calling from enqueueCallback. We don't want to warn
|
|
// there because we already warned for the corresponding lifecycle method.
|
|
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined;
|
|
}
|
|
|
|
return internalInstance;
|
|
}
|
|
|
|
/**
|
|
* ReactUpdateQueue allows for state updates to be scheduled into a later
|
|
* reconciliation step.
|
|
*/
|
|
var ReactUpdateQueue = {
|
|
|
|
/**
|
|
* Checks whether or not this composite component is mounted.
|
|
* @param {ReactClass} publicInstance The instance we want to test.
|
|
* @return {boolean} True if mounted, false otherwise.
|
|
* @protected
|
|
* @final
|
|
*/
|
|
isMounted: function (publicInstance) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var owner = ReactCurrentOwner.current;
|
|
if (owner !== null) {
|
|
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%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.', owner.getName() || 'A component') : undefined;
|
|
owner._warnedAboutRefsInRender = true;
|
|
}
|
|
}
|
|
var internalInstance = ReactInstanceMap.get(publicInstance);
|
|
if (internalInstance) {
|
|
// During componentWillMount and render this will still be null but after
|
|
// that will always render to something. At least for now. So we can use
|
|
// this hack.
|
|
return !!internalInstance._renderedComponent;
|
|
} else {
|
|
return false;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Enqueue a callback that will be executed after all the pending updates
|
|
* have processed.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance to use as `this` context.
|
|
* @param {?function} callback Called after state is updated.
|
|
* @internal
|
|
*/
|
|
enqueueCallback: function (publicInstance, callback) {
|
|
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
|
|
|
|
// Previously we would throw an error if we didn't have an internal
|
|
// instance. Since we want to make it a no-op instead, we mirror the same
|
|
// behavior we have in other enqueue* methods.
|
|
// We also need to ignore callbacks in componentWillMount. See
|
|
// enqueueUpdates.
|
|
if (!internalInstance) {
|
|
return null;
|
|
}
|
|
|
|
if (internalInstance._pendingCallbacks) {
|
|
internalInstance._pendingCallbacks.push(callback);
|
|
} else {
|
|
internalInstance._pendingCallbacks = [callback];
|
|
}
|
|
// TODO: The callback here is ignored when setState is called from
|
|
// componentWillMount. Either fix it or disallow doing so completely in
|
|
// favor of getInitialState. Alternatively, we can disallow
|
|
// componentWillMount during server-side rendering.
|
|
enqueueUpdate(internalInstance);
|
|
},
|
|
|
|
enqueueCallbackInternal: function (internalInstance, callback) {
|
|
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
|
|
if (internalInstance._pendingCallbacks) {
|
|
internalInstance._pendingCallbacks.push(callback);
|
|
} else {
|
|
internalInstance._pendingCallbacks = [callback];
|
|
}
|
|
enqueueUpdate(internalInstance);
|
|
},
|
|
|
|
/**
|
|
* Forces an update. This should only be invoked when it is known with
|
|
* certainty that we are **not** in a DOM transaction.
|
|
*
|
|
* You may want to call this when you know that some deeper aspect of the
|
|
* component's state has changed but `setState` was not called.
|
|
*
|
|
* This will not invoke `shouldComponentUpdate`, but it will invoke
|
|
* `componentWillUpdate` and `componentDidUpdate`.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @internal
|
|
*/
|
|
enqueueForceUpdate: function (publicInstance) {
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
|
|
|
|
if (!internalInstance) {
|
|
return;
|
|
}
|
|
|
|
internalInstance._pendingForceUpdate = true;
|
|
|
|
enqueueUpdate(internalInstance);
|
|
},
|
|
|
|
/**
|
|
* Replaces all of the state. Always use this or `setState` to mutate state.
|
|
* You should treat `this.state` as immutable.
|
|
*
|
|
* There is no guarantee that `this.state` will be immediately updated, so
|
|
* accessing `this.state` after calling this method may return the old value.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} completeState Next state.
|
|
* @internal
|
|
*/
|
|
enqueueReplaceState: function (publicInstance, completeState) {
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
|
|
|
|
if (!internalInstance) {
|
|
return;
|
|
}
|
|
|
|
internalInstance._pendingStateQueue = [completeState];
|
|
internalInstance._pendingReplaceState = true;
|
|
|
|
enqueueUpdate(internalInstance);
|
|
},
|
|
|
|
/**
|
|
* Sets a subset of the state. This only exists because _pendingState is
|
|
* internal. This provides a merging strategy that is not available to deep
|
|
* properties which is confusing. TODO: Expose pendingState or don't use it
|
|
* during the merge.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} partialState Next partial state to be merged with state.
|
|
* @internal
|
|
*/
|
|
enqueueSetState: function (publicInstance, partialState) {
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
|
|
|
|
if (!internalInstance) {
|
|
return;
|
|
}
|
|
|
|
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
|
|
queue.push(partialState);
|
|
|
|
enqueueUpdate(internalInstance);
|
|
},
|
|
|
|
/**
|
|
* Sets a subset of the props.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} partialProps Subset of the next props.
|
|
* @internal
|
|
*/
|
|
enqueueSetProps: function (publicInstance, partialProps) {
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps');
|
|
if (!internalInstance) {
|
|
return;
|
|
}
|
|
ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
|
|
},
|
|
|
|
enqueueSetPropsInternal: function (internalInstance, partialProps) {
|
|
var topLevelWrapper = internalInstance._topLevelWrapper;
|
|
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
|
|
|
|
// Merge with the pending element if it exists, otherwise with existing
|
|
// element props.
|
|
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
|
|
var element = wrapElement.props;
|
|
var props = assign({}, element.props, partialProps);
|
|
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
|
|
|
|
enqueueUpdate(topLevelWrapper);
|
|
},
|
|
|
|
/**
|
|
* Replaces all of the props.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} props New props.
|
|
* @internal
|
|
*/
|
|
enqueueReplaceProps: function (publicInstance, props) {
|
|
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps');
|
|
if (!internalInstance) {
|
|
return;
|
|
}
|
|
ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
|
|
},
|
|
|
|
enqueueReplacePropsInternal: function (internalInstance, props) {
|
|
var topLevelWrapper = internalInstance._topLevelWrapper;
|
|
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
|
|
|
|
// Merge with the pending element if it exists, otherwise with existing
|
|
// element props.
|
|
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
|
|
var element = wrapElement.props;
|
|
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
|
|
|
|
enqueueUpdate(topLevelWrapper);
|
|
},
|
|
|
|
enqueueElementInternal: function (internalInstance, newElement) {
|
|
internalInstance._pendingElement = newElement;
|
|
enqueueUpdate(internalInstance);
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactUpdateQueue;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 54 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactUpdates
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var CallbackQueue = __webpack_require__(55);
|
|
var PooledClass = __webpack_require__(56);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
var Transaction = __webpack_require__(57);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var dirtyComponents = [];
|
|
var asapCallbackQueue = CallbackQueue.getPooled();
|
|
var asapEnqueued = false;
|
|
|
|
var batchingStrategy = null;
|
|
|
|
function ensureInjected() {
|
|
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
|
|
}
|
|
|
|
var NESTED_UPDATES = {
|
|
initialize: function () {
|
|
this.dirtyComponentsLength = dirtyComponents.length;
|
|
},
|
|
close: function () {
|
|
if (this.dirtyComponentsLength !== dirtyComponents.length) {
|
|
// Additional updates were enqueued by componentDidUpdate handlers or
|
|
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
|
|
// these new updates so that if A's componentDidUpdate calls setState on
|
|
// B, B will update before the callback A's updater provided when calling
|
|
// setState.
|
|
dirtyComponents.splice(0, this.dirtyComponentsLength);
|
|
flushBatchedUpdates();
|
|
} else {
|
|
dirtyComponents.length = 0;
|
|
}
|
|
}
|
|
};
|
|
|
|
var UPDATE_QUEUEING = {
|
|
initialize: function () {
|
|
this.callbackQueue.reset();
|
|
},
|
|
close: function () {
|
|
this.callbackQueue.notifyAll();
|
|
}
|
|
};
|
|
|
|
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
|
|
|
|
function ReactUpdatesFlushTransaction() {
|
|
this.reinitializeTransaction();
|
|
this.dirtyComponentsLength = null;
|
|
this.callbackQueue = CallbackQueue.getPooled();
|
|
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false);
|
|
}
|
|
|
|
assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
|
|
getTransactionWrappers: function () {
|
|
return TRANSACTION_WRAPPERS;
|
|
},
|
|
|
|
destructor: function () {
|
|
this.dirtyComponentsLength = null;
|
|
CallbackQueue.release(this.callbackQueue);
|
|
this.callbackQueue = null;
|
|
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
|
|
this.reconcileTransaction = null;
|
|
},
|
|
|
|
perform: function (method, scope, a) {
|
|
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
|
|
// with this transaction's wrappers around it.
|
|
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
|
|
}
|
|
});
|
|
|
|
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
|
|
|
|
function batchedUpdates(callback, a, b, c, d, e) {
|
|
ensureInjected();
|
|
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
|
|
}
|
|
|
|
/**
|
|
* Array comparator for ReactComponents by mount ordering.
|
|
*
|
|
* @param {ReactComponent} c1 first component you're comparing
|
|
* @param {ReactComponent} c2 second component you're comparing
|
|
* @return {number} Return value usable by Array.prototype.sort().
|
|
*/
|
|
function mountOrderComparator(c1, c2) {
|
|
return c1._mountOrder - c2._mountOrder;
|
|
}
|
|
|
|
function runBatchedUpdates(transaction) {
|
|
var len = transaction.dirtyComponentsLength;
|
|
!(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
|
|
|
|
// Since reconciling a component higher in the owner hierarchy usually (not
|
|
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
|
|
// them before their children by sorting the array.
|
|
dirtyComponents.sort(mountOrderComparator);
|
|
|
|
for (var i = 0; i < len; i++) {
|
|
// If a component is unmounted before pending changes apply, it will still
|
|
// be here, but we assume that it has cleared its _pendingCallbacks and
|
|
// that performUpdateIfNecessary is a noop.
|
|
var component = dirtyComponents[i];
|
|
|
|
// If performUpdateIfNecessary happens to enqueue any new updates, we
|
|
// shouldn't execute the callbacks until the next render happens, so
|
|
// stash the callbacks first
|
|
var callbacks = component._pendingCallbacks;
|
|
component._pendingCallbacks = null;
|
|
|
|
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
|
|
|
|
if (callbacks) {
|
|
for (var j = 0; j < callbacks.length; j++) {
|
|
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var flushBatchedUpdates = function () {
|
|
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
|
|
// array and perform any updates enqueued by mount-ready handlers (i.e.,
|
|
// componentDidUpdate) but we need to check here too in order to catch
|
|
// updates enqueued by setState callbacks and asap calls.
|
|
while (dirtyComponents.length || asapEnqueued) {
|
|
if (dirtyComponents.length) {
|
|
var transaction = ReactUpdatesFlushTransaction.getPooled();
|
|
transaction.perform(runBatchedUpdates, null, transaction);
|
|
ReactUpdatesFlushTransaction.release(transaction);
|
|
}
|
|
|
|
if (asapEnqueued) {
|
|
asapEnqueued = false;
|
|
var queue = asapCallbackQueue;
|
|
asapCallbackQueue = CallbackQueue.getPooled();
|
|
queue.notifyAll();
|
|
CallbackQueue.release(queue);
|
|
}
|
|
}
|
|
};
|
|
flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
|
|
|
|
/**
|
|
* Mark a component as needing a rerender, adding an optional callback to a
|
|
* list of functions which will be executed once the rerender occurs.
|
|
*/
|
|
function enqueueUpdate(component) {
|
|
ensureInjected();
|
|
|
|
// Various parts of our code (such as ReactCompositeComponent's
|
|
// _renderValidatedComponent) assume that calls to render aren't nested;
|
|
// verify that that's the case. (This is called by each top-level update
|
|
// function, like setProps, setState, forceUpdate, etc.; creation and
|
|
// destruction of top-level components is guarded in ReactMount.)
|
|
|
|
if (!batchingStrategy.isBatchingUpdates) {
|
|
batchingStrategy.batchedUpdates(enqueueUpdate, component);
|
|
return;
|
|
}
|
|
|
|
dirtyComponents.push(component);
|
|
}
|
|
|
|
/**
|
|
* Enqueue a callback to be run at the end of the current batching cycle. Throws
|
|
* if no updates are currently being performed.
|
|
*/
|
|
function asap(callback, context) {
|
|
!batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
|
|
asapCallbackQueue.enqueue(callback, context);
|
|
asapEnqueued = true;
|
|
}
|
|
|
|
var ReactUpdatesInjection = {
|
|
injectReconcileTransaction: function (ReconcileTransaction) {
|
|
!ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
|
|
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
|
|
},
|
|
|
|
injectBatchingStrategy: function (_batchingStrategy) {
|
|
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
|
|
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
|
|
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
|
|
batchingStrategy = _batchingStrategy;
|
|
}
|
|
};
|
|
|
|
var ReactUpdates = {
|
|
/**
|
|
* React references `ReactReconcileTransaction` using this property in order
|
|
* to allow dependency injection.
|
|
*
|
|
* @internal
|
|
*/
|
|
ReactReconcileTransaction: null,
|
|
|
|
batchedUpdates: batchedUpdates,
|
|
enqueueUpdate: enqueueUpdate,
|
|
flushBatchedUpdates: flushBatchedUpdates,
|
|
injection: ReactUpdatesInjection,
|
|
asap: asap
|
|
};
|
|
|
|
module.exports = ReactUpdates;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 55 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule CallbackQueue
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var PooledClass = __webpack_require__(56);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* A specialized pseudo-event module to help keep track of components waiting to
|
|
* be notified when their DOM representations are available for use.
|
|
*
|
|
* This implements `PooledClass`, so you should never need to instantiate this.
|
|
* Instead, use `CallbackQueue.getPooled()`.
|
|
*
|
|
* @class ReactMountReady
|
|
* @implements PooledClass
|
|
* @internal
|
|
*/
|
|
function CallbackQueue() {
|
|
this._callbacks = null;
|
|
this._contexts = null;
|
|
}
|
|
|
|
assign(CallbackQueue.prototype, {
|
|
|
|
/**
|
|
* Enqueues a callback to be invoked when `notifyAll` is invoked.
|
|
*
|
|
* @param {function} callback Invoked when `notifyAll` is invoked.
|
|
* @param {?object} context Context to call `callback` with.
|
|
* @internal
|
|
*/
|
|
enqueue: function (callback, context) {
|
|
this._callbacks = this._callbacks || [];
|
|
this._contexts = this._contexts || [];
|
|
this._callbacks.push(callback);
|
|
this._contexts.push(context);
|
|
},
|
|
|
|
/**
|
|
* Invokes all enqueued callbacks and clears the queue. This is invoked after
|
|
* the DOM representation of a component has been created or updated.
|
|
*
|
|
* @internal
|
|
*/
|
|
notifyAll: function () {
|
|
var callbacks = this._callbacks;
|
|
var contexts = this._contexts;
|
|
if (callbacks) {
|
|
!(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined;
|
|
this._callbacks = null;
|
|
this._contexts = null;
|
|
for (var i = 0; i < callbacks.length; i++) {
|
|
callbacks[i].call(contexts[i]);
|
|
}
|
|
callbacks.length = 0;
|
|
contexts.length = 0;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Resets the internal queue.
|
|
*
|
|
* @internal
|
|
*/
|
|
reset: function () {
|
|
this._callbacks = null;
|
|
this._contexts = null;
|
|
},
|
|
|
|
/**
|
|
* `PooledClass` looks for this.
|
|
*/
|
|
destructor: function () {
|
|
this.reset();
|
|
}
|
|
|
|
});
|
|
|
|
PooledClass.addPoolingTo(CallbackQueue);
|
|
|
|
module.exports = CallbackQueue;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 56 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule PooledClass
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Static poolers. Several custom versions for each potential number of
|
|
* arguments. A completely generic pooler is easy to implement, but would
|
|
* require accessing the `arguments` object. In each of these, `this` refers to
|
|
* the Class itself, not an instance. If any others are needed, simply add them
|
|
* here, or in their own files.
|
|
*/
|
|
var oneArgumentPooler = function (copyFieldsFrom) {
|
|
var Klass = this;
|
|
if (Klass.instancePool.length) {
|
|
var instance = Klass.instancePool.pop();
|
|
Klass.call(instance, copyFieldsFrom);
|
|
return instance;
|
|
} else {
|
|
return new Klass(copyFieldsFrom);
|
|
}
|
|
};
|
|
|
|
var twoArgumentPooler = function (a1, a2) {
|
|
var Klass = this;
|
|
if (Klass.instancePool.length) {
|
|
var instance = Klass.instancePool.pop();
|
|
Klass.call(instance, a1, a2);
|
|
return instance;
|
|
} else {
|
|
return new Klass(a1, a2);
|
|
}
|
|
};
|
|
|
|
var threeArgumentPooler = function (a1, a2, a3) {
|
|
var Klass = this;
|
|
if (Klass.instancePool.length) {
|
|
var instance = Klass.instancePool.pop();
|
|
Klass.call(instance, a1, a2, a3);
|
|
return instance;
|
|
} else {
|
|
return new Klass(a1, a2, a3);
|
|
}
|
|
};
|
|
|
|
var fourArgumentPooler = function (a1, a2, a3, a4) {
|
|
var Klass = this;
|
|
if (Klass.instancePool.length) {
|
|
var instance = Klass.instancePool.pop();
|
|
Klass.call(instance, a1, a2, a3, a4);
|
|
return instance;
|
|
} else {
|
|
return new Klass(a1, a2, a3, a4);
|
|
}
|
|
};
|
|
|
|
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
|
|
var Klass = this;
|
|
if (Klass.instancePool.length) {
|
|
var instance = Klass.instancePool.pop();
|
|
Klass.call(instance, a1, a2, a3, a4, a5);
|
|
return instance;
|
|
} else {
|
|
return new Klass(a1, a2, a3, a4, a5);
|
|
}
|
|
};
|
|
|
|
var standardReleaser = function (instance) {
|
|
var Klass = this;
|
|
!(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined;
|
|
instance.destructor();
|
|
if (Klass.instancePool.length < Klass.poolSize) {
|
|
Klass.instancePool.push(instance);
|
|
}
|
|
};
|
|
|
|
var DEFAULT_POOL_SIZE = 10;
|
|
var DEFAULT_POOLER = oneArgumentPooler;
|
|
|
|
/**
|
|
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
|
|
* itself (statically) not adding any prototypical fields. Any CopyConstructor
|
|
* you give this may have a `poolSize` property, and will look for a
|
|
* prototypical `destructor` on instances (optional).
|
|
*
|
|
* @param {Function} CopyConstructor Constructor that can be used to reset.
|
|
* @param {Function} pooler Customizable pooler.
|
|
*/
|
|
var addPoolingTo = function (CopyConstructor, pooler) {
|
|
var NewKlass = CopyConstructor;
|
|
NewKlass.instancePool = [];
|
|
NewKlass.getPooled = pooler || DEFAULT_POOLER;
|
|
if (!NewKlass.poolSize) {
|
|
NewKlass.poolSize = DEFAULT_POOL_SIZE;
|
|
}
|
|
NewKlass.release = standardReleaser;
|
|
return NewKlass;
|
|
};
|
|
|
|
var PooledClass = {
|
|
addPoolingTo: addPoolingTo,
|
|
oneArgumentPooler: oneArgumentPooler,
|
|
twoArgumentPooler: twoArgumentPooler,
|
|
threeArgumentPooler: threeArgumentPooler,
|
|
fourArgumentPooler: fourArgumentPooler,
|
|
fiveArgumentPooler: fiveArgumentPooler
|
|
};
|
|
|
|
module.exports = PooledClass;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 57 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule Transaction
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* `Transaction` creates a black box that is able to wrap any method such that
|
|
* certain invariants are maintained before and after the method is invoked
|
|
* (Even if an exception is thrown while invoking the wrapped method). Whoever
|
|
* instantiates a transaction can provide enforcers of the invariants at
|
|
* creation time. The `Transaction` class itself will supply one additional
|
|
* automatic invariant for you - the invariant that any transaction instance
|
|
* should not be run while it is already being run. You would typically create a
|
|
* single instance of a `Transaction` for reuse multiple times, that potentially
|
|
* is used to wrap several different methods. Wrappers are extremely simple -
|
|
* they only require implementing two methods.
|
|
*
|
|
* <pre>
|
|
* wrappers (injected at creation time)
|
|
* + +
|
|
* | |
|
|
* +-----------------|--------|--------------+
|
|
* | v | |
|
|
* | +---------------+ | |
|
|
* | +--| wrapper1 |---|----+ |
|
|
* | | +---------------+ v | |
|
|
* | | +-------------+ | |
|
|
* | | +----| wrapper2 |--------+ |
|
|
* | | | +-------------+ | | |
|
|
* | | | | | |
|
|
* | v v v v | wrapper
|
|
* | +---+ +---+ +---------+ +---+ +---+ | invariants
|
|
* perform(anyMethod) | | | | | | | | | | | | maintained
|
|
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
|
|
* | | | | | | | | | | | |
|
|
* | | | | | | | | | | | |
|
|
* | | | | | | | | | | | |
|
|
* | +---+ +---+ +---------+ +---+ +---+ |
|
|
* | initialize close |
|
|
* +-----------------------------------------+
|
|
* </pre>
|
|
*
|
|
* Use cases:
|
|
* - Preserving the input selection ranges before/after reconciliation.
|
|
* Restoring selection even in the event of an unexpected error.
|
|
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
|
|
* while guaranteeing that afterwards, the event system is reactivated.
|
|
* - Flushing a queue of collected DOM mutations to the main UI thread after a
|
|
* reconciliation takes place in a worker thread.
|
|
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
|
|
* content.
|
|
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
|
|
* to preserve the `scrollTop` (an automatic scroll aware DOM).
|
|
* - (Future use case): Layout calculations before and after DOM updates.
|
|
*
|
|
* Transactional plugin API:
|
|
* - A module that has an `initialize` method that returns any precomputation.
|
|
* - and a `close` method that accepts the precomputation. `close` is invoked
|
|
* when the wrapped process is completed, or has failed.
|
|
*
|
|
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
|
|
* that implement `initialize` and `close`.
|
|
* @return {Transaction} Single transaction for reuse in thread.
|
|
*
|
|
* @class Transaction
|
|
*/
|
|
var Mixin = {
|
|
/**
|
|
* Sets up this instance so that it is prepared for collecting metrics. Does
|
|
* so such that this setup method may be used on an instance that is already
|
|
* initialized, in a way that does not consume additional memory upon reuse.
|
|
* That can be useful if you decide to make your subclass of this mixin a
|
|
* "PooledClass".
|
|
*/
|
|
reinitializeTransaction: function () {
|
|
this.transactionWrappers = this.getTransactionWrappers();
|
|
if (this.wrapperInitData) {
|
|
this.wrapperInitData.length = 0;
|
|
} else {
|
|
this.wrapperInitData = [];
|
|
}
|
|
this._isInTransaction = false;
|
|
},
|
|
|
|
_isInTransaction: false,
|
|
|
|
/**
|
|
* @abstract
|
|
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
|
|
*/
|
|
getTransactionWrappers: null,
|
|
|
|
isInTransaction: function () {
|
|
return !!this._isInTransaction;
|
|
},
|
|
|
|
/**
|
|
* Executes the function within a safety window. Use this for the top level
|
|
* methods that result in large amounts of computation/mutations that would
|
|
* need to be safety checked. The optional arguments helps prevent the need
|
|
* to bind in many cases.
|
|
*
|
|
* @param {function} method Member of scope to call.
|
|
* @param {Object} scope Scope to invoke from.
|
|
* @param {Object?=} a Argument to pass to the method.
|
|
* @param {Object?=} b Argument to pass to the method.
|
|
* @param {Object?=} c Argument to pass to the method.
|
|
* @param {Object?=} d Argument to pass to the method.
|
|
* @param {Object?=} e Argument to pass to the method.
|
|
* @param {Object?=} f Argument to pass to the method.
|
|
*
|
|
* @return {*} Return value from `method`.
|
|
*/
|
|
perform: function (method, scope, a, b, c, d, e, f) {
|
|
!!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined;
|
|
var errorThrown;
|
|
var ret;
|
|
try {
|
|
this._isInTransaction = true;
|
|
// Catching errors makes debugging more difficult, so we start with
|
|
// errorThrown set to true before setting it to false after calling
|
|
// close -- if it's still set to true in the finally block, it means
|
|
// one of these calls threw.
|
|
errorThrown = true;
|
|
this.initializeAll(0);
|
|
ret = method.call(scope, a, b, c, d, e, f);
|
|
errorThrown = false;
|
|
} finally {
|
|
try {
|
|
if (errorThrown) {
|
|
// If `method` throws, prefer to show that stack trace over any thrown
|
|
// by invoking `closeAll`.
|
|
try {
|
|
this.closeAll(0);
|
|
} catch (err) {}
|
|
} else {
|
|
// Since `method` didn't throw, we don't want to silence the exception
|
|
// here.
|
|
this.closeAll(0);
|
|
}
|
|
} finally {
|
|
this._isInTransaction = false;
|
|
}
|
|
}
|
|
return ret;
|
|
},
|
|
|
|
initializeAll: function (startIndex) {
|
|
var transactionWrappers = this.transactionWrappers;
|
|
for (var i = startIndex; i < transactionWrappers.length; i++) {
|
|
var wrapper = transactionWrappers[i];
|
|
try {
|
|
// Catching errors makes debugging more difficult, so we start with the
|
|
// OBSERVED_ERROR state before overwriting it with the real return value
|
|
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
|
|
// block, it means wrapper.initialize threw.
|
|
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
|
|
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
|
|
} finally {
|
|
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
|
|
// The initializer for wrapper i threw an error; initialize the
|
|
// remaining wrappers but silence any exceptions from them to ensure
|
|
// that the first error is the one to bubble up.
|
|
try {
|
|
this.initializeAll(i + 1);
|
|
} catch (err) {}
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
|
|
* them the respective return values of `this.transactionWrappers.init[i]`
|
|
* (`close`rs that correspond to initializers that failed will not be
|
|
* invoked).
|
|
*/
|
|
closeAll: function (startIndex) {
|
|
!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined;
|
|
var transactionWrappers = this.transactionWrappers;
|
|
for (var i = startIndex; i < transactionWrappers.length; i++) {
|
|
var wrapper = transactionWrappers[i];
|
|
var initData = this.wrapperInitData[i];
|
|
var errorThrown;
|
|
try {
|
|
// Catching errors makes debugging more difficult, so we start with
|
|
// errorThrown set to true before setting it to false after calling
|
|
// close -- if it's still set to true in the finally block, it means
|
|
// wrapper.close threw.
|
|
errorThrown = true;
|
|
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
|
|
wrapper.close.call(this, initData);
|
|
}
|
|
errorThrown = false;
|
|
} finally {
|
|
if (errorThrown) {
|
|
// The closer for wrapper i threw an error; close the remaining
|
|
// wrappers but silence any exceptions from them to ensure that the
|
|
// first error is the one to bubble up.
|
|
try {
|
|
this.closeAll(i + 1);
|
|
} catch (e) {}
|
|
}
|
|
}
|
|
}
|
|
this.wrapperInitData.length = 0;
|
|
}
|
|
};
|
|
|
|
var Transaction = {
|
|
|
|
Mixin: Mixin,
|
|
|
|
/**
|
|
* Token to look for to determine if an error occurred.
|
|
*/
|
|
OBSERVED_ERROR: {}
|
|
|
|
};
|
|
|
|
module.exports = Transaction;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 58 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule emptyObject
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var emptyObject = {};
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
Object.freeze(emptyObject);
|
|
}
|
|
|
|
module.exports = emptyObject;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 59 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule containsNode
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var isTextNode = __webpack_require__(60);
|
|
|
|
/*eslint-disable no-bitwise */
|
|
|
|
/**
|
|
* Checks if a given DOM node contains or is another DOM node.
|
|
*
|
|
* @param {?DOMNode} outerNode Outer DOM node.
|
|
* @param {?DOMNode} innerNode Inner DOM node.
|
|
* @return {boolean} True if `outerNode` contains or is `innerNode`.
|
|
*/
|
|
function containsNode(_x, _x2) {
|
|
var _again = true;
|
|
|
|
_function: while (_again) {
|
|
var outerNode = _x,
|
|
innerNode = _x2;
|
|
_again = false;
|
|
|
|
if (!outerNode || !innerNode) {
|
|
return false;
|
|
} else if (outerNode === innerNode) {
|
|
return true;
|
|
} else if (isTextNode(outerNode)) {
|
|
return false;
|
|
} else if (isTextNode(innerNode)) {
|
|
_x = outerNode;
|
|
_x2 = innerNode.parentNode;
|
|
_again = true;
|
|
continue _function;
|
|
} else if (outerNode.contains) {
|
|
return outerNode.contains(innerNode);
|
|
} else if (outerNode.compareDocumentPosition) {
|
|
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = containsNode;
|
|
|
|
/***/ }),
|
|
/* 60 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule isTextNode
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var isNode = __webpack_require__(61);
|
|
|
|
/**
|
|
* @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;
|
|
|
|
/***/ }),
|
|
/* 61 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule isNode
|
|
* @typechecks
|
|
*/
|
|
|
|
/**
|
|
* @param {*} object The object to check.
|
|
* @return {boolean} Whether or not the object is a DOM node.
|
|
*/
|
|
'use strict';
|
|
|
|
function isNode(object) {
|
|
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
|
|
}
|
|
|
|
module.exports = isNode;
|
|
|
|
/***/ }),
|
|
/* 62 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule instantiateReactComponent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCompositeComponent = __webpack_require__(63);
|
|
var ReactEmptyComponent = __webpack_require__(68);
|
|
var ReactNativeComponent = __webpack_require__(69);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
// To avoid a cyclic dependency, we create the final class in this module
|
|
var ReactCompositeComponentWrapper = function () {};
|
|
assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
|
|
_instantiateReactComponent: instantiateReactComponent
|
|
});
|
|
|
|
function getDeclarationErrorAddendum(owner) {
|
|
if (owner) {
|
|
var name = owner.getName();
|
|
if (name) {
|
|
return ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Check if the type reference is a known internal type. I.e. not a user
|
|
* provided composite type.
|
|
*
|
|
* @param {function} type
|
|
* @return {boolean} Returns true if this is a valid internal type.
|
|
*/
|
|
function isInternalComponentType(type) {
|
|
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
|
|
}
|
|
|
|
/**
|
|
* Given a ReactNode, create an instance that will actually be mounted.
|
|
*
|
|
* @param {ReactNode} node
|
|
* @return {object} A new instance of the element's constructor.
|
|
* @protected
|
|
*/
|
|
function instantiateReactComponent(node) {
|
|
var instance;
|
|
|
|
if (node === null || node === false) {
|
|
instance = new ReactEmptyComponent(instantiateReactComponent);
|
|
} else if (typeof node === 'object') {
|
|
var element = node;
|
|
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
|
|
|
|
// Special case string values
|
|
if (typeof element.type === 'string') {
|
|
instance = ReactNativeComponent.createInternalComponent(element);
|
|
} else if (isInternalComponentType(element.type)) {
|
|
// This is temporarily available for custom components that are not string
|
|
// representations. I.e. ART. Once those are updated to use the string
|
|
// representation, we can drop this code path.
|
|
instance = new element.type(element);
|
|
} else {
|
|
instance = new ReactCompositeComponentWrapper();
|
|
}
|
|
} else if (typeof node === 'string' || typeof node === 'number') {
|
|
instance = ReactNativeComponent.createInstanceForText(node);
|
|
} else {
|
|
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
|
|
}
|
|
|
|
// Sets up the instance. This can probably just move into the constructor now.
|
|
instance.construct(node);
|
|
|
|
// These two fields are used by the DOM and ART diffing algorithms
|
|
// respectively. Instead of using expandos on components, we should be
|
|
// storing the state needed by the diffing algorithms elsewhere.
|
|
instance._mountIndex = 0;
|
|
instance._mountImage = null;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
instance._isOwnerNecessary = false;
|
|
instance._warnedAboutRefsInRender = false;
|
|
}
|
|
|
|
// Internal instances should fully constructed at this point, so they should
|
|
// not get any new fields added to them at this point.
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (Object.preventExtensions) {
|
|
Object.preventExtensions(instance);
|
|
}
|
|
}
|
|
|
|
return instance;
|
|
}
|
|
|
|
module.exports = instantiateReactComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 63 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactCompositeComponent
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactComponentEnvironment = __webpack_require__(64);
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactInstanceMap = __webpack_require__(47);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactPropTypeLocations = __webpack_require__(65);
|
|
var ReactPropTypeLocationNames = __webpack_require__(66);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
var ReactUpdateQueue = __webpack_require__(53);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyObject = __webpack_require__(58);
|
|
var invariant = __webpack_require__(13);
|
|
var shouldUpdateReactComponent = __webpack_require__(67);
|
|
var warning = __webpack_require__(25);
|
|
|
|
function getDeclarationErrorAddendum(component) {
|
|
var owner = component._currentElement._owner || null;
|
|
if (owner) {
|
|
var name = owner.getName();
|
|
if (name) {
|
|
return ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function StatelessComponent(Component) {}
|
|
StatelessComponent.prototype.render = function () {
|
|
var Component = ReactInstanceMap.get(this)._currentElement.type;
|
|
return Component(this.props, this.context, this.updater);
|
|
};
|
|
|
|
/**
|
|
* ------------------ The Life-Cycle of a Composite Component ------------------
|
|
*
|
|
* - constructor: Initialization of state. The instance is now retained.
|
|
* - componentWillMount
|
|
* - render
|
|
* - [children's constructors]
|
|
* - [children's componentWillMount and render]
|
|
* - [children's componentDidMount]
|
|
* - componentDidMount
|
|
*
|
|
* Update Phases:
|
|
* - componentWillReceiveProps (only called if parent updated)
|
|
* - shouldComponentUpdate
|
|
* - componentWillUpdate
|
|
* - render
|
|
* - [children's constructors or receive props phases]
|
|
* - componentDidUpdate
|
|
*
|
|
* - componentWillUnmount
|
|
* - [children's componentWillUnmount]
|
|
* - [children destroyed]
|
|
* - (destroyed): The instance is now blank, released by React and ready for GC.
|
|
*
|
|
* -----------------------------------------------------------------------------
|
|
*/
|
|
|
|
/**
|
|
* An incrementing ID assigned to each component when it is mounted. This is
|
|
* used to enforce the order in which `ReactUpdates` updates dirty components.
|
|
*
|
|
* @private
|
|
*/
|
|
var nextMountID = 1;
|
|
|
|
/**
|
|
* @lends {ReactCompositeComponent.prototype}
|
|
*/
|
|
var ReactCompositeComponentMixin = {
|
|
|
|
/**
|
|
* Base constructor for all composite component.
|
|
*
|
|
* @param {ReactElement} element
|
|
* @final
|
|
* @internal
|
|
*/
|
|
construct: function (element) {
|
|
this._currentElement = element;
|
|
this._rootNodeID = null;
|
|
this._instance = null;
|
|
|
|
// See ReactUpdateQueue
|
|
this._pendingElement = null;
|
|
this._pendingStateQueue = null;
|
|
this._pendingReplaceState = false;
|
|
this._pendingForceUpdate = false;
|
|
|
|
this._renderedComponent = null;
|
|
|
|
this._context = null;
|
|
this._mountOrder = 0;
|
|
this._topLevelWrapper = null;
|
|
|
|
// See ReactUpdates and ReactUpdateQueue.
|
|
this._pendingCallbacks = null;
|
|
},
|
|
|
|
/**
|
|
* Initializes the component, renders markup, and registers event listeners.
|
|
*
|
|
* @param {string} rootID DOM ID of the root node.
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @return {?string} Rendered markup to be inserted into the DOM.
|
|
* @final
|
|
* @internal
|
|
*/
|
|
mountComponent: function (rootID, transaction, context) {
|
|
this._context = context;
|
|
this._mountOrder = nextMountID++;
|
|
this._rootNodeID = rootID;
|
|
|
|
var publicProps = this._processProps(this._currentElement.props);
|
|
var publicContext = this._processContext(context);
|
|
|
|
var Component = this._currentElement.type;
|
|
|
|
// Initialize the public class
|
|
var inst;
|
|
var renderedElement;
|
|
|
|
// This is a way to detect if Component is a stateless arrow function
|
|
// component, which is not newable. It might not be 100% reliable but is
|
|
// something we can do until we start detecting that Component extends
|
|
// React.Component. We already assume that typeof Component === 'function'.
|
|
var canInstantiate = ('prototype' in Component);
|
|
|
|
if (canInstantiate) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
ReactCurrentOwner.current = this;
|
|
try {
|
|
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
|
|
} finally {
|
|
ReactCurrentOwner.current = null;
|
|
}
|
|
} else {
|
|
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
|
|
}
|
|
}
|
|
|
|
if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) {
|
|
renderedElement = inst;
|
|
inst = new StatelessComponent(Component);
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// This will throw later in _renderValidatedComponent, but add an early
|
|
// warning now to help debugging
|
|
if (inst.render == null) {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined;
|
|
} else {
|
|
// We support ES6 inheriting from React.Component, the module pattern,
|
|
// and stateless components, but not ES6 classes that don't extend
|
|
process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined;
|
|
}
|
|
}
|
|
|
|
// These should be set up in the constructor, but as a convenience for
|
|
// simpler class abstractions, we set them up after the fact.
|
|
inst.props = publicProps;
|
|
inst.context = publicContext;
|
|
inst.refs = emptyObject;
|
|
inst.updater = ReactUpdateQueue;
|
|
|
|
this._instance = inst;
|
|
|
|
// Store a reference from the instance back to the internal representation
|
|
ReactInstanceMap.set(inst, this);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// Since plain JS classes are defined without any special initialization
|
|
// logic, we can not catch common errors early. Therefore, we have to
|
|
// catch them here, at initialization time, instead.
|
|
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, '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?', this.getName() || 'a component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, '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.', this.getName() || 'a component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%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.', this.getName() || 'A component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined;
|
|
}
|
|
|
|
var initialState = inst.state;
|
|
if (initialState === undefined) {
|
|
inst.state = initialState = null;
|
|
}
|
|
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
|
|
|
|
this._pendingStateQueue = null;
|
|
this._pendingReplaceState = false;
|
|
this._pendingForceUpdate = false;
|
|
|
|
if (inst.componentWillMount) {
|
|
inst.componentWillMount();
|
|
// When mounting, calls to `setState` by `componentWillMount` will set
|
|
// `this._pendingStateQueue` without triggering a re-render.
|
|
if (this._pendingStateQueue) {
|
|
inst.state = this._processPendingState(inst.props, inst.context);
|
|
}
|
|
}
|
|
|
|
// If not a stateless component, we now render
|
|
if (renderedElement === undefined) {
|
|
renderedElement = this._renderValidatedComponent();
|
|
}
|
|
|
|
this._renderedComponent = this._instantiateReactComponent(renderedElement);
|
|
|
|
var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context));
|
|
if (inst.componentDidMount) {
|
|
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
|
|
}
|
|
|
|
return markup;
|
|
},
|
|
|
|
/**
|
|
* Releases any resources allocated by `mountComponent`.
|
|
*
|
|
* @final
|
|
* @internal
|
|
*/
|
|
unmountComponent: function () {
|
|
var inst = this._instance;
|
|
|
|
if (inst.componentWillUnmount) {
|
|
inst.componentWillUnmount();
|
|
}
|
|
|
|
ReactReconciler.unmountComponent(this._renderedComponent);
|
|
this._renderedComponent = null;
|
|
this._instance = null;
|
|
|
|
// Reset pending fields
|
|
// Even if this component is scheduled for another update in ReactUpdates,
|
|
// it would still be ignored because these fields are reset.
|
|
this._pendingStateQueue = null;
|
|
this._pendingReplaceState = false;
|
|
this._pendingForceUpdate = false;
|
|
this._pendingCallbacks = null;
|
|
this._pendingElement = null;
|
|
|
|
// These fields do not really need to be reset since this object is no
|
|
// longer accessible.
|
|
this._context = null;
|
|
this._rootNodeID = null;
|
|
this._topLevelWrapper = null;
|
|
|
|
// Delete the reference from the instance to this internal representation
|
|
// which allow the internals to be properly cleaned up even if the user
|
|
// leaks a reference to the public instance.
|
|
ReactInstanceMap.remove(inst);
|
|
|
|
// Some existing components rely on inst.props even after they've been
|
|
// destroyed (in event handlers).
|
|
// TODO: inst.props = null;
|
|
// TODO: inst.state = null;
|
|
// TODO: inst.context = null;
|
|
},
|
|
|
|
/**
|
|
* Filters the context object to only contain keys specified in
|
|
* `contextTypes`
|
|
*
|
|
* @param {object} context
|
|
* @return {?object}
|
|
* @private
|
|
*/
|
|
_maskContext: function (context) {
|
|
var maskedContext = null;
|
|
var Component = this._currentElement.type;
|
|
var contextTypes = Component.contextTypes;
|
|
if (!contextTypes) {
|
|
return emptyObject;
|
|
}
|
|
maskedContext = {};
|
|
for (var contextName in contextTypes) {
|
|
maskedContext[contextName] = context[contextName];
|
|
}
|
|
return maskedContext;
|
|
},
|
|
|
|
/**
|
|
* Filters the context object to only contain keys specified in
|
|
* `contextTypes`, and asserts that they are valid.
|
|
*
|
|
* @param {object} context
|
|
* @return {?object}
|
|
* @private
|
|
*/
|
|
_processContext: function (context) {
|
|
var maskedContext = this._maskContext(context);
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var Component = this._currentElement.type;
|
|
if (Component.contextTypes) {
|
|
this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
|
|
}
|
|
}
|
|
return maskedContext;
|
|
},
|
|
|
|
/**
|
|
* @param {object} currentContext
|
|
* @return {object}
|
|
* @private
|
|
*/
|
|
_processChildContext: function (currentContext) {
|
|
var Component = this._currentElement.type;
|
|
var inst = this._instance;
|
|
var childContext = inst.getChildContext && inst.getChildContext();
|
|
if (childContext) {
|
|
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
|
|
}
|
|
for (var name in childContext) {
|
|
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined;
|
|
}
|
|
return assign({}, currentContext, childContext);
|
|
}
|
|
return currentContext;
|
|
},
|
|
|
|
/**
|
|
* Processes props by setting default values for unspecified props and
|
|
* asserting that the props are valid. Does not mutate its argument; returns
|
|
* a new props object with defaults merged in.
|
|
*
|
|
* @param {object} newProps
|
|
* @return {object}
|
|
* @private
|
|
*/
|
|
_processProps: function (newProps) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var Component = this._currentElement.type;
|
|
if (Component.propTypes) {
|
|
this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
|
|
}
|
|
}
|
|
return newProps;
|
|
},
|
|
|
|
/**
|
|
* Assert that the props are valid
|
|
*
|
|
* @param {object} propTypes Map of prop name to a ReactPropType
|
|
* @param {object} props
|
|
* @param {string} location e.g. "prop", "context", "child context"
|
|
* @private
|
|
*/
|
|
_checkPropTypes: function (propTypes, props, location) {
|
|
// TODO: Stop validating prop types here and only use the element
|
|
// validation.
|
|
var componentName = this.getName();
|
|
for (var propName in propTypes) {
|
|
if (propTypes.hasOwnProperty(propName)) {
|
|
var error;
|
|
try {
|
|
// This is intentionally an invariant that gets caught. It's the same
|
|
// behavior as without this statement except with a better message.
|
|
!(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
|
|
error = propTypes[propName](props, propName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
} catch (ex) {
|
|
error = ex;
|
|
}
|
|
if (error instanceof Error) {
|
|
// We may want to extend this logic for similar errors in
|
|
// top-level render calls, so I'm abstracting it away into
|
|
// a function to minimize refactoring in the future
|
|
var addendum = getDeclarationErrorAddendum(this);
|
|
|
|
if (location === ReactPropTypeLocations.prop) {
|
|
// Preface gives us something to blacklist in warning module
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined;
|
|
} else {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
receiveComponent: function (nextElement, transaction, nextContext) {
|
|
var prevElement = this._currentElement;
|
|
var prevContext = this._context;
|
|
|
|
this._pendingElement = null;
|
|
|
|
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
|
|
},
|
|
|
|
/**
|
|
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
|
|
* is set, update the component.
|
|
*
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
*/
|
|
performUpdateIfNecessary: function (transaction) {
|
|
if (this._pendingElement != null) {
|
|
ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context);
|
|
}
|
|
|
|
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
|
|
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Perform an update to a mounted component. The componentWillReceiveProps and
|
|
* shouldComponentUpdate methods are called, then (assuming the update isn't
|
|
* skipped) the remaining update lifecycle methods are called and the DOM
|
|
* representation is updated.
|
|
*
|
|
* By default, this implements React's rendering and reconciliation algorithm.
|
|
* Sophisticated clients may wish to override this.
|
|
*
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {ReactElement} prevParentElement
|
|
* @param {ReactElement} nextParentElement
|
|
* @internal
|
|
* @overridable
|
|
*/
|
|
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
|
|
var inst = this._instance;
|
|
|
|
var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext);
|
|
var nextProps;
|
|
|
|
// Distinguish between a props update versus a simple state update
|
|
if (prevParentElement === nextParentElement) {
|
|
// Skip checking prop types again -- we don't read inst.props to avoid
|
|
// warning for DOM component props in this upgrade
|
|
nextProps = nextParentElement.props;
|
|
} else {
|
|
nextProps = this._processProps(nextParentElement.props);
|
|
// An update here will schedule an update but immediately set
|
|
// _pendingStateQueue which will ensure that any state updates gets
|
|
// immediately reconciled instead of waiting for the next batch.
|
|
|
|
if (inst.componentWillReceiveProps) {
|
|
inst.componentWillReceiveProps(nextProps, nextContext);
|
|
}
|
|
}
|
|
|
|
var nextState = this._processPendingState(nextProps, nextContext);
|
|
|
|
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined;
|
|
}
|
|
|
|
if (shouldUpdate) {
|
|
this._pendingForceUpdate = false;
|
|
// Will set `this.props`, `this.state` and `this.context`.
|
|
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
|
|
} else {
|
|
// If it's determined that a component should not update, we still want
|
|
// to set props and state but we shortcut the rest of the update.
|
|
this._currentElement = nextParentElement;
|
|
this._context = nextUnmaskedContext;
|
|
inst.props = nextProps;
|
|
inst.state = nextState;
|
|
inst.context = nextContext;
|
|
}
|
|
},
|
|
|
|
_processPendingState: function (props, context) {
|
|
var inst = this._instance;
|
|
var queue = this._pendingStateQueue;
|
|
var replace = this._pendingReplaceState;
|
|
this._pendingReplaceState = false;
|
|
this._pendingStateQueue = null;
|
|
|
|
if (!queue) {
|
|
return inst.state;
|
|
}
|
|
|
|
if (replace && queue.length === 1) {
|
|
return queue[0];
|
|
}
|
|
|
|
var nextState = assign({}, replace ? queue[0] : inst.state);
|
|
for (var i = replace ? 1 : 0; i < queue.length; i++) {
|
|
var partial = queue[i];
|
|
assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
|
|
}
|
|
|
|
return nextState;
|
|
},
|
|
|
|
/**
|
|
* Merges new props and state, notifies delegate methods of update and
|
|
* performs update.
|
|
*
|
|
* @param {ReactElement} nextElement Next element
|
|
* @param {object} nextProps Next public object to set as properties.
|
|
* @param {?object} nextState Next object to set as state.
|
|
* @param {?object} nextContext Next public object to set as context.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {?object} unmaskedContext
|
|
* @private
|
|
*/
|
|
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
|
|
var inst = this._instance;
|
|
|
|
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
|
|
var prevProps;
|
|
var prevState;
|
|
var prevContext;
|
|
if (hasComponentDidUpdate) {
|
|
prevProps = inst.props;
|
|
prevState = inst.state;
|
|
prevContext = inst.context;
|
|
}
|
|
|
|
if (inst.componentWillUpdate) {
|
|
inst.componentWillUpdate(nextProps, nextState, nextContext);
|
|
}
|
|
|
|
this._currentElement = nextElement;
|
|
this._context = unmaskedContext;
|
|
inst.props = nextProps;
|
|
inst.state = nextState;
|
|
inst.context = nextContext;
|
|
|
|
this._updateRenderedComponent(transaction, unmaskedContext);
|
|
|
|
if (hasComponentDidUpdate) {
|
|
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Call the component's `render` method and update the DOM accordingly.
|
|
*
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
*/
|
|
_updateRenderedComponent: function (transaction, context) {
|
|
var prevComponentInstance = this._renderedComponent;
|
|
var prevRenderedElement = prevComponentInstance._currentElement;
|
|
var nextRenderedElement = this._renderValidatedComponent();
|
|
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
|
|
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
|
|
} else {
|
|
// These two IDs are actually the same! But nothing should rely on that.
|
|
var thisID = this._rootNodeID;
|
|
var prevComponentID = prevComponentInstance._rootNodeID;
|
|
ReactReconciler.unmountComponent(prevComponentInstance);
|
|
|
|
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
|
|
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context));
|
|
this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* @protected
|
|
*/
|
|
_replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) {
|
|
ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
|
|
},
|
|
|
|
/**
|
|
* @protected
|
|
*/
|
|
_renderValidatedComponentWithoutOwnerOrContext: function () {
|
|
var inst = this._instance;
|
|
var renderedComponent = inst.render();
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// We allow auto-mocks to proceed as if they're returning null.
|
|
if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) {
|
|
// This is probably bad practice. Consider warning here and
|
|
// deprecating this convenience.
|
|
renderedComponent = null;
|
|
}
|
|
}
|
|
|
|
return renderedComponent;
|
|
},
|
|
|
|
/**
|
|
* @private
|
|
*/
|
|
_renderValidatedComponent: function () {
|
|
var renderedComponent;
|
|
ReactCurrentOwner.current = this;
|
|
try {
|
|
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
|
|
} finally {
|
|
ReactCurrentOwner.current = null;
|
|
}
|
|
!(
|
|
// TODO: An `isValidNode` function would probably be more appropriate
|
|
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
|
|
return renderedComponent;
|
|
},
|
|
|
|
/**
|
|
* Lazily allocates the refs object and stores `component` as `ref`.
|
|
*
|
|
* @param {string} ref Reference name.
|
|
* @param {component} component Component to store as `ref`.
|
|
* @final
|
|
* @private
|
|
*/
|
|
attachRef: function (ref, component) {
|
|
var inst = this.getPublicInstance();
|
|
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined;
|
|
var publicComponentInstance = component.getPublicInstance();
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var componentName = component && component.getName ? component.getName() : 'a component';
|
|
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined;
|
|
}
|
|
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
|
|
refs[ref] = publicComponentInstance;
|
|
},
|
|
|
|
/**
|
|
* Detaches a reference name.
|
|
*
|
|
* @param {string} ref Name to dereference.
|
|
* @final
|
|
* @private
|
|
*/
|
|
detachRef: function (ref) {
|
|
var refs = this.getPublicInstance().refs;
|
|
delete refs[ref];
|
|
},
|
|
|
|
/**
|
|
* Get a text description of the component that can be used to identify it
|
|
* in error messages.
|
|
* @return {string} The name or null.
|
|
* @internal
|
|
*/
|
|
getName: function () {
|
|
var type = this._currentElement.type;
|
|
var constructor = this._instance && this._instance.constructor;
|
|
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
|
|
},
|
|
|
|
/**
|
|
* Get the publicly accessible representation of this component - i.e. what
|
|
* is exposed by refs and returned by render. Can be null for stateless
|
|
* components.
|
|
*
|
|
* @return {ReactComponent} the public component instance.
|
|
* @internal
|
|
*/
|
|
getPublicInstance: function () {
|
|
var inst = this._instance;
|
|
if (inst instanceof StatelessComponent) {
|
|
return null;
|
|
}
|
|
return inst;
|
|
},
|
|
|
|
// Stub
|
|
_instantiateReactComponent: null
|
|
|
|
};
|
|
|
|
ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', {
|
|
mountComponent: 'mountComponent',
|
|
updateComponent: 'updateComponent',
|
|
_renderValidatedComponent: '_renderValidatedComponent'
|
|
});
|
|
|
|
var ReactCompositeComponent = {
|
|
|
|
Mixin: ReactCompositeComponentMixin
|
|
|
|
};
|
|
|
|
module.exports = ReactCompositeComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 64 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactComponentEnvironment
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var injected = false;
|
|
|
|
var ReactComponentEnvironment = {
|
|
|
|
/**
|
|
* Optionally injectable environment dependent cleanup hook. (server vs.
|
|
* browser etc). Example: A browser system caches DOM nodes based on component
|
|
* ID and must remove that cache entry when this instance is unmounted.
|
|
*/
|
|
unmountIDFromEnvironment: null,
|
|
|
|
/**
|
|
* Optionally injectable hook for swapping out mount images in the middle of
|
|
* the tree.
|
|
*/
|
|
replaceNodeWithMarkupByID: null,
|
|
|
|
/**
|
|
* Optionally injectable hook for processing a queue of child updates. Will
|
|
* later move into MultiChildComponents.
|
|
*/
|
|
processChildrenUpdates: null,
|
|
|
|
injection: {
|
|
injectEnvironment: function (environment) {
|
|
!!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined;
|
|
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
|
|
ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID;
|
|
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
|
|
injected = true;
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactComponentEnvironment;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 65 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactPropTypeLocations
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var keyMirror = __webpack_require__(17);
|
|
|
|
var ReactPropTypeLocations = keyMirror({
|
|
prop: null,
|
|
context: null,
|
|
childContext: null
|
|
});
|
|
|
|
module.exports = ReactPropTypeLocations;
|
|
|
|
/***/ }),
|
|
/* 66 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactPropTypeLocationNames
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactPropTypeLocationNames = {};
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
ReactPropTypeLocationNames = {
|
|
prop: 'prop',
|
|
context: 'context',
|
|
childContext: 'child context'
|
|
};
|
|
}
|
|
|
|
module.exports = ReactPropTypeLocationNames;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 67 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule shouldUpdateReactComponent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Given a `prevElement` and `nextElement`, determines if the existing
|
|
* instance should be updated as opposed to being destroyed or replaced by a new
|
|
* instance. Both arguments are elements. This ensures that this logic can
|
|
* operate on stateless trees without any backing instance.
|
|
*
|
|
* @param {?object} prevElement
|
|
* @param {?object} nextElement
|
|
* @return {boolean} True if the existing instance should be updated.
|
|
* @protected
|
|
*/
|
|
function shouldUpdateReactComponent(prevElement, nextElement) {
|
|
var prevEmpty = prevElement === null || prevElement === false;
|
|
var nextEmpty = nextElement === null || nextElement === false;
|
|
if (prevEmpty || nextEmpty) {
|
|
return prevEmpty === nextEmpty;
|
|
}
|
|
|
|
var prevType = typeof prevElement;
|
|
var nextType = typeof nextElement;
|
|
if (prevType === 'string' || prevType === 'number') {
|
|
return nextType === 'string' || nextType === 'number';
|
|
} else {
|
|
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
module.exports = shouldUpdateReactComponent;
|
|
|
|
/***/ }),
|
|
/* 68 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactEmptyComponent
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactEmptyComponentRegistry = __webpack_require__(44);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
|
|
var assign = __webpack_require__(39);
|
|
|
|
var placeholderElement;
|
|
|
|
var ReactEmptyComponentInjection = {
|
|
injectEmptyComponent: function (component) {
|
|
placeholderElement = ReactElement.createElement(component);
|
|
}
|
|
};
|
|
|
|
function registerNullComponentID() {
|
|
ReactEmptyComponentRegistry.registerNullComponentID(this._rootNodeID);
|
|
}
|
|
|
|
var ReactEmptyComponent = function (instantiate) {
|
|
this._currentElement = null;
|
|
this._rootNodeID = null;
|
|
this._renderedComponent = instantiate(placeholderElement);
|
|
};
|
|
assign(ReactEmptyComponent.prototype, {
|
|
construct: function (element) {},
|
|
mountComponent: function (rootID, transaction, context) {
|
|
transaction.getReactMountReady().enqueue(registerNullComponentID, this);
|
|
this._rootNodeID = rootID;
|
|
return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context);
|
|
},
|
|
receiveComponent: function () {},
|
|
unmountComponent: function (rootID, transaction, context) {
|
|
ReactReconciler.unmountComponent(this._renderedComponent);
|
|
ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID);
|
|
this._rootNodeID = null;
|
|
this._renderedComponent = null;
|
|
}
|
|
});
|
|
|
|
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
|
|
|
|
module.exports = ReactEmptyComponent;
|
|
|
|
/***/ }),
|
|
/* 69 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactNativeComponent
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var autoGenerateWrapperClass = null;
|
|
var genericComponentClass = null;
|
|
// This registry keeps track of wrapper classes around native tags.
|
|
var tagToComponentClass = {};
|
|
var textComponentClass = null;
|
|
|
|
var ReactNativeComponentInjection = {
|
|
// This accepts a class that receives the tag string. This is a catch all
|
|
// that can render any kind of tag.
|
|
injectGenericComponentClass: function (componentClass) {
|
|
genericComponentClass = componentClass;
|
|
},
|
|
// This accepts a text component class that takes the text string to be
|
|
// rendered as props.
|
|
injectTextComponentClass: function (componentClass) {
|
|
textComponentClass = componentClass;
|
|
},
|
|
// This accepts a keyed object with classes as values. Each key represents a
|
|
// tag. That particular tag will use this class instead of the generic one.
|
|
injectComponentClasses: function (componentClasses) {
|
|
assign(tagToComponentClass, componentClasses);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Get a composite component wrapper class for a specific tag.
|
|
*
|
|
* @param {ReactElement} element The tag for which to get the class.
|
|
* @return {function} The React class constructor function.
|
|
*/
|
|
function getComponentClassForElement(element) {
|
|
if (typeof element.type === 'function') {
|
|
return element.type;
|
|
}
|
|
var tag = element.type;
|
|
var componentClass = tagToComponentClass[tag];
|
|
if (componentClass == null) {
|
|
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
|
|
}
|
|
return componentClass;
|
|
}
|
|
|
|
/**
|
|
* Get a native internal component class for a specific tag.
|
|
*
|
|
* @param {ReactElement} element The element to create.
|
|
* @return {function} The internal class constructor function.
|
|
*/
|
|
function createInternalComponent(element) {
|
|
!genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
|
|
return new genericComponentClass(element.type, element.props);
|
|
}
|
|
|
|
/**
|
|
* @param {ReactText} text
|
|
* @return {ReactComponent}
|
|
*/
|
|
function createInstanceForText(text) {
|
|
return new textComponentClass(text);
|
|
}
|
|
|
|
/**
|
|
* @param {ReactComponent} component
|
|
* @return {boolean}
|
|
*/
|
|
function isTextComponent(component) {
|
|
return component instanceof textComponentClass;
|
|
}
|
|
|
|
var ReactNativeComponent = {
|
|
getComponentClassForElement: getComponentClassForElement,
|
|
createInternalComponent: createInternalComponent,
|
|
createInstanceForText: createInstanceForText,
|
|
isTextComponent: isTextComponent,
|
|
injection: ReactNativeComponentInjection
|
|
};
|
|
|
|
module.exports = ReactNativeComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 70 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule validateDOMNesting
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyFunction = __webpack_require__(15);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var validateDOMNesting = emptyFunction;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// This validation code was written based on the HTML5 parsing spec:
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
|
|
//
|
|
// Note: this does not catch all invalid nesting, nor does it try to (as it's
|
|
// not clear what practical benefit doing so provides); instead, we warn only
|
|
// for cases where the parser will give a parse tree differing from what React
|
|
// intended. For example, <b><div></div></b> is invalid but we don't warn
|
|
// because it still parses correctly; we do warn for other cases like nested
|
|
// <p> tags where the beginning of the second element implicitly closes the
|
|
// first, causing a confusing mess.
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#special
|
|
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
|
|
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
|
|
// TODO: Distinguish by namespace here -- for <title>, including it here
|
|
// errs on the side of fewer warnings
|
|
'foreignObject', 'desc', 'title'];
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
|
|
var buttonScopeTags = inScopeTags.concat(['button']);
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
|
|
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
|
|
|
|
var emptyAncestorInfo = {
|
|
parentTag: null,
|
|
|
|
formTag: null,
|
|
aTagInScope: null,
|
|
buttonTagInScope: null,
|
|
nobrTagInScope: null,
|
|
pTagInButtonScope: null,
|
|
|
|
listItemTagAutoclosing: null,
|
|
dlItemTagAutoclosing: null
|
|
};
|
|
|
|
var updatedAncestorInfo = function (oldInfo, tag, instance) {
|
|
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
|
|
var info = { tag: tag, instance: instance };
|
|
|
|
if (inScopeTags.indexOf(tag) !== -1) {
|
|
ancestorInfo.aTagInScope = null;
|
|
ancestorInfo.buttonTagInScope = null;
|
|
ancestorInfo.nobrTagInScope = null;
|
|
}
|
|
if (buttonScopeTags.indexOf(tag) !== -1) {
|
|
ancestorInfo.pTagInButtonScope = null;
|
|
}
|
|
|
|
// See rules for 'li', 'dd', 'dt' start tags in
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
|
|
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
|
|
ancestorInfo.listItemTagAutoclosing = null;
|
|
ancestorInfo.dlItemTagAutoclosing = null;
|
|
}
|
|
|
|
ancestorInfo.parentTag = info;
|
|
|
|
if (tag === 'form') {
|
|
ancestorInfo.formTag = info;
|
|
}
|
|
if (tag === 'a') {
|
|
ancestorInfo.aTagInScope = info;
|
|
}
|
|
if (tag === 'button') {
|
|
ancestorInfo.buttonTagInScope = info;
|
|
}
|
|
if (tag === 'nobr') {
|
|
ancestorInfo.nobrTagInScope = info;
|
|
}
|
|
if (tag === 'p') {
|
|
ancestorInfo.pTagInButtonScope = info;
|
|
}
|
|
if (tag === 'li') {
|
|
ancestorInfo.listItemTagAutoclosing = info;
|
|
}
|
|
if (tag === 'dd' || tag === 'dt') {
|
|
ancestorInfo.dlItemTagAutoclosing = info;
|
|
}
|
|
|
|
return ancestorInfo;
|
|
};
|
|
|
|
/**
|
|
* Returns whether
|
|
*/
|
|
var isTagValidWithParent = function (tag, parentTag) {
|
|
// First, let's check if we're in an unusual parsing mode...
|
|
switch (parentTag) {
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
|
|
case 'select':
|
|
return tag === 'option' || tag === 'optgroup' || tag === '#text';
|
|
case 'optgroup':
|
|
return tag === 'option' || tag === '#text';
|
|
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
|
|
// but
|
|
case 'option':
|
|
return tag === '#text';
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
|
|
// No special behavior since these rules fall back to "in body" mode for
|
|
// all except special table nodes which cause bad parsing behavior anyway.
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
|
|
case 'tr':
|
|
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
|
|
case 'tbody':
|
|
case 'thead':
|
|
case 'tfoot':
|
|
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
|
|
case 'colgroup':
|
|
return tag === 'col' || tag === 'template';
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
|
|
case 'table':
|
|
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
|
|
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
|
|
case 'head':
|
|
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
|
|
|
|
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
|
|
case 'html':
|
|
return tag === 'head' || tag === 'body';
|
|
}
|
|
|
|
// Probably in the "in body" parsing mode, so we outlaw only tag combos
|
|
// where the parsing rules cause implicit opens or closes to be added.
|
|
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
|
|
switch (tag) {
|
|
case 'h1':
|
|
case 'h2':
|
|
case 'h3':
|
|
case 'h4':
|
|
case 'h5':
|
|
case 'h6':
|
|
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
|
|
|
|
case 'rp':
|
|
case 'rt':
|
|
return impliedEndTags.indexOf(parentTag) === -1;
|
|
|
|
case 'caption':
|
|
case 'col':
|
|
case 'colgroup':
|
|
case 'frame':
|
|
case 'head':
|
|
case 'tbody':
|
|
case 'td':
|
|
case 'tfoot':
|
|
case 'th':
|
|
case 'thead':
|
|
case 'tr':
|
|
// These tags are only valid with a few parents that have special child
|
|
// parsing rules -- if we're down here, then none of those matched and
|
|
// so we allow it only if we don't know what the parent is, as all other
|
|
// cases are invalid.
|
|
return parentTag == null;
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* Returns whether
|
|
*/
|
|
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
|
|
switch (tag) {
|
|
case 'address':
|
|
case 'article':
|
|
case 'aside':
|
|
case 'blockquote':
|
|
case 'center':
|
|
case 'details':
|
|
case 'dialog':
|
|
case 'dir':
|
|
case 'div':
|
|
case 'dl':
|
|
case 'fieldset':
|
|
case 'figcaption':
|
|
case 'figure':
|
|
case 'footer':
|
|
case 'header':
|
|
case 'hgroup':
|
|
case 'main':
|
|
case 'menu':
|
|
case 'nav':
|
|
case 'ol':
|
|
case 'p':
|
|
case 'section':
|
|
case 'summary':
|
|
case 'ul':
|
|
|
|
case 'pre':
|
|
case 'listing':
|
|
|
|
case 'table':
|
|
|
|
case 'hr':
|
|
|
|
case 'xmp':
|
|
|
|
case 'h1':
|
|
case 'h2':
|
|
case 'h3':
|
|
case 'h4':
|
|
case 'h5':
|
|
case 'h6':
|
|
return ancestorInfo.pTagInButtonScope;
|
|
|
|
case 'form':
|
|
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
|
|
|
|
case 'li':
|
|
return ancestorInfo.listItemTagAutoclosing;
|
|
|
|
case 'dd':
|
|
case 'dt':
|
|
return ancestorInfo.dlItemTagAutoclosing;
|
|
|
|
case 'button':
|
|
return ancestorInfo.buttonTagInScope;
|
|
|
|
case 'a':
|
|
// Spec says something about storing a list of markers, but it sounds
|
|
// equivalent to this check.
|
|
return ancestorInfo.aTagInScope;
|
|
|
|
case 'nobr':
|
|
return ancestorInfo.nobrTagInScope;
|
|
}
|
|
|
|
return null;
|
|
};
|
|
|
|
/**
|
|
* Given a ReactCompositeComponent instance, return a list of its recursive
|
|
* owners, starting at the root and ending with the instance itself.
|
|
*/
|
|
var findOwnerStack = function (instance) {
|
|
if (!instance) {
|
|
return [];
|
|
}
|
|
|
|
var stack = [];
|
|
/*eslint-disable space-after-keywords */
|
|
do {
|
|
/*eslint-enable space-after-keywords */
|
|
stack.push(instance);
|
|
} while (instance = instance._currentElement._owner);
|
|
stack.reverse();
|
|
return stack;
|
|
};
|
|
|
|
var didWarn = {};
|
|
|
|
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
|
|
ancestorInfo = ancestorInfo || emptyAncestorInfo;
|
|
var parentInfo = ancestorInfo.parentTag;
|
|
var parentTag = parentInfo && parentInfo.tag;
|
|
|
|
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
|
|
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
|
|
var problematic = invalidParent || invalidAncestor;
|
|
|
|
if (problematic) {
|
|
var ancestorTag = problematic.tag;
|
|
var ancestorInstance = problematic.instance;
|
|
|
|
var childOwner = childInstance && childInstance._currentElement._owner;
|
|
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
|
|
|
|
var childOwners = findOwnerStack(childOwner);
|
|
var ancestorOwners = findOwnerStack(ancestorOwner);
|
|
|
|
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
|
|
var i;
|
|
|
|
var deepestCommon = -1;
|
|
for (i = 0; i < minStackLen; i++) {
|
|
if (childOwners[i] === ancestorOwners[i]) {
|
|
deepestCommon = i;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
var UNKNOWN = '(unknown)';
|
|
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
|
|
return inst.getName() || UNKNOWN;
|
|
});
|
|
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
|
|
return inst.getName() || UNKNOWN;
|
|
});
|
|
var ownerInfo = [].concat(
|
|
// If the parent and child instances have a common owner ancestor, start
|
|
// with that -- otherwise we just start with the parent's owners.
|
|
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
|
|
// If we're warning about an invalid (non-parent) ancestry, add '...'
|
|
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
|
|
|
|
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
|
|
if (didWarn[warnKey]) {
|
|
return;
|
|
}
|
|
didWarn[warnKey] = true;
|
|
|
|
if (invalidParent) {
|
|
var info = '';
|
|
if (ancestorTag === 'table' && childTag === 'tr') {
|
|
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
|
|
}
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined;
|
|
} else {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined;
|
|
}
|
|
}
|
|
};
|
|
|
|
validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2);
|
|
|
|
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
|
|
|
|
// For testing
|
|
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
|
|
ancestorInfo = ancestorInfo || emptyAncestorInfo;
|
|
var parentInfo = ancestorInfo.parentTag;
|
|
var parentTag = parentInfo && parentInfo.tag;
|
|
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
|
|
};
|
|
}
|
|
|
|
module.exports = validateDOMNesting;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 71 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDefaultInjection
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var BeforeInputEventPlugin = __webpack_require__(72);
|
|
var ChangeEventPlugin = __webpack_require__(80);
|
|
var ClientReactRootIndex = __webpack_require__(83);
|
|
var DefaultEventPluginOrder = __webpack_require__(84);
|
|
var EnterLeaveEventPlugin = __webpack_require__(85);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var HTMLDOMPropertyConfig = __webpack_require__(89);
|
|
var ReactBrowserComponentMixin = __webpack_require__(90);
|
|
var ReactComponentBrowserEnvironment = __webpack_require__(26);
|
|
var ReactDefaultBatchingStrategy = __webpack_require__(92);
|
|
var ReactDOMComponent = __webpack_require__(93);
|
|
var ReactDOMTextComponent = __webpack_require__(6);
|
|
var ReactEventListener = __webpack_require__(118);
|
|
var ReactInjection = __webpack_require__(121);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactReconcileTransaction = __webpack_require__(125);
|
|
var SelectEventPlugin = __webpack_require__(130);
|
|
var ServerReactRootIndex = __webpack_require__(131);
|
|
var SimpleEventPlugin = __webpack_require__(132);
|
|
var SVGDOMPropertyConfig = __webpack_require__(141);
|
|
|
|
var alreadyInjected = false;
|
|
|
|
function inject() {
|
|
if (alreadyInjected) {
|
|
// TODO: This is currently true because these injections are shared between
|
|
// the client and the server package. They should be built independently
|
|
// and not share any injection state. Then this problem will be solved.
|
|
return;
|
|
}
|
|
alreadyInjected = true;
|
|
|
|
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
|
|
|
|
/**
|
|
* Inject modules for resolving DOM hierarchy and plugin ordering.
|
|
*/
|
|
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
|
|
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
|
|
ReactInjection.EventPluginHub.injectMount(ReactMount);
|
|
|
|
/**
|
|
* Some important event plugins included by default (without having to require
|
|
* them).
|
|
*/
|
|
ReactInjection.EventPluginHub.injectEventPluginsByName({
|
|
SimpleEventPlugin: SimpleEventPlugin,
|
|
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
|
|
ChangeEventPlugin: ChangeEventPlugin,
|
|
SelectEventPlugin: SelectEventPlugin,
|
|
BeforeInputEventPlugin: BeforeInputEventPlugin
|
|
});
|
|
|
|
ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent);
|
|
|
|
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent);
|
|
|
|
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
|
|
|
|
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
|
|
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
|
|
|
|
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
|
|
|
|
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
|
|
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
|
|
|
|
ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex);
|
|
|
|
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
|
|
if (/[?&]react_perf\b/.test(url)) {
|
|
var ReactDefaultPerf = __webpack_require__(142);
|
|
ReactDefaultPerf.start();
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
inject: inject
|
|
};
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 72 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015 Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule BeforeInputEventPlugin
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPropagators = __webpack_require__(73);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var FallbackCompositionState = __webpack_require__(74);
|
|
var SyntheticCompositionEvent = __webpack_require__(76);
|
|
var SyntheticInputEvent = __webpack_require__(78);
|
|
|
|
var keyOf = __webpack_require__(79);
|
|
|
|
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
|
|
var START_KEYCODE = 229;
|
|
|
|
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
|
|
|
|
var documentMode = null;
|
|
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
|
|
documentMode = document.documentMode;
|
|
}
|
|
|
|
// Webkit offers a very useful `textInput` event that can be used to
|
|
// directly represent `beforeInput`. The IE `textinput` event is not as
|
|
// useful, so we don't use it.
|
|
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
|
|
|
|
// In IE9+, we have access to composition events, but the data supplied
|
|
// by the native compositionend event may be incorrect. Japanese ideographic
|
|
// spaces, for instance (\u3000) are not recorded correctly.
|
|
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
|
|
|
|
/**
|
|
* Opera <= 12 includes TextEvent in window, but does not fire
|
|
* text input events. Rely on keypress instead.
|
|
*/
|
|
function isPresto() {
|
|
var opera = window.opera;
|
|
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
|
|
}
|
|
|
|
var SPACEBAR_CODE = 32;
|
|
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
|
|
// Events and their corresponding property names.
|
|
var eventTypes = {
|
|
beforeInput: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onBeforeInput: null }),
|
|
captured: keyOf({ onBeforeInputCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
|
|
},
|
|
compositionEnd: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCompositionEnd: null }),
|
|
captured: keyOf({ onCompositionEndCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
|
|
},
|
|
compositionStart: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCompositionStart: null }),
|
|
captured: keyOf({ onCompositionStartCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
|
|
},
|
|
compositionUpdate: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCompositionUpdate: null }),
|
|
captured: keyOf({ onCompositionUpdateCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.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 topLevelTypes.topCompositionStart:
|
|
return eventTypes.compositionStart;
|
|
case topLevelTypes.topCompositionEnd:
|
|
return eventTypes.compositionEnd;
|
|
case topLevelTypes.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 === topLevelTypes.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 topLevelTypes.topKeyUp:
|
|
// Command keys insert or clear IME input.
|
|
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
|
|
case topLevelTypes.topKeyDown:
|
|
// Expect IME keyCode on each keydown. If we get any other
|
|
// code we must have exited earlier.
|
|
return nativeEvent.keyCode !== START_KEYCODE;
|
|
case topLevelTypes.topKeyPress:
|
|
case topLevelTypes.topMouseDown:
|
|
case topLevelTypes.topBlur:
|
|
// Events are not possible without cancelling IME.
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Google Input Tools provides composition data via a CustomEvent,
|
|
* with the `data` property populated in the `detail` object. If this
|
|
* is available on the event object, use it. If not, this is a plain
|
|
* composition event and we have nothing special to extract.
|
|
*
|
|
* @param {object} nativeEvent
|
|
* @return {?string}
|
|
*/
|
|
function getDataFromCustomEvent(nativeEvent) {
|
|
var detail = nativeEvent.detail;
|
|
if (typeof detail === 'object' && 'data' in detail) {
|
|
return detail.data;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Track the current IME composition fallback object, if any.
|
|
var currentComposition = null;
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {?object} A SyntheticCompositionEvent.
|
|
*/
|
|
function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
var eventType;
|
|
var fallbackData;
|
|
|
|
if (canUseCompositionEvent) {
|
|
eventType = getCompositionEventType(topLevelType);
|
|
} else if (!currentComposition) {
|
|
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
|
|
eventType = eventTypes.compositionStart;
|
|
}
|
|
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
|
|
eventType = eventTypes.compositionEnd;
|
|
}
|
|
|
|
if (!eventType) {
|
|
return null;
|
|
}
|
|
|
|
if (useFallbackCompositionData) {
|
|
// The current composition is stored statically and must not be
|
|
// overwritten while composition continues.
|
|
if (!currentComposition && eventType === eventTypes.compositionStart) {
|
|
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
|
|
} else if (eventType === eventTypes.compositionEnd) {
|
|
if (currentComposition) {
|
|
fallbackData = currentComposition.getData();
|
|
}
|
|
}
|
|
}
|
|
|
|
var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget);
|
|
|
|
if (fallbackData) {
|
|
// Inject data generated from fallback path into the synthetic event.
|
|
// This matches the property of native CompositionEventInterface.
|
|
event.data = fallbackData;
|
|
} else {
|
|
var customData = getDataFromCustomEvent(nativeEvent);
|
|
if (customData !== null) {
|
|
event.data = customData;
|
|
}
|
|
}
|
|
|
|
EventPropagators.accumulateTwoPhaseDispatches(event);
|
|
return event;
|
|
}
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {?string} The string corresponding to this `beforeInput` event.
|
|
*/
|
|
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
|
|
switch (topLevelType) {
|
|
case topLevelTypes.topCompositionEnd:
|
|
return getDataFromCustomEvent(nativeEvent);
|
|
case topLevelTypes.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 topLevelTypes.topTextInput:
|
|
// Record the characters to be added to the DOM.
|
|
var chars = nativeEvent.data;
|
|
|
|
// If it's a spacebar character, assume that we have already handled
|
|
// it at the keypress level and bail immediately. Android Chrome
|
|
// doesn't give us keycodes, so we need to blacklist it.
|
|
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
|
|
return null;
|
|
}
|
|
|
|
return chars;
|
|
|
|
default:
|
|
// For other native event types, do nothing.
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* For browsers that do not provide the `textInput` event, extract the
|
|
* appropriate string to use for SyntheticInputEvent.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {?string} The fallback string for this `beforeInput` event.
|
|
*/
|
|
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
|
|
// If we are currently composing (IME) and using a fallback to do so,
|
|
// try to extract the composed characters from the fallback object.
|
|
if (currentComposition) {
|
|
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
|
|
var chars = currentComposition.getData();
|
|
FallbackCompositionState.release(currentComposition);
|
|
currentComposition = null;
|
|
return chars;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
switch (topLevelType) {
|
|
case topLevelTypes.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 topLevelTypes.topKeyPress:
|
|
/**
|
|
* As of v27, Firefox may fire keypress events even when no character
|
|
* will be inserted. A few possibilities:
|
|
*
|
|
* - `which` is `0`. Arrow keys, Esc key, etc.
|
|
*
|
|
* - `which` is the pressed key code, but no char is available.
|
|
* Ex: 'AltGr + d` in Polish. There is no modified character for
|
|
* this key combination and no character is inserted into the
|
|
* document, but FF fires the keypress for char code `100` anyway.
|
|
* No `input` event will occur.
|
|
*
|
|
* - `which` is the pressed key code, but a command combination is
|
|
* being used. Ex: `Cmd+C`. No character is inserted, and no
|
|
* `input` event will occur.
|
|
*/
|
|
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
|
|
return String.fromCharCode(nativeEvent.which);
|
|
}
|
|
return null;
|
|
case topLevelTypes.topCompositionEnd:
|
|
return useFallbackCompositionData ? null : nativeEvent.data;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
|
|
* `textInput` or fallback behavior.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {?object} A SyntheticInputEvent.
|
|
*/
|
|
function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
var chars;
|
|
|
|
if (canUseTextInputEvent) {
|
|
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
|
|
} else {
|
|
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
|
|
}
|
|
|
|
// If no characters are being inserted, no BeforeInput event should
|
|
// be fired.
|
|
if (!chars) {
|
|
return null;
|
|
}
|
|
|
|
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget);
|
|
|
|
event.data = chars;
|
|
EventPropagators.accumulateTwoPhaseDispatches(event);
|
|
return event;
|
|
}
|
|
|
|
/**
|
|
* Create an `onBeforeInput` event to match
|
|
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
|
|
*
|
|
* This event plugin is based on the native `textInput` event
|
|
* available in Chrome, Safari, Opera, and IE. This event fires after
|
|
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
|
|
*
|
|
* `beforeInput` is spec'd but not implemented in any browsers, and
|
|
* the `input` event does not provide any useful information about what has
|
|
* actually been added, contrary to the spec. Thus, `textInput` is the best
|
|
* available event to identify the characters that have actually been inserted
|
|
* into the target node.
|
|
*
|
|
* This plugin is also responsible for emitting `composition` events, thus
|
|
* allowing us to share composition fallback code for both `beforeInput` and
|
|
* `composition` event types.
|
|
*/
|
|
var BeforeInputEventPlugin = {
|
|
|
|
eventTypes: eventTypes,
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @see {EventPluginHub.extractEvents}
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)];
|
|
}
|
|
};
|
|
|
|
module.exports = BeforeInputEventPlugin;
|
|
|
|
/***/ }),
|
|
/* 73 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EventPropagators
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPluginHub = __webpack_require__(31);
|
|
|
|
var warning = __webpack_require__(25);
|
|
|
|
var accumulateInto = __webpack_require__(35);
|
|
var forEachAccumulated = __webpack_require__(36);
|
|
|
|
var PropagationPhases = EventConstants.PropagationPhases;
|
|
var getListener = EventPluginHub.getListener;
|
|
|
|
/**
|
|
* Some event types have a notion of different registration names for different
|
|
* "phases" of propagation. This finds listeners by a given phase.
|
|
*/
|
|
function listenerAtPhase(id, event, propagationPhase) {
|
|
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
|
|
return getListener(id, registrationName);
|
|
}
|
|
|
|
/**
|
|
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
|
|
* here, allows us to not have to bind or create functions for each event.
|
|
* Mutating the event's members allows us to not have to create a wrapping
|
|
* "dispatch" object that pairs the event with the listener.
|
|
*/
|
|
function accumulateDirectionalDispatches(domID, upwards, event) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined;
|
|
}
|
|
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
|
|
var listener = listenerAtPhase(domID, event, phase);
|
|
if (listener) {
|
|
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
|
|
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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) {
|
|
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
|
|
*/
|
|
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
|
|
if (event && event.dispatchConfig.phasedRegistrationNames) {
|
|
EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, 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(id, ignoredDirection, event) {
|
|
if (event && event.dispatchConfig.registrationName) {
|
|
var registrationName = event.dispatchConfig.registrationName;
|
|
var listener = getListener(id, registrationName);
|
|
if (listener) {
|
|
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
|
|
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Accumulates dispatches on an `SyntheticEvent`, but only for the
|
|
* `dispatchMarker`.
|
|
* @param {SyntheticEvent} event
|
|
*/
|
|
function accumulateDirectDispatchesSingle(event) {
|
|
if (event && event.dispatchConfig.registrationName) {
|
|
accumulateDispatches(event.dispatchMarker, null, event);
|
|
}
|
|
}
|
|
|
|
function accumulateTwoPhaseDispatches(events) {
|
|
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
|
|
}
|
|
|
|
function accumulateTwoPhaseDispatchesSkipTarget(events) {
|
|
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
|
|
}
|
|
|
|
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
|
|
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter);
|
|
}
|
|
|
|
function accumulateDirectDispatches(events) {
|
|
forEachAccumulated(events, accumulateDirectDispatchesSingle);
|
|
}
|
|
|
|
/**
|
|
* A small set of propagation patterns, each of which will accept a small amount
|
|
* of information, and generate a set of "dispatch ready event objects" - which
|
|
* are sets of events that have already been annotated with a set of dispatched
|
|
* listener functions/ids. The API is designed this way to discourage these
|
|
* propagation strategies from actually executing the dispatches, since we
|
|
* always want to collect the entire set of dispatches before executing event a
|
|
* single one.
|
|
*
|
|
* @constructor EventPropagators
|
|
*/
|
|
var EventPropagators = {
|
|
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
|
|
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
|
|
accumulateDirectDispatches: accumulateDirectDispatches,
|
|
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
|
|
};
|
|
|
|
module.exports = EventPropagators;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 74 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule FallbackCompositionState
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var PooledClass = __webpack_require__(56);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var getTextContentAccessor = __webpack_require__(75);
|
|
|
|
/**
|
|
* This helper class stores information about text content of a target node,
|
|
* allowing comparison of content before and after a given event.
|
|
*
|
|
* Identify the node where selection currently begins, then observe
|
|
* both its text content and its current position in the DOM. Since the
|
|
* browser may natively replace the target node during composition, we can
|
|
* use its position to find its replacement.
|
|
*
|
|
* @param {DOMEventTarget} root
|
|
*/
|
|
function FallbackCompositionState(root) {
|
|
this._root = root;
|
|
this._startText = this.getText();
|
|
this._fallbackText = null;
|
|
}
|
|
|
|
assign(FallbackCompositionState.prototype, {
|
|
destructor: function () {
|
|
this._root = null;
|
|
this._startText = null;
|
|
this._fallbackText = null;
|
|
},
|
|
|
|
/**
|
|
* Get current text of input.
|
|
*
|
|
* @return {string}
|
|
*/
|
|
getText: function () {
|
|
if ('value' in this._root) {
|
|
return this._root.value;
|
|
}
|
|
return this._root[getTextContentAccessor()];
|
|
},
|
|
|
|
/**
|
|
* Determine the differing substring between the initially stored
|
|
* text content and the current content.
|
|
*
|
|
* @return {string}
|
|
*/
|
|
getData: function () {
|
|
if (this._fallbackText) {
|
|
return this._fallbackText;
|
|
}
|
|
|
|
var start;
|
|
var startValue = this._startText;
|
|
var startLength = startValue.length;
|
|
var end;
|
|
var endValue = this.getText();
|
|
var endLength = endValue.length;
|
|
|
|
for (start = 0; start < startLength; start++) {
|
|
if (startValue[start] !== endValue[start]) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
var minEnd = startLength - start;
|
|
for (end = 1; end <= minEnd; end++) {
|
|
if (startValue[startLength - end] !== endValue[endLength - end]) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
var sliceTail = end > 1 ? 1 - end : undefined;
|
|
this._fallbackText = endValue.slice(start, sliceTail);
|
|
return this._fallbackText;
|
|
}
|
|
});
|
|
|
|
PooledClass.addPoolingTo(FallbackCompositionState);
|
|
|
|
module.exports = FallbackCompositionState;
|
|
|
|
/***/ }),
|
|
/* 75 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getTextContentAccessor
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
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 <text> elements don't support innerText even when <div> does.
|
|
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
|
|
}
|
|
return contentKey;
|
|
}
|
|
|
|
module.exports = getTextContentAccessor;
|
|
|
|
/***/ }),
|
|
/* 76 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticCompositionEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
/**
|
|
* @interface Event
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
|
|
*/
|
|
var CompositionEventInterface = {
|
|
data: null
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
|
|
|
|
module.exports = SyntheticCompositionEvent;
|
|
|
|
/***/ }),
|
|
/* 77 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var PooledClass = __webpack_require__(56);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyFunction = __webpack_require__(15);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* @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 {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
*/
|
|
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
this.dispatchConfig = dispatchConfig;
|
|
this.dispatchMarker = dispatchMarker;
|
|
this.nativeEvent = nativeEvent;
|
|
|
|
var Interface = this.constructor.Interface;
|
|
for (var propName in Interface) {
|
|
if (!Interface.hasOwnProperty(propName)) {
|
|
continue;
|
|
}
|
|
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;
|
|
}
|
|
|
|
assign(SyntheticEvent.prototype, {
|
|
|
|
preventDefault: function () {
|
|
this.defaultPrevented = true;
|
|
var event = this.nativeEvent;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
|
|
}
|
|
if (!event) {
|
|
return;
|
|
}
|
|
|
|
if (event.preventDefault) {
|
|
event.preventDefault();
|
|
} else {
|
|
event.returnValue = false;
|
|
}
|
|
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
|
|
},
|
|
|
|
stopPropagation: function () {
|
|
var event = this.nativeEvent;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
|
|
}
|
|
if (!event) {
|
|
return;
|
|
}
|
|
|
|
if (event.stopPropagation) {
|
|
event.stopPropagation();
|
|
} else {
|
|
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) {
|
|
this[propName] = null;
|
|
}
|
|
this.dispatchConfig = null;
|
|
this.dispatchMarker = null;
|
|
this.nativeEvent = null;
|
|
}
|
|
|
|
});
|
|
|
|
SyntheticEvent.Interface = EventInterface;
|
|
|
|
/**
|
|
* Helper to reduce boilerplate when creating subclasses.
|
|
*
|
|
* @param {function} Class
|
|
* @param {?object} Interface
|
|
*/
|
|
SyntheticEvent.augmentClass = function (Class, Interface) {
|
|
var Super = this;
|
|
|
|
var prototype = Object.create(Super.prototype);
|
|
assign(prototype, Class.prototype);
|
|
Class.prototype = prototype;
|
|
Class.prototype.constructor = Class;
|
|
|
|
Class.Interface = assign({}, Super.Interface, Interface);
|
|
Class.augmentClass = Super.augmentClass;
|
|
|
|
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
|
|
};
|
|
|
|
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
|
|
|
|
module.exports = SyntheticEvent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 78 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticInputEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
/**
|
|
* @interface Event
|
|
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
|
|
* /#events-inputevents
|
|
*/
|
|
var InputEventInterface = {
|
|
data: null
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
|
|
|
|
module.exports = SyntheticInputEvent;
|
|
|
|
/***/ }),
|
|
/* 79 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule keyOf
|
|
*/
|
|
|
|
/**
|
|
* Allows extraction of a minified key. Let's the build system minify keys
|
|
* without losing the ability to dynamically use key strings as values
|
|
* themselves. Pass in an object with a single key/val pair and it will return
|
|
* you the string key of that single record. Suppose you want to grab the
|
|
* value for a key 'className' inside of an object. Key/val minification may
|
|
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
|
|
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
|
|
* reuse those resolutions.
|
|
*/
|
|
"use strict";
|
|
|
|
var keyOf = function (oneKeyObj) {
|
|
var key;
|
|
for (key in oneKeyObj) {
|
|
if (!oneKeyObj.hasOwnProperty(key)) {
|
|
continue;
|
|
}
|
|
return key;
|
|
}
|
|
return null;
|
|
};
|
|
|
|
module.exports = keyOf;
|
|
|
|
/***/ }),
|
|
/* 80 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ChangeEventPlugin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPluginHub = __webpack_require__(31);
|
|
var EventPropagators = __webpack_require__(73);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
var getEventTarget = __webpack_require__(81);
|
|
var isEventSupported = __webpack_require__(40);
|
|
var isTextInputElement = __webpack_require__(82);
|
|
var keyOf = __webpack_require__(79);
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
|
|
var eventTypes = {
|
|
change: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onChange: null }),
|
|
captured: keyOf({ onChangeCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
|
|
}
|
|
};
|
|
|
|
/**
|
|
* For IE shims
|
|
*/
|
|
var activeElement = null;
|
|
var activeElementID = null;
|
|
var activeElementValue = null;
|
|
var activeElementValueProp = null;
|
|
|
|
/**
|
|
* SECTION: handle `change` event
|
|
*/
|
|
function shouldUseChangeEvent(elem) {
|
|
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
|
|
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
|
|
}
|
|
|
|
var doesChangeEventBubble = false;
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
// See `handleChange` comment below
|
|
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
|
|
}
|
|
|
|
function manualDispatchChangeEvent(nativeEvent) {
|
|
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent));
|
|
EventPropagators.accumulateTwoPhaseDispatches(event);
|
|
|
|
// If change and propertychange bubbled, we'd just bind to it like all the
|
|
// other events and have it go through ReactBrowserEventEmitter. Since it
|
|
// doesn't, we manually listen for the events and so we have to enqueue and
|
|
// process the abstract event manually.
|
|
//
|
|
// Batching is necessary here in order to ensure that all event handlers run
|
|
// before the next rerender (including event handlers attached to ancestor
|
|
// elements instead of directly on the input). Without this, controlled
|
|
// components don't work properly in conjunction with event bubbling because
|
|
// the component is rerendered and the value reverted before all the event
|
|
// handlers can run. See https://github.com/facebook/react/issues/708.
|
|
ReactUpdates.batchedUpdates(runEventInBatch, event);
|
|
}
|
|
|
|
function runEventInBatch(event) {
|
|
EventPluginHub.enqueueEvents(event);
|
|
EventPluginHub.processEventQueue(false);
|
|
}
|
|
|
|
function startWatchingForChangeEventIE8(target, targetID) {
|
|
activeElement = target;
|
|
activeElementID = targetID;
|
|
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
|
|
}
|
|
|
|
function stopWatchingForChangeEventIE8() {
|
|
if (!activeElement) {
|
|
return;
|
|
}
|
|
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
|
|
activeElement = null;
|
|
activeElementID = null;
|
|
}
|
|
|
|
function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topChange) {
|
|
return topLevelTargetID;
|
|
}
|
|
}
|
|
function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topFocus) {
|
|
// stopWatching() should be a noop here but we call it just in case we
|
|
// missed a blur event somehow.
|
|
stopWatchingForChangeEventIE8();
|
|
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
|
|
} else if (topLevelType === topLevelTypes.topBlur) {
|
|
stopWatchingForChangeEventIE8();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* SECTION: handle `input` event
|
|
*/
|
|
var isInputEventSupported = false;
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
// IE9 claims to support the input event but fails to trigger it when
|
|
// deleting text, so we ignore its input events
|
|
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9);
|
|
}
|
|
|
|
/**
|
|
* (For old IE.) Replacement getter/setter for the `value` property that gets
|
|
* set on the active element.
|
|
*/
|
|
var newValueProp = {
|
|
get: function () {
|
|
return activeElementValueProp.get.call(this);
|
|
},
|
|
set: function (val) {
|
|
// Cast to a string so we can do equality checks.
|
|
activeElementValue = '' + val;
|
|
activeElementValueProp.set.call(this, val);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* (For old IE.) 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, targetID) {
|
|
activeElement = target;
|
|
activeElementID = targetID;
|
|
activeElementValue = target.value;
|
|
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
|
|
|
|
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
|
|
// on DOM elements
|
|
Object.defineProperty(activeElement, 'value', newValueProp);
|
|
activeElement.attachEvent('onpropertychange', handlePropertyChange);
|
|
}
|
|
|
|
/**
|
|
* (For old IE.) Removes the event listeners from the currently-tracked element,
|
|
* if any exists.
|
|
*/
|
|
function stopWatchingForValueChange() {
|
|
if (!activeElement) {
|
|
return;
|
|
}
|
|
|
|
// delete restores the original property definition
|
|
delete activeElement.value;
|
|
activeElement.detachEvent('onpropertychange', handlePropertyChange);
|
|
|
|
activeElement = null;
|
|
activeElementID = null;
|
|
activeElementValue = null;
|
|
activeElementValueProp = null;
|
|
}
|
|
|
|
/**
|
|
* (For old IE.) Handles a propertychange event, sending a `change` event if
|
|
* the value of the active element has changed.
|
|
*/
|
|
function handlePropertyChange(nativeEvent) {
|
|
if (nativeEvent.propertyName !== 'value') {
|
|
return;
|
|
}
|
|
var value = nativeEvent.srcElement.value;
|
|
if (value === activeElementValue) {
|
|
return;
|
|
}
|
|
activeElementValue = value;
|
|
|
|
manualDispatchChangeEvent(nativeEvent);
|
|
}
|
|
|
|
/**
|
|
* If a `change` event should be fired, returns the target's ID.
|
|
*/
|
|
function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topInput) {
|
|
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
|
|
// what we want so fall through here and trigger an abstract event
|
|
return topLevelTargetID;
|
|
}
|
|
}
|
|
|
|
// For IE8 and IE9.
|
|
function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topFocus) {
|
|
// In IE8, we can capture almost all .value changes by adding a
|
|
// propertychange handler and looking for events with propertyName
|
|
// equal to 'value'
|
|
// In IE9, 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(topLevelTarget, topLevelTargetID);
|
|
} else if (topLevelType === topLevelTypes.topBlur) {
|
|
stopWatchingForValueChange();
|
|
}
|
|
}
|
|
|
|
// For IE8 and IE9.
|
|
function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
|
|
// On the selectionchange event, the target is just document which isn't
|
|
// helpful for us so just check activeElement instead.
|
|
//
|
|
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
|
|
// propertychange on the first input event after setting `value` from a
|
|
// script and fires only keydown, keypress, keyup. Catching keyup usually
|
|
// gets it and catching keydown lets us fire an event for the first
|
|
// keystroke if user does a key repeat (it'll be a little delayed: right
|
|
// before the second keystroke). Other input methods (e.g., paste) seem to
|
|
// fire selectionchange normally.
|
|
if (activeElement && activeElement.value !== activeElementValue) {
|
|
activeElementValue = activeElement.value;
|
|
return activeElementID;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* SECTION: handle `click` event
|
|
*/
|
|
function shouldUseClickEvent(elem) {
|
|
// Use the `click` event to detect changes to checkbox and radio inputs.
|
|
// This approach works across all browsers, whereas `change` does not fire
|
|
// until `blur` in IE8.
|
|
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
|
|
}
|
|
|
|
function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) {
|
|
if (topLevelType === topLevelTypes.topClick) {
|
|
return topLevelTargetID;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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,
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @see {EventPluginHub.extractEvents}
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
|
|
var getTargetIDFunc, handleEventFunc;
|
|
if (shouldUseChangeEvent(topLevelTarget)) {
|
|
if (doesChangeEventBubble) {
|
|
getTargetIDFunc = getTargetIDForChangeEvent;
|
|
} else {
|
|
handleEventFunc = handleEventsForChangeEventIE8;
|
|
}
|
|
} else if (isTextInputElement(topLevelTarget)) {
|
|
if (isInputEventSupported) {
|
|
getTargetIDFunc = getTargetIDForInputEvent;
|
|
} else {
|
|
getTargetIDFunc = getTargetIDForInputEventIE;
|
|
handleEventFunc = handleEventsForInputEventIE;
|
|
}
|
|
} else if (shouldUseClickEvent(topLevelTarget)) {
|
|
getTargetIDFunc = getTargetIDForClickEvent;
|
|
}
|
|
|
|
if (getTargetIDFunc) {
|
|
var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID);
|
|
if (targetID) {
|
|
var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget);
|
|
event.type = 'change';
|
|
EventPropagators.accumulateTwoPhaseDispatches(event);
|
|
return event;
|
|
}
|
|
}
|
|
|
|
if (handleEventFunc) {
|
|
handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID);
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ChangeEventPlugin;
|
|
|
|
/***/ }),
|
|
/* 81 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getEventTarget
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Gets the target node from a native browser event by accounting for
|
|
* inconsistencies in browser DOM APIs.
|
|
*
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {DOMEventTarget} Target node.
|
|
*/
|
|
function getEventTarget(nativeEvent) {
|
|
var target = nativeEvent.target || nativeEvent.srcElement || window;
|
|
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
|
|
// @see http://www.quirksmode.org/js/events_properties.html
|
|
return target.nodeType === 3 ? target.parentNode : target;
|
|
}
|
|
|
|
module.exports = getEventTarget;
|
|
|
|
/***/ }),
|
|
/* 82 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule isTextInputElement
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* @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();
|
|
return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea');
|
|
}
|
|
|
|
module.exports = isTextInputElement;
|
|
|
|
/***/ }),
|
|
/* 83 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ClientReactRootIndex
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var nextReactRootIndex = 0;
|
|
|
|
var ClientReactRootIndex = {
|
|
createReactRootIndex: function () {
|
|
return nextReactRootIndex++;
|
|
}
|
|
};
|
|
|
|
module.exports = ClientReactRootIndex;
|
|
|
|
/***/ }),
|
|
/* 84 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule DefaultEventPluginOrder
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var keyOf = __webpack_require__(79);
|
|
|
|
/**
|
|
* 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 DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
|
|
|
|
module.exports = DefaultEventPluginOrder;
|
|
|
|
/***/ }),
|
|
/* 85 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule EnterLeaveEventPlugin
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPropagators = __webpack_require__(73);
|
|
var SyntheticMouseEvent = __webpack_require__(86);
|
|
|
|
var ReactMount = __webpack_require__(28);
|
|
var keyOf = __webpack_require__(79);
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
var getFirstReactDOM = ReactMount.getFirstReactDOM;
|
|
|
|
var eventTypes = {
|
|
mouseEnter: {
|
|
registrationName: keyOf({ onMouseEnter: null }),
|
|
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
|
|
},
|
|
mouseLeave: {
|
|
registrationName: keyOf({ onMouseLeave: null }),
|
|
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
|
|
}
|
|
};
|
|
|
|
var extractedEvents = [null, null];
|
|
|
|
var EnterLeaveEventPlugin = {
|
|
|
|
eventTypes: eventTypes,
|
|
|
|
/**
|
|
* 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.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @see {EventPluginHub.extractEvents}
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
|
|
return null;
|
|
}
|
|
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
|
|
// Must not be a mouse in or mouse out - ignoring.
|
|
return null;
|
|
}
|
|
|
|
var win;
|
|
if (topLevelTarget.window === topLevelTarget) {
|
|
// `topLevelTarget` is probably a window object.
|
|
win = topLevelTarget;
|
|
} else {
|
|
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
|
|
var doc = topLevelTarget.ownerDocument;
|
|
if (doc) {
|
|
win = doc.defaultView || doc.parentWindow;
|
|
} else {
|
|
win = window;
|
|
}
|
|
}
|
|
|
|
var from;
|
|
var to;
|
|
var fromID = '';
|
|
var toID = '';
|
|
if (topLevelType === topLevelTypes.topMouseOut) {
|
|
from = topLevelTarget;
|
|
fromID = topLevelTargetID;
|
|
to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement);
|
|
if (to) {
|
|
toID = ReactMount.getID(to);
|
|
} else {
|
|
to = win;
|
|
}
|
|
to = to || win;
|
|
} else {
|
|
from = win;
|
|
to = topLevelTarget;
|
|
toID = topLevelTargetID;
|
|
}
|
|
|
|
if (from === to) {
|
|
// Nothing pertains to our managed components.
|
|
return null;
|
|
}
|
|
|
|
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget);
|
|
leave.type = 'mouseleave';
|
|
leave.target = from;
|
|
leave.relatedTarget = to;
|
|
|
|
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget);
|
|
enter.type = 'mouseenter';
|
|
enter.target = to;
|
|
enter.relatedTarget = from;
|
|
|
|
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
|
|
|
|
extractedEvents[0] = leave;
|
|
extractedEvents[1] = enter;
|
|
|
|
return extractedEvents;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = EnterLeaveEventPlugin;
|
|
|
|
/***/ }),
|
|
/* 86 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticMouseEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticUIEvent = __webpack_require__(87);
|
|
var ViewportMetrics = __webpack_require__(38);
|
|
|
|
var getEventModifierState = __webpack_require__(88);
|
|
|
|
/**
|
|
* @interface MouseEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var MouseEventInterface = {
|
|
screenX: null,
|
|
screenY: null,
|
|
clientX: null,
|
|
clientY: null,
|
|
ctrlKey: null,
|
|
shiftKey: null,
|
|
altKey: null,
|
|
metaKey: null,
|
|
getModifierState: getEventModifierState,
|
|
button: function (event) {
|
|
// Webkit, Firefox, IE9+
|
|
// which: 1 2 3
|
|
// button: 0 1 2 (standard)
|
|
var button = event.button;
|
|
if ('which' in event) {
|
|
return button;
|
|
}
|
|
// IE<9
|
|
// which: undefined
|
|
// button: 0 0 0
|
|
// button: 1 4 2 (onmouseup)
|
|
return button === 2 ? 2 : button === 4 ? 1 : 0;
|
|
},
|
|
buttons: null,
|
|
relatedTarget: function (event) {
|
|
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
|
|
},
|
|
// "Proprietary" Interface.
|
|
pageX: function (event) {
|
|
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
|
|
},
|
|
pageY: function (event) {
|
|
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
|
|
|
|
module.exports = SyntheticMouseEvent;
|
|
|
|
/***/ }),
|
|
/* 87 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticUIEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
var getEventTarget = __webpack_require__(81);
|
|
|
|
/**
|
|
* @interface UIEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var UIEventInterface = {
|
|
view: function (event) {
|
|
if (event.view) {
|
|
return event.view;
|
|
}
|
|
|
|
var target = getEventTarget(event);
|
|
if (target != null && target.window === target) {
|
|
// target is a window object
|
|
return target;
|
|
}
|
|
|
|
var doc = target.ownerDocument;
|
|
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
|
|
if (doc) {
|
|
return doc.defaultView || doc.parentWindow;
|
|
} else {
|
|
return window;
|
|
}
|
|
},
|
|
detail: function (event) {
|
|
return event.detail || 0;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticEvent}
|
|
*/
|
|
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
|
|
|
|
module.exports = SyntheticUIEvent;
|
|
|
|
/***/ }),
|
|
/* 88 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getEventModifierState
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
|
|
module.exports = getEventModifierState;
|
|
|
|
/***/ }),
|
|
/* 89 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule HTMLDOMPropertyConfig
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
|
|
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
|
|
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
|
|
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
|
|
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
|
|
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
|
|
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
|
|
|
|
var hasSVG;
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
var implementation = document.implementation;
|
|
hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
|
|
}
|
|
|
|
var HTMLDOMPropertyConfig = {
|
|
isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),
|
|
Properties: {
|
|
/**
|
|
* Standard Properties
|
|
*/
|
|
accept: null,
|
|
acceptCharset: null,
|
|
accessKey: null,
|
|
action: null,
|
|
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
allowTransparency: MUST_USE_ATTRIBUTE,
|
|
alt: null,
|
|
async: HAS_BOOLEAN_VALUE,
|
|
autoComplete: null,
|
|
// autoFocus is polyfilled/normalized by AutoFocusUtils
|
|
// autoFocus: HAS_BOOLEAN_VALUE,
|
|
autoPlay: HAS_BOOLEAN_VALUE,
|
|
capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
cellPadding: null,
|
|
cellSpacing: null,
|
|
charSet: MUST_USE_ATTRIBUTE,
|
|
challenge: MUST_USE_ATTRIBUTE,
|
|
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
classID: MUST_USE_ATTRIBUTE,
|
|
// To set className on SVG elements, it's necessary to use .setAttribute;
|
|
// this works on HTML elements too in all browsers except IE8. Conveniently,
|
|
// IE8 doesn't support SVG and so we can simply use the attribute in
|
|
// browsers that support SVG and the property in browsers that don't,
|
|
// regardless of whether the element is HTML or SVG.
|
|
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
|
|
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
|
|
colSpan: null,
|
|
content: null,
|
|
contentEditable: null,
|
|
contextMenu: MUST_USE_ATTRIBUTE,
|
|
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
coords: null,
|
|
crossOrigin: null,
|
|
data: null, // For `<object />` acts as `src`.
|
|
dateTime: MUST_USE_ATTRIBUTE,
|
|
'default': HAS_BOOLEAN_VALUE,
|
|
defer: HAS_BOOLEAN_VALUE,
|
|
dir: null,
|
|
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
download: HAS_OVERLOADED_BOOLEAN_VALUE,
|
|
draggable: null,
|
|
encType: null,
|
|
form: MUST_USE_ATTRIBUTE,
|
|
formAction: MUST_USE_ATTRIBUTE,
|
|
formEncType: MUST_USE_ATTRIBUTE,
|
|
formMethod: MUST_USE_ATTRIBUTE,
|
|
formNoValidate: HAS_BOOLEAN_VALUE,
|
|
formTarget: MUST_USE_ATTRIBUTE,
|
|
frameBorder: MUST_USE_ATTRIBUTE,
|
|
headers: null,
|
|
height: MUST_USE_ATTRIBUTE,
|
|
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
high: null,
|
|
href: null,
|
|
hrefLang: null,
|
|
htmlFor: null,
|
|
httpEquiv: null,
|
|
icon: null,
|
|
id: MUST_USE_PROPERTY,
|
|
inputMode: MUST_USE_ATTRIBUTE,
|
|
integrity: null,
|
|
is: MUST_USE_ATTRIBUTE,
|
|
keyParams: MUST_USE_ATTRIBUTE,
|
|
keyType: MUST_USE_ATTRIBUTE,
|
|
kind: null,
|
|
label: null,
|
|
lang: null,
|
|
list: MUST_USE_ATTRIBUTE,
|
|
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
low: null,
|
|
manifest: MUST_USE_ATTRIBUTE,
|
|
marginHeight: null,
|
|
marginWidth: null,
|
|
max: null,
|
|
maxLength: MUST_USE_ATTRIBUTE,
|
|
media: MUST_USE_ATTRIBUTE,
|
|
mediaGroup: null,
|
|
method: null,
|
|
min: null,
|
|
minLength: MUST_USE_ATTRIBUTE,
|
|
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
name: null,
|
|
nonce: MUST_USE_ATTRIBUTE,
|
|
noValidate: HAS_BOOLEAN_VALUE,
|
|
open: HAS_BOOLEAN_VALUE,
|
|
optimum: null,
|
|
pattern: null,
|
|
placeholder: null,
|
|
poster: null,
|
|
preload: null,
|
|
radioGroup: null,
|
|
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
rel: null,
|
|
required: HAS_BOOLEAN_VALUE,
|
|
reversed: HAS_BOOLEAN_VALUE,
|
|
role: MUST_USE_ATTRIBUTE,
|
|
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
|
|
rowSpan: null,
|
|
sandbox: null,
|
|
scope: null,
|
|
scoped: HAS_BOOLEAN_VALUE,
|
|
scrolling: null,
|
|
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
|
|
shape: null,
|
|
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
|
|
sizes: MUST_USE_ATTRIBUTE,
|
|
span: HAS_POSITIVE_NUMERIC_VALUE,
|
|
spellCheck: null,
|
|
src: null,
|
|
srcDoc: MUST_USE_PROPERTY,
|
|
srcLang: null,
|
|
srcSet: MUST_USE_ATTRIBUTE,
|
|
start: HAS_NUMERIC_VALUE,
|
|
step: null,
|
|
style: null,
|
|
summary: null,
|
|
tabIndex: null,
|
|
target: null,
|
|
title: null,
|
|
type: null,
|
|
useMap: null,
|
|
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
|
|
width: MUST_USE_ATTRIBUTE,
|
|
wmode: MUST_USE_ATTRIBUTE,
|
|
wrap: null,
|
|
|
|
/**
|
|
* RDFa Properties
|
|
*/
|
|
about: MUST_USE_ATTRIBUTE,
|
|
datatype: MUST_USE_ATTRIBUTE,
|
|
inlist: MUST_USE_ATTRIBUTE,
|
|
prefix: MUST_USE_ATTRIBUTE,
|
|
// property is also supported for OpenGraph in meta tags.
|
|
property: MUST_USE_ATTRIBUTE,
|
|
resource: MUST_USE_ATTRIBUTE,
|
|
'typeof': MUST_USE_ATTRIBUTE,
|
|
vocab: MUST_USE_ATTRIBUTE,
|
|
|
|
/**
|
|
* Non-standard Properties
|
|
*/
|
|
// autoCapitalize and autoCorrect are supported in Mobile Safari for
|
|
// keyboard hints.
|
|
autoCapitalize: MUST_USE_ATTRIBUTE,
|
|
autoCorrect: MUST_USE_ATTRIBUTE,
|
|
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
|
|
autoSave: null,
|
|
// color is for Safari mask-icon link
|
|
color: null,
|
|
// itemProp, itemScope, itemType are for
|
|
// Microdata support. See http://schema.org/docs/gs.html
|
|
itemProp: MUST_USE_ATTRIBUTE,
|
|
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
|
|
itemType: MUST_USE_ATTRIBUTE,
|
|
// itemID and itemRef are for Microdata support as well but
|
|
// only specified in the the WHATWG spec document. See
|
|
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
|
|
itemID: MUST_USE_ATTRIBUTE,
|
|
itemRef: MUST_USE_ATTRIBUTE,
|
|
// results show looking glass icon and recent searches on input
|
|
// search fields in WebKit/Blink
|
|
results: null,
|
|
// IE-only attribute that specifies security restrictions on an iframe
|
|
// as an alternative to the sandbox attribute on IE<10
|
|
security: MUST_USE_ATTRIBUTE,
|
|
// IE-only attribute that controls focus behavior
|
|
unselectable: MUST_USE_ATTRIBUTE
|
|
},
|
|
DOMAttributeNames: {
|
|
acceptCharset: 'accept-charset',
|
|
className: 'class',
|
|
htmlFor: 'for',
|
|
httpEquiv: 'http-equiv'
|
|
},
|
|
DOMPropertyNames: {
|
|
autoComplete: 'autocomplete',
|
|
autoFocus: 'autofocus',
|
|
autoPlay: 'autoplay',
|
|
autoSave: 'autosave',
|
|
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
|
|
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
|
|
encType: 'encoding',
|
|
hrefLang: 'hreflang',
|
|
radioGroup: 'radiogroup',
|
|
spellCheck: 'spellcheck',
|
|
srcDoc: 'srcdoc',
|
|
srcSet: 'srcset'
|
|
}
|
|
};
|
|
|
|
module.exports = HTMLDOMPropertyConfig;
|
|
|
|
/***/ }),
|
|
/* 90 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactBrowserComponentMixin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactInstanceMap = __webpack_require__(47);
|
|
|
|
var findDOMNode = __webpack_require__(91);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var didWarnKey = '_getDOMNodeDidWarn';
|
|
|
|
var ReactBrowserComponentMixin = {
|
|
/**
|
|
* Returns the DOM node rendered by this component.
|
|
*
|
|
* @return {DOMElement} The root node of this component.
|
|
* @final
|
|
* @protected
|
|
*/
|
|
getDOMNode: function () {
|
|
process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined;
|
|
this.constructor[didWarnKey] = true;
|
|
return findDOMNode(this);
|
|
}
|
|
};
|
|
|
|
module.exports = ReactBrowserComponentMixin;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 91 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule findDOMNode
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactInstanceMap = __webpack_require__(47);
|
|
var ReactMount = __webpack_require__(28);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* Returns the DOM node rendered by this element.
|
|
*
|
|
* @param {ReactComponent|DOMElement} componentOrElement
|
|
* @return {?DOMElement} The root node of this element.
|
|
*/
|
|
function findDOMNode(componentOrElement) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var owner = ReactCurrentOwner.current;
|
|
if (owner !== null) {
|
|
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
|
|
owner._warnedAboutRefsInRender = true;
|
|
}
|
|
}
|
|
if (componentOrElement == null) {
|
|
return null;
|
|
}
|
|
if (componentOrElement.nodeType === 1) {
|
|
return componentOrElement;
|
|
}
|
|
if (ReactInstanceMap.has(componentOrElement)) {
|
|
return ReactMount.getNodeFromInstance(componentOrElement);
|
|
}
|
|
!(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
|
|
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
|
|
}
|
|
|
|
module.exports = findDOMNode;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 92 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDefaultBatchingStrategy
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactUpdates = __webpack_require__(54);
|
|
var Transaction = __webpack_require__(57);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyFunction = __webpack_require__(15);
|
|
|
|
var RESET_BATCHED_UPDATES = {
|
|
initialize: emptyFunction,
|
|
close: function () {
|
|
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
|
|
}
|
|
};
|
|
|
|
var FLUSH_BATCHED_UPDATES = {
|
|
initialize: emptyFunction,
|
|
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
|
|
};
|
|
|
|
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
|
|
|
|
function ReactDefaultBatchingStrategyTransaction() {
|
|
this.reinitializeTransaction();
|
|
}
|
|
|
|
assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
|
|
getTransactionWrappers: function () {
|
|
return TRANSACTION_WRAPPERS;
|
|
}
|
|
});
|
|
|
|
var transaction = new ReactDefaultBatchingStrategyTransaction();
|
|
|
|
var ReactDefaultBatchingStrategy = {
|
|
isBatchingUpdates: false,
|
|
|
|
/**
|
|
* Call the provided function in a context within which calls to `setState`
|
|
* and friends are batched such that components aren't updated unnecessarily.
|
|
*/
|
|
batchedUpdates: function (callback, a, b, c, d, e) {
|
|
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
|
|
|
|
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
|
|
|
|
// The code is written this way to avoid extra allocations
|
|
if (alreadyBatchingUpdates) {
|
|
callback(a, b, c, d, e);
|
|
} else {
|
|
transaction.perform(callback, null, a, b, c, d, e);
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = ReactDefaultBatchingStrategy;
|
|
|
|
/***/ }),
|
|
/* 93 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMComponent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
/* global hasOwnProperty:true */
|
|
|
|
'use strict';
|
|
|
|
var AutoFocusUtils = __webpack_require__(94);
|
|
var CSSPropertyOperations = __webpack_require__(96);
|
|
var DOMProperty = __webpack_require__(23);
|
|
var DOMPropertyOperations = __webpack_require__(22);
|
|
var EventConstants = __webpack_require__(30);
|
|
var ReactBrowserEventEmitter = __webpack_require__(29);
|
|
var ReactComponentBrowserEnvironment = __webpack_require__(26);
|
|
var ReactDOMButton = __webpack_require__(104);
|
|
var ReactDOMInput = __webpack_require__(105);
|
|
var ReactDOMOption = __webpack_require__(109);
|
|
var ReactDOMSelect = __webpack_require__(112);
|
|
var ReactDOMTextarea = __webpack_require__(113);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactMultiChild = __webpack_require__(114);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactUpdateQueue = __webpack_require__(53);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var canDefineProperty = __webpack_require__(43);
|
|
var escapeTextContentForBrowser = __webpack_require__(21);
|
|
var invariant = __webpack_require__(13);
|
|
var isEventSupported = __webpack_require__(40);
|
|
var keyOf = __webpack_require__(79);
|
|
var setInnerHTML = __webpack_require__(19);
|
|
var setTextContent = __webpack_require__(20);
|
|
var shallowEqual = __webpack_require__(117);
|
|
var validateDOMNesting = __webpack_require__(70);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var deleteListener = ReactBrowserEventEmitter.deleteListener;
|
|
var listenTo = ReactBrowserEventEmitter.listenTo;
|
|
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
|
|
|
|
// For quickly matching children type, to test if can be treated as content.
|
|
var CONTENT_TYPES = { 'string': true, 'number': true };
|
|
|
|
var CHILDREN = keyOf({ children: null });
|
|
var STYLE = keyOf({ style: null });
|
|
var HTML = keyOf({ __html: null });
|
|
|
|
var ELEMENT_NODE_TYPE = 1;
|
|
|
|
function getDeclarationErrorAddendum(internalInstance) {
|
|
if (internalInstance) {
|
|
var owner = internalInstance._currentElement._owner || null;
|
|
if (owner) {
|
|
var name = owner.getName();
|
|
if (name) {
|
|
return ' This DOM node was rendered by `' + name + '`.';
|
|
}
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
var legacyPropsDescriptor;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
legacyPropsDescriptor = {
|
|
props: {
|
|
enumerable: false,
|
|
get: function () {
|
|
var component = this._reactInternalComponent;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
return component._currentElement.props;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function legacyGetDOMNode() {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var component = this._reactInternalComponent;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
}
|
|
return this;
|
|
}
|
|
|
|
function legacyIsMounted() {
|
|
var component = this._reactInternalComponent;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
}
|
|
return !!component;
|
|
}
|
|
|
|
function legacySetStateEtc() {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var component = this._reactInternalComponent;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
}
|
|
}
|
|
|
|
function legacySetProps(partialProps, callback) {
|
|
var component = this._reactInternalComponent;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
}
|
|
if (!component) {
|
|
return;
|
|
}
|
|
ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps);
|
|
if (callback) {
|
|
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
|
|
}
|
|
}
|
|
|
|
function legacyReplaceProps(partialProps, callback) {
|
|
var component = this._reactInternalComponent;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
|
|
}
|
|
if (!component) {
|
|
return;
|
|
}
|
|
ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps);
|
|
if (callback) {
|
|
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
|
|
}
|
|
}
|
|
|
|
function friendlyStringify(obj) {
|
|
if (typeof obj === 'object') {
|
|
if (Array.isArray(obj)) {
|
|
return '[' + obj.map(friendlyStringify).join(', ') + ']';
|
|
} else {
|
|
var pairs = [];
|
|
for (var key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
|
|
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
|
|
}
|
|
}
|
|
return '{' + pairs.join(', ') + '}';
|
|
}
|
|
} else if (typeof obj === 'string') {
|
|
return JSON.stringify(obj);
|
|
} else if (typeof obj === 'function') {
|
|
return '[function object]';
|
|
}
|
|
// Differs from JSON.stringify in that undefined becauses undefined and that
|
|
// inf and nan don't become null
|
|
return String(obj);
|
|
}
|
|
|
|
var styleMutationWarning = {};
|
|
|
|
function checkAndWarnForMutatedStyle(style1, style2, component) {
|
|
if (style1 == null || style2 == null) {
|
|
return;
|
|
}
|
|
if (shallowEqual(style1, style2)) {
|
|
return;
|
|
}
|
|
|
|
var componentName = component._tag;
|
|
var owner = component._currentElement._owner;
|
|
var ownerName;
|
|
if (owner) {
|
|
ownerName = owner.getName();
|
|
}
|
|
|
|
var hash = ownerName + '|' + componentName;
|
|
|
|
if (styleMutationWarning.hasOwnProperty(hash)) {
|
|
return;
|
|
}
|
|
|
|
styleMutationWarning[hash] = true;
|
|
|
|
process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined;
|
|
}
|
|
|
|
/**
|
|
* @param {object} component
|
|
* @param {?object} props
|
|
*/
|
|
function assertValidProps(component, props) {
|
|
if (!props) {
|
|
return;
|
|
}
|
|
// Note the use of `==` which checks for null or undefined.
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (voidElementTags[component._tag]) {
|
|
process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined;
|
|
}
|
|
}
|
|
if (props.dangerouslySetInnerHTML != null) {
|
|
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
|
|
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
|
|
}
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
|
|
}
|
|
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
|
|
}
|
|
|
|
function enqueuePutListener(id, registrationName, listener, transaction) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// IE8 has no API for event capturing and the `onScroll` event doesn't
|
|
// bubble.
|
|
process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined;
|
|
}
|
|
var container = ReactMount.findReactContainerForID(id);
|
|
if (container) {
|
|
var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container;
|
|
listenTo(registrationName, doc);
|
|
}
|
|
transaction.getReactMountReady().enqueue(putListener, {
|
|
id: id,
|
|
registrationName: registrationName,
|
|
listener: listener
|
|
});
|
|
}
|
|
|
|
function putListener() {
|
|
var listenerToPut = this;
|
|
ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener);
|
|
}
|
|
|
|
// There are so many media events, it makes sense to just
|
|
// maintain a list rather than create a `trapBubbledEvent` for each
|
|
var mediaEvents = {
|
|
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'
|
|
};
|
|
|
|
function trapBubbledEventsLocal() {
|
|
var inst = this;
|
|
// If a component renders to null or if another component fatals and causes
|
|
// the state of the tree to be corrupted, `node` here can be null.
|
|
!inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined;
|
|
var node = ReactMount.getNode(inst._rootNodeID);
|
|
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined;
|
|
|
|
switch (inst._tag) {
|
|
case 'iframe':
|
|
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
|
|
break;
|
|
case 'video':
|
|
case 'audio':
|
|
|
|
inst._wrapperState.listeners = [];
|
|
// create listener for each media event
|
|
for (var event in mediaEvents) {
|
|
if (mediaEvents.hasOwnProperty(event)) {
|
|
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
|
|
}
|
|
}
|
|
|
|
break;
|
|
case 'img':
|
|
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
|
|
break;
|
|
case 'form':
|
|
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
|
|
break;
|
|
}
|
|
}
|
|
|
|
function mountReadyInputWrapper() {
|
|
ReactDOMInput.mountReadyWrapper(this);
|
|
}
|
|
|
|
function postUpdateSelectWrapper() {
|
|
ReactDOMSelect.postUpdateWrapper(this);
|
|
}
|
|
|
|
// For HTML, certain tags should omit their close tag. We keep a whitelist for
|
|
// those special cased tags.
|
|
|
|
var omittedCloseTags = {
|
|
'area': true,
|
|
'base': true,
|
|
'br': true,
|
|
'col': true,
|
|
'embed': true,
|
|
'hr': true,
|
|
'img': true,
|
|
'input': true,
|
|
'keygen': true,
|
|
'link': true,
|
|
'meta': true,
|
|
'param': true,
|
|
'source': true,
|
|
'track': true,
|
|
'wbr': true
|
|
};
|
|
|
|
// NOTE: menuitem's close tag should be omitted, but that causes problems.
|
|
var newlineEatingTags = {
|
|
'listing': true,
|
|
'pre': true,
|
|
'textarea': true
|
|
};
|
|
|
|
// For HTML, certain tags cannot have children. This has the same purpose as
|
|
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
|
|
|
|
var voidElementTags = assign({
|
|
'menuitem': true
|
|
}, omittedCloseTags);
|
|
|
|
// We accept any tag to be rendered but since this gets injected into arbitrary
|
|
// HTML, we want to make sure that it's a safe tag.
|
|
// http://www.w3.org/TR/REC-xml/#NT-Name
|
|
|
|
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
|
|
var validatedTagCache = {};
|
|
var hasOwnProperty = ({}).hasOwnProperty;
|
|
|
|
function validateDangerousTag(tag) {
|
|
if (!hasOwnProperty.call(validatedTagCache, tag)) {
|
|
!VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined;
|
|
validatedTagCache[tag] = true;
|
|
}
|
|
}
|
|
|
|
function processChildContextDev(context, inst) {
|
|
// Pass down our tag name to child components for validation purposes
|
|
context = assign({}, context);
|
|
var info = context[validateDOMNesting.ancestorInfoContextKey];
|
|
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst);
|
|
return context;
|
|
}
|
|
|
|
function isCustomComponent(tagName, props) {
|
|
return tagName.indexOf('-') >= 0 || props.is != null;
|
|
}
|
|
|
|
/**
|
|
* Creates a new React class that is idempotent and capable of containing other
|
|
* React components. It accepts event listeners and DOM properties that are
|
|
* valid according to `DOMProperty`.
|
|
*
|
|
* - Event listeners: `onClick`, `onMouseDown`, etc.
|
|
* - DOM properties: `className`, `name`, `title`, etc.
|
|
*
|
|
* The `style` property functions differently from the DOM API. It accepts an
|
|
* object mapping of style properties to values.
|
|
*
|
|
* @constructor ReactDOMComponent
|
|
* @extends ReactMultiChild
|
|
*/
|
|
function ReactDOMComponent(tag) {
|
|
validateDangerousTag(tag);
|
|
this._tag = tag.toLowerCase();
|
|
this._renderedChildren = null;
|
|
this._previousStyle = null;
|
|
this._previousStyleCopy = null;
|
|
this._rootNodeID = null;
|
|
this._wrapperState = null;
|
|
this._topLevelWrapper = null;
|
|
this._nodeWithLegacyProperties = null;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
this._unprocessedContextDev = null;
|
|
this._processedContextDev = null;
|
|
}
|
|
}
|
|
|
|
ReactDOMComponent.displayName = 'ReactDOMComponent';
|
|
|
|
ReactDOMComponent.Mixin = {
|
|
|
|
construct: function (element) {
|
|
this._currentElement = element;
|
|
},
|
|
|
|
/**
|
|
* Generates root tag markup then recurses. This method has side effects and
|
|
* is not idempotent.
|
|
*
|
|
* @internal
|
|
* @param {string} rootID The root DOM ID for this node.
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @param {object} context
|
|
* @return {string} The computed markup.
|
|
*/
|
|
mountComponent: function (rootID, transaction, context) {
|
|
this._rootNodeID = rootID;
|
|
|
|
var props = this._currentElement.props;
|
|
|
|
switch (this._tag) {
|
|
case 'iframe':
|
|
case 'img':
|
|
case 'form':
|
|
case 'video':
|
|
case 'audio':
|
|
this._wrapperState = {
|
|
listeners: null
|
|
};
|
|
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
|
|
break;
|
|
case 'button':
|
|
props = ReactDOMButton.getNativeProps(this, props, context);
|
|
break;
|
|
case 'input':
|
|
ReactDOMInput.mountWrapper(this, props, context);
|
|
props = ReactDOMInput.getNativeProps(this, props, context);
|
|
break;
|
|
case 'option':
|
|
ReactDOMOption.mountWrapper(this, props, context);
|
|
props = ReactDOMOption.getNativeProps(this, props, context);
|
|
break;
|
|
case 'select':
|
|
ReactDOMSelect.mountWrapper(this, props, context);
|
|
props = ReactDOMSelect.getNativeProps(this, props, context);
|
|
context = ReactDOMSelect.processChildContext(this, props, context);
|
|
break;
|
|
case 'textarea':
|
|
ReactDOMTextarea.mountWrapper(this, props, context);
|
|
props = ReactDOMTextarea.getNativeProps(this, props, context);
|
|
break;
|
|
}
|
|
|
|
assertValidProps(this, props);
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (context[validateDOMNesting.ancestorInfoContextKey]) {
|
|
validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]);
|
|
}
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
this._unprocessedContextDev = context;
|
|
this._processedContextDev = processChildContextDev(context, this);
|
|
context = this._processedContextDev;
|
|
}
|
|
|
|
var mountImage;
|
|
if (transaction.useCreateElement) {
|
|
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
|
|
var el = ownerDocument.createElement(this._currentElement.type);
|
|
DOMPropertyOperations.setAttributeForID(el, this._rootNodeID);
|
|
// Populate node cache
|
|
ReactMount.getID(el);
|
|
this._updateDOMProperties({}, props, transaction, el);
|
|
this._createInitialChildren(transaction, props, context, el);
|
|
mountImage = el;
|
|
} else {
|
|
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
|
|
var tagContent = this._createContentMarkup(transaction, props, context);
|
|
if (!tagContent && omittedCloseTags[this._tag]) {
|
|
mountImage = tagOpen + '/>';
|
|
} else {
|
|
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
|
|
}
|
|
}
|
|
|
|
switch (this._tag) {
|
|
case 'input':
|
|
transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this);
|
|
// falls through
|
|
case 'button':
|
|
case 'select':
|
|
case 'textarea':
|
|
if (props.autoFocus) {
|
|
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
|
|
}
|
|
break;
|
|
}
|
|
|
|
return mountImage;
|
|
},
|
|
|
|
/**
|
|
* Creates markup for the open tag and all attributes.
|
|
*
|
|
* This method has side effects because events get registered.
|
|
*
|
|
* Iterating over object properties is faster than iterating over arrays.
|
|
* @see http://jsperf.com/obj-vs-arr-iteration
|
|
*
|
|
* @private
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @param {object} props
|
|
* @return {string} Markup of opening tag.
|
|
*/
|
|
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
|
|
var ret = '<' + this._currentElement.type;
|
|
|
|
for (var propKey in props) {
|
|
if (!props.hasOwnProperty(propKey)) {
|
|
continue;
|
|
}
|
|
var propValue = props[propKey];
|
|
if (propValue == null) {
|
|
continue;
|
|
}
|
|
if (registrationNameModules.hasOwnProperty(propKey)) {
|
|
if (propValue) {
|
|
enqueuePutListener(this._rootNodeID, propKey, propValue, transaction);
|
|
}
|
|
} else {
|
|
if (propKey === STYLE) {
|
|
if (propValue) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// See `_updateDOMProperties`. style block
|
|
this._previousStyle = propValue;
|
|
}
|
|
propValue = this._previousStyleCopy = assign({}, props.style);
|
|
}
|
|
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
|
|
}
|
|
var markup = null;
|
|
if (this._tag != null && isCustomComponent(this._tag, props)) {
|
|
if (propKey !== CHILDREN) {
|
|
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
|
|
}
|
|
} else {
|
|
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
|
|
}
|
|
if (markup) {
|
|
ret += ' ' + markup;
|
|
}
|
|
}
|
|
}
|
|
|
|
// For static pages, no need to put React ID and checksum. Saves lots of
|
|
// bytes.
|
|
if (transaction.renderToStaticMarkup) {
|
|
return ret;
|
|
}
|
|
|
|
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
|
|
return ret + ' ' + markupForID;
|
|
},
|
|
|
|
/**
|
|
* Creates markup for the content between the tags.
|
|
*
|
|
* @private
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @param {object} props
|
|
* @param {object} context
|
|
* @return {string} Content markup.
|
|
*/
|
|
_createContentMarkup: function (transaction, props, context) {
|
|
var ret = '';
|
|
|
|
// Intentional use of != to avoid catching zero/false.
|
|
var innerHTML = props.dangerouslySetInnerHTML;
|
|
if (innerHTML != null) {
|
|
if (innerHTML.__html != null) {
|
|
ret = innerHTML.__html;
|
|
}
|
|
} else {
|
|
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
|
|
var childrenToUse = contentToUse != null ? null : props.children;
|
|
if (contentToUse != null) {
|
|
// TODO: Validate that text is allowed as a child of this node
|
|
ret = escapeTextContentForBrowser(contentToUse);
|
|
} else if (childrenToUse != null) {
|
|
var mountImages = this.mountChildren(childrenToUse, transaction, context);
|
|
ret = mountImages.join('');
|
|
}
|
|
}
|
|
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
|
|
// text/html ignores the first character in these tags if it's a newline
|
|
// Prefer to break application/xml over text/html (for now) by adding
|
|
// a newline specifically to get eaten by the parser. (Alternately for
|
|
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
|
|
// \r is normalized out by HTMLTextAreaElement#value.)
|
|
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
|
|
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
|
|
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
|
|
// See: Parsing of "textarea" "listing" and "pre" elements
|
|
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
|
|
return '\n' + ret;
|
|
} else {
|
|
return ret;
|
|
}
|
|
},
|
|
|
|
_createInitialChildren: function (transaction, props, context, el) {
|
|
// Intentional use of != to avoid catching zero/false.
|
|
var innerHTML = props.dangerouslySetInnerHTML;
|
|
if (innerHTML != null) {
|
|
if (innerHTML.__html != null) {
|
|
setInnerHTML(el, innerHTML.__html);
|
|
}
|
|
} else {
|
|
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
|
|
var childrenToUse = contentToUse != null ? null : props.children;
|
|
if (contentToUse != null) {
|
|
// TODO: Validate that text is allowed as a child of this node
|
|
setTextContent(el, contentToUse);
|
|
} else if (childrenToUse != null) {
|
|
var mountImages = this.mountChildren(childrenToUse, transaction, context);
|
|
for (var i = 0; i < mountImages.length; i++) {
|
|
el.appendChild(mountImages[i]);
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Receives a next element and updates the component.
|
|
*
|
|
* @internal
|
|
* @param {ReactElement} nextElement
|
|
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
|
|
* @param {object} context
|
|
*/
|
|
receiveComponent: function (nextElement, transaction, context) {
|
|
var prevElement = this._currentElement;
|
|
this._currentElement = nextElement;
|
|
this.updateComponent(transaction, prevElement, nextElement, context);
|
|
},
|
|
|
|
/**
|
|
* Updates a native DOM component after it has already been allocated and
|
|
* attached to the DOM. Reconciles the root DOM node, then recurses.
|
|
*
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {ReactElement} prevElement
|
|
* @param {ReactElement} nextElement
|
|
* @internal
|
|
* @overridable
|
|
*/
|
|
updateComponent: function (transaction, prevElement, nextElement, context) {
|
|
var lastProps = prevElement.props;
|
|
var nextProps = this._currentElement.props;
|
|
|
|
switch (this._tag) {
|
|
case 'button':
|
|
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
|
|
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
|
|
break;
|
|
case 'input':
|
|
ReactDOMInput.updateWrapper(this);
|
|
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
|
|
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
|
|
break;
|
|
case 'option':
|
|
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
|
|
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
|
|
break;
|
|
case 'select':
|
|
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
|
|
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
|
|
break;
|
|
case 'textarea':
|
|
ReactDOMTextarea.updateWrapper(this);
|
|
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
|
|
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
|
|
break;
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// If the context is reference-equal to the old one, pass down the same
|
|
// processed object so the update bailout in ReactReconciler behaves
|
|
// correctly (and identically in dev and prod). See #5005.
|
|
if (this._unprocessedContextDev !== context) {
|
|
this._unprocessedContextDev = context;
|
|
this._processedContextDev = processChildContextDev(context, this);
|
|
}
|
|
context = this._processedContextDev;
|
|
}
|
|
|
|
assertValidProps(this, nextProps);
|
|
this._updateDOMProperties(lastProps, nextProps, transaction, null);
|
|
this._updateDOMChildren(lastProps, nextProps, transaction, context);
|
|
|
|
if (!canDefineProperty && this._nodeWithLegacyProperties) {
|
|
this._nodeWithLegacyProperties.props = nextProps;
|
|
}
|
|
|
|
if (this._tag === 'select') {
|
|
// <select> value update needs to occur after <option> children
|
|
// reconciliation
|
|
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Reconciles the properties by detecting differences in property values and
|
|
* updating the DOM as necessary. This function is probably the single most
|
|
* critical path for performance optimization.
|
|
*
|
|
* TODO: Benchmark whether checking for changed values in memory actually
|
|
* improves performance (especially statically positioned elements).
|
|
* TODO: Benchmark the effects of putting this at the top since 99% of props
|
|
* do not change for a given reconciliation.
|
|
* TODO: Benchmark areas that can be improved with caching.
|
|
*
|
|
* @private
|
|
* @param {object} lastProps
|
|
* @param {object} nextProps
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {?DOMElement} node
|
|
*/
|
|
_updateDOMProperties: function (lastProps, nextProps, transaction, node) {
|
|
var propKey;
|
|
var styleName;
|
|
var styleUpdates;
|
|
for (propKey in lastProps) {
|
|
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) {
|
|
continue;
|
|
}
|
|
if (propKey === STYLE) {
|
|
var lastStyle = this._previousStyleCopy;
|
|
for (styleName in lastStyle) {
|
|
if (lastStyle.hasOwnProperty(styleName)) {
|
|
styleUpdates = styleUpdates || {};
|
|
styleUpdates[styleName] = '';
|
|
}
|
|
}
|
|
this._previousStyleCopy = null;
|
|
} else if (registrationNameModules.hasOwnProperty(propKey)) {
|
|
if (lastProps[propKey]) {
|
|
// Only call deleteListener if there was a listener previously or
|
|
// else willDeleteListener gets called when there wasn't actually a
|
|
// listener (e.g., onClick={null})
|
|
deleteListener(this._rootNodeID, propKey);
|
|
}
|
|
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
|
|
if (!node) {
|
|
node = ReactMount.getNode(this._rootNodeID);
|
|
}
|
|
DOMPropertyOperations.deleteValueForProperty(node, propKey);
|
|
}
|
|
}
|
|
for (propKey in nextProps) {
|
|
var nextProp = nextProps[propKey];
|
|
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey];
|
|
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
|
|
continue;
|
|
}
|
|
if (propKey === STYLE) {
|
|
if (nextProp) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
|
|
this._previousStyle = nextProp;
|
|
}
|
|
nextProp = this._previousStyleCopy = assign({}, nextProp);
|
|
} else {
|
|
this._previousStyleCopy = null;
|
|
}
|
|
if (lastProp) {
|
|
// Unset styles on `lastProp` but not on `nextProp`.
|
|
for (styleName in lastProp) {
|
|
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
|
|
styleUpdates = styleUpdates || {};
|
|
styleUpdates[styleName] = '';
|
|
}
|
|
}
|
|
// Update styles that changed since `lastProp`.
|
|
for (styleName in nextProp) {
|
|
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
|
|
styleUpdates = styleUpdates || {};
|
|
styleUpdates[styleName] = nextProp[styleName];
|
|
}
|
|
}
|
|
} else {
|
|
// Relies on `updateStylesByID` not mutating `styleUpdates`.
|
|
styleUpdates = nextProp;
|
|
}
|
|
} else if (registrationNameModules.hasOwnProperty(propKey)) {
|
|
if (nextProp) {
|
|
enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction);
|
|
} else if (lastProp) {
|
|
deleteListener(this._rootNodeID, propKey);
|
|
}
|
|
} else if (isCustomComponent(this._tag, nextProps)) {
|
|
if (!node) {
|
|
node = ReactMount.getNode(this._rootNodeID);
|
|
}
|
|
if (propKey === CHILDREN) {
|
|
nextProp = null;
|
|
}
|
|
DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp);
|
|
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
|
|
if (!node) {
|
|
node = ReactMount.getNode(this._rootNodeID);
|
|
}
|
|
// If we're updating to null or undefined, we should remove the property
|
|
// from the DOM node instead of inadvertantly setting to a string. This
|
|
// brings us in line with the same behavior we have on initial render.
|
|
if (nextProp != null) {
|
|
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
|
|
} else {
|
|
DOMPropertyOperations.deleteValueForProperty(node, propKey);
|
|
}
|
|
}
|
|
}
|
|
if (styleUpdates) {
|
|
if (!node) {
|
|
node = ReactMount.getNode(this._rootNodeID);
|
|
}
|
|
CSSPropertyOperations.setValueForStyles(node, styleUpdates);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Reconciles the children with the various properties that affect the
|
|
* children content.
|
|
*
|
|
* @param {object} lastProps
|
|
* @param {object} nextProps
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {object} context
|
|
*/
|
|
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
|
|
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
|
|
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
|
|
|
|
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
|
|
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
|
|
|
|
// Note the use of `!=` which checks for null or undefined.
|
|
var lastChildren = lastContent != null ? null : lastProps.children;
|
|
var nextChildren = nextContent != null ? null : nextProps.children;
|
|
|
|
// If we're switching from children to content/html or vice versa, remove
|
|
// the old content
|
|
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
|
|
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
|
|
if (lastChildren != null && nextChildren == null) {
|
|
this.updateChildren(null, transaction, context);
|
|
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
|
|
this.updateTextContent('');
|
|
}
|
|
|
|
if (nextContent != null) {
|
|
if (lastContent !== nextContent) {
|
|
this.updateTextContent('' + nextContent);
|
|
}
|
|
} else if (nextHtml != null) {
|
|
if (lastHtml !== nextHtml) {
|
|
this.updateMarkup('' + nextHtml);
|
|
}
|
|
} else if (nextChildren != null) {
|
|
this.updateChildren(nextChildren, transaction, context);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Destroys all event registrations for this instance. Does not remove from
|
|
* the DOM. That must be done by the parent.
|
|
*
|
|
* @internal
|
|
*/
|
|
unmountComponent: function () {
|
|
switch (this._tag) {
|
|
case 'iframe':
|
|
case 'img':
|
|
case 'form':
|
|
case 'video':
|
|
case 'audio':
|
|
var listeners = this._wrapperState.listeners;
|
|
if (listeners) {
|
|
for (var i = 0; i < listeners.length; i++) {
|
|
listeners[i].remove();
|
|
}
|
|
}
|
|
break;
|
|
case 'input':
|
|
ReactDOMInput.unmountWrapper(this);
|
|
break;
|
|
case 'html':
|
|
case 'head':
|
|
case 'body':
|
|
/**
|
|
* Components like <html> <head> and <body> can't be removed or added
|
|
* easily in a cross-browser way, however it's valuable to be able to
|
|
* take advantage of React's reconciliation for styling and <title>
|
|
* management. So we just document it and throw in dangerous cases.
|
|
*/
|
|
true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined;
|
|
break;
|
|
}
|
|
|
|
this.unmountChildren();
|
|
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
|
|
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
|
|
this._rootNodeID = null;
|
|
this._wrapperState = null;
|
|
if (this._nodeWithLegacyProperties) {
|
|
var node = this._nodeWithLegacyProperties;
|
|
node._reactInternalComponent = null;
|
|
this._nodeWithLegacyProperties = null;
|
|
}
|
|
},
|
|
|
|
getPublicInstance: function () {
|
|
if (!this._nodeWithLegacyProperties) {
|
|
var node = ReactMount.getNode(this._rootNodeID);
|
|
|
|
node._reactInternalComponent = this;
|
|
node.getDOMNode = legacyGetDOMNode;
|
|
node.isMounted = legacyIsMounted;
|
|
node.setState = legacySetStateEtc;
|
|
node.replaceState = legacySetStateEtc;
|
|
node.forceUpdate = legacySetStateEtc;
|
|
node.setProps = legacySetProps;
|
|
node.replaceProps = legacyReplaceProps;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (canDefineProperty) {
|
|
Object.defineProperties(node, legacyPropsDescriptor);
|
|
} else {
|
|
// updateComponent will update this property on subsequent renders
|
|
node.props = this._currentElement.props;
|
|
}
|
|
} else {
|
|
// updateComponent will update this property on subsequent renders
|
|
node.props = this._currentElement.props;
|
|
}
|
|
|
|
this._nodeWithLegacyProperties = node;
|
|
}
|
|
return this._nodeWithLegacyProperties;
|
|
}
|
|
|
|
};
|
|
|
|
ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', {
|
|
mountComponent: 'mountComponent',
|
|
updateComponent: 'updateComponent'
|
|
});
|
|
|
|
assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
|
|
|
|
module.exports = ReactDOMComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 94 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule AutoFocusUtils
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactMount = __webpack_require__(28);
|
|
|
|
var findDOMNode = __webpack_require__(91);
|
|
var focusNode = __webpack_require__(95);
|
|
|
|
var Mixin = {
|
|
componentDidMount: function () {
|
|
if (this.props.autoFocus) {
|
|
focusNode(findDOMNode(this));
|
|
}
|
|
}
|
|
};
|
|
|
|
var AutoFocusUtils = {
|
|
Mixin: Mixin,
|
|
|
|
focusDOMComponent: function () {
|
|
focusNode(ReactMount.getNode(this._rootNodeID));
|
|
}
|
|
};
|
|
|
|
module.exports = AutoFocusUtils;
|
|
|
|
/***/ }),
|
|
/* 95 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule focusNode
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* @param {DOMElement} node input/textarea to focus
|
|
*/
|
|
function focusNode(node) {
|
|
// IE8 can throw "Can't move focus to the control because it is invisible,
|
|
// not enabled, or of a type that does not accept the focus." for all kinds of
|
|
// reasons that are too expensive and fragile to test.
|
|
try {
|
|
node.focus();
|
|
} catch (e) {}
|
|
}
|
|
|
|
module.exports = focusNode;
|
|
|
|
/***/ }),
|
|
/* 96 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule CSSPropertyOperations
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var CSSProperty = __webpack_require__(97);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var ReactPerf = __webpack_require__(18);
|
|
|
|
var camelizeStyleName = __webpack_require__(98);
|
|
var dangerousStyleValue = __webpack_require__(100);
|
|
var hyphenateStyleName = __webpack_require__(101);
|
|
var memoizeStringOnly = __webpack_require__(103);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var processStyleName = memoizeStringOnly(function (styleName) {
|
|
return hyphenateStyleName(styleName);
|
|
});
|
|
|
|
var hasShorthandPropertyBug = false;
|
|
var styleFloatAccessor = 'cssFloat';
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
var tempStyle = document.createElement('div').style;
|
|
try {
|
|
// IE8 throws "Invalid argument." if resetting shorthand style properties.
|
|
tempStyle.font = '';
|
|
} catch (e) {
|
|
hasShorthandPropertyBug = true;
|
|
}
|
|
// IE8 only supports accessing cssFloat (standard) as styleFloat
|
|
if (document.documentElement.style.cssFloat === undefined) {
|
|
styleFloatAccessor = 'styleFloat';
|
|
}
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// 'msTransform' is correct, but the other prefixes should be capitalized
|
|
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
|
|
|
|
// style values shouldn't contain a semicolon
|
|
var badStyleValueWithSemicolonPattern = /;\s*$/;
|
|
|
|
var warnedStyleNames = {};
|
|
var warnedStyleValues = {};
|
|
|
|
var warnHyphenatedStyleName = function (name) {
|
|
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
|
|
return;
|
|
}
|
|
|
|
warnedStyleNames[name] = true;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined;
|
|
};
|
|
|
|
var warnBadVendoredStyleName = function (name) {
|
|
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
|
|
return;
|
|
}
|
|
|
|
warnedStyleNames[name] = true;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined;
|
|
};
|
|
|
|
var warnStyleValueWithSemicolon = function (name, value) {
|
|
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
|
|
return;
|
|
}
|
|
|
|
warnedStyleValues[value] = true;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined;
|
|
};
|
|
|
|
/**
|
|
* @param {string} name
|
|
* @param {*} value
|
|
*/
|
|
var warnValidStyle = function (name, value) {
|
|
if (name.indexOf('-') > -1) {
|
|
warnHyphenatedStyleName(name);
|
|
} else if (badVendoredStyleNamePattern.test(name)) {
|
|
warnBadVendoredStyleName(name);
|
|
} else if (badStyleValueWithSemicolonPattern.test(value)) {
|
|
warnStyleValueWithSemicolon(name, value);
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Operations for dealing with CSS properties.
|
|
*/
|
|
var CSSPropertyOperations = {
|
|
|
|
/**
|
|
* Serializes a mapping of style properties for use as inline styles:
|
|
*
|
|
* > createMarkupForStyles({width: '200px', height: 0})
|
|
* "width:200px;height:0;"
|
|
*
|
|
* Undefined values are ignored so that declarative programming is easier.
|
|
* The result should be HTML-escaped before insertion into the DOM.
|
|
*
|
|
* @param {object} styles
|
|
* @return {?string}
|
|
*/
|
|
createMarkupForStyles: function (styles) {
|
|
var serialized = '';
|
|
for (var styleName in styles) {
|
|
if (!styles.hasOwnProperty(styleName)) {
|
|
continue;
|
|
}
|
|
var styleValue = styles[styleName];
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
warnValidStyle(styleName, styleValue);
|
|
}
|
|
if (styleValue != null) {
|
|
serialized += processStyleName(styleName) + ':';
|
|
serialized += dangerousStyleValue(styleName, styleValue) + ';';
|
|
}
|
|
}
|
|
return serialized || null;
|
|
},
|
|
|
|
/**
|
|
* Sets the value for multiple styles on a node. If a value is specified as
|
|
* '' (empty string), the corresponding style property will be unset.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @param {object} styles
|
|
*/
|
|
setValueForStyles: function (node, styles) {
|
|
var style = node.style;
|
|
for (var styleName in styles) {
|
|
if (!styles.hasOwnProperty(styleName)) {
|
|
continue;
|
|
}
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
warnValidStyle(styleName, styles[styleName]);
|
|
}
|
|
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
|
|
if (styleName === 'float') {
|
|
styleName = styleFloatAccessor;
|
|
}
|
|
if (styleValue) {
|
|
style[styleName] = styleValue;
|
|
} else {
|
|
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
|
|
if (expansion) {
|
|
// Shorthand property that IE8 won't like unsetting, so unset each
|
|
// component to placate it
|
|
for (var individualStyleName in expansion) {
|
|
style[individualStyleName] = '';
|
|
}
|
|
} else {
|
|
style[styleName] = '';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', {
|
|
setValueForStyles: 'setValueForStyles'
|
|
});
|
|
|
|
module.exports = CSSPropertyOperations;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 97 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule CSSProperty
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* CSS properties which accept numbers but are not in units of "px".
|
|
*/
|
|
var isUnitlessNumber = {
|
|
animationIterationCount: true,
|
|
boxFlex: true,
|
|
boxFlexGroup: true,
|
|
boxOrdinalGroup: true,
|
|
columnCount: true,
|
|
flex: true,
|
|
flexGrow: true,
|
|
flexPositive: true,
|
|
flexShrink: true,
|
|
flexNegative: true,
|
|
flexOrder: true,
|
|
fontWeight: true,
|
|
lineClamp: true,
|
|
lineHeight: true,
|
|
opacity: true,
|
|
order: true,
|
|
orphans: true,
|
|
tabSize: true,
|
|
widows: true,
|
|
zIndex: true,
|
|
zoom: true,
|
|
|
|
// SVG-related properties
|
|
fillOpacity: true,
|
|
stopOpacity: true,
|
|
strokeDashoffset: true,
|
|
strokeOpacity: true,
|
|
strokeWidth: true
|
|
};
|
|
|
|
/**
|
|
* @param {string} prefix vendor-specific prefix, eg: Webkit
|
|
* @param {string} key style name, eg: transitionDuration
|
|
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
|
|
* WebkitTransitionDuration
|
|
*/
|
|
function prefixKey(prefix, key) {
|
|
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
|
|
}
|
|
|
|
/**
|
|
* Support style names that may come passed in prefixed by adding permutations
|
|
* of vendor prefixes.
|
|
*/
|
|
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
|
|
|
|
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
|
|
// infinite loop, because it iterates over the newly added props too.
|
|
Object.keys(isUnitlessNumber).forEach(function (prop) {
|
|
prefixes.forEach(function (prefix) {
|
|
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Most style properties can be unset by doing .style[prop] = '' but IE8
|
|
* doesn't like doing that with shorthand properties so for the properties that
|
|
* IE8 breaks on, which are listed here, we instead unset each of the
|
|
* individual properties. See http://bugs.jquery.com/ticket/12385.
|
|
* The 4-value 'clock' properties like margin, padding, border-width seem to
|
|
* behave without any problems. Curiously, list-style works too without any
|
|
* special prodding.
|
|
*/
|
|
var shorthandPropertyExpansions = {
|
|
background: {
|
|
backgroundAttachment: true,
|
|
backgroundColor: true,
|
|
backgroundImage: true,
|
|
backgroundPositionX: true,
|
|
backgroundPositionY: true,
|
|
backgroundRepeat: true
|
|
},
|
|
backgroundPosition: {
|
|
backgroundPositionX: true,
|
|
backgroundPositionY: true
|
|
},
|
|
border: {
|
|
borderWidth: true,
|
|
borderStyle: true,
|
|
borderColor: true
|
|
},
|
|
borderBottom: {
|
|
borderBottomWidth: true,
|
|
borderBottomStyle: true,
|
|
borderBottomColor: true
|
|
},
|
|
borderLeft: {
|
|
borderLeftWidth: true,
|
|
borderLeftStyle: true,
|
|
borderLeftColor: true
|
|
},
|
|
borderRight: {
|
|
borderRightWidth: true,
|
|
borderRightStyle: true,
|
|
borderRightColor: true
|
|
},
|
|
borderTop: {
|
|
borderTopWidth: true,
|
|
borderTopStyle: true,
|
|
borderTopColor: true
|
|
},
|
|
font: {
|
|
fontStyle: true,
|
|
fontVariant: true,
|
|
fontWeight: true,
|
|
fontSize: true,
|
|
lineHeight: true,
|
|
fontFamily: true
|
|
},
|
|
outline: {
|
|
outlineWidth: true,
|
|
outlineStyle: true,
|
|
outlineColor: true
|
|
}
|
|
};
|
|
|
|
var CSSProperty = {
|
|
isUnitlessNumber: isUnitlessNumber,
|
|
shorthandPropertyExpansions: shorthandPropertyExpansions
|
|
};
|
|
|
|
module.exports = CSSProperty;
|
|
|
|
/***/ }),
|
|
/* 98 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule camelizeStyleName
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var camelize = __webpack_require__(99);
|
|
|
|
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;
|
|
|
|
/***/ }),
|
|
/* 99 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule camelize
|
|
* @typechecks
|
|
*/
|
|
|
|
"use strict";
|
|
|
|
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;
|
|
|
|
/***/ }),
|
|
/* 100 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule dangerousStyleValue
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var CSSProperty = __webpack_require__(97);
|
|
|
|
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
|
|
|
|
/**
|
|
* Convert a value into the proper css writable value. The style name `name`
|
|
* should be logical (no hyphens), as specified
|
|
* in `CSSProperty.isUnitlessNumber`.
|
|
*
|
|
* @param {string} name CSS property name such as `topMargin`.
|
|
* @param {*} value CSS property value such as `10px`.
|
|
* @return {string} Normalized style value with dimensions applied.
|
|
*/
|
|
function dangerousStyleValue(name, value) {
|
|
// Note that we've removed escapeTextForBrowser() calls here since the
|
|
// whole string will be escaped when the attribute is injected into
|
|
// the markup. If you provide unsafe user data here they can inject
|
|
// arbitrary CSS which may be problematic (I couldn't repro this):
|
|
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
|
|
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
|
|
// This is not an XSS hole but instead a potential CSS injection issue
|
|
// which has lead to a greater discussion about how we're going to
|
|
// trust URLs moving forward. See #2115901
|
|
|
|
var isEmpty = value == null || typeof value === 'boolean' || value === '';
|
|
if (isEmpty) {
|
|
return '';
|
|
}
|
|
|
|
var isNonNumeric = isNaN(value);
|
|
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
|
|
return '' + value; // cast to string
|
|
}
|
|
|
|
if (typeof value === 'string') {
|
|
value = value.trim();
|
|
}
|
|
return value + 'px';
|
|
}
|
|
|
|
module.exports = dangerousStyleValue;
|
|
|
|
/***/ }),
|
|
/* 101 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule hyphenateStyleName
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var hyphenate = __webpack_require__(102);
|
|
|
|
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;
|
|
|
|
/***/ }),
|
|
/* 102 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule hyphenate
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
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;
|
|
|
|
/***/ }),
|
|
/* 103 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule memoizeStringOnly
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Memoizes the return value of a function that accepts one string argument.
|
|
*
|
|
* @param {function} callback
|
|
* @return {function}
|
|
*/
|
|
function memoizeStringOnly(callback) {
|
|
var cache = {};
|
|
return function (string) {
|
|
if (!cache.hasOwnProperty(string)) {
|
|
cache[string] = callback.call(this, string);
|
|
}
|
|
return cache[string];
|
|
};
|
|
}
|
|
|
|
module.exports = memoizeStringOnly;
|
|
|
|
/***/ }),
|
|
/* 104 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMButton
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var mouseListenerNames = {
|
|
onClick: true,
|
|
onDoubleClick: true,
|
|
onMouseDown: true,
|
|
onMouseMove: true,
|
|
onMouseUp: true,
|
|
|
|
onClickCapture: true,
|
|
onDoubleClickCapture: true,
|
|
onMouseDownCapture: true,
|
|
onMouseMoveCapture: true,
|
|
onMouseUpCapture: true
|
|
};
|
|
|
|
/**
|
|
* Implements a <button> native component that does not receive mouse events
|
|
* when `disabled` is set.
|
|
*/
|
|
var ReactDOMButton = {
|
|
getNativeProps: function (inst, props, context) {
|
|
if (!props.disabled) {
|
|
return props;
|
|
}
|
|
|
|
// Copy the props, except the mouse listeners
|
|
var nativeProps = {};
|
|
for (var key in props) {
|
|
if (props.hasOwnProperty(key) && !mouseListenerNames[key]) {
|
|
nativeProps[key] = props[key];
|
|
}
|
|
}
|
|
|
|
return nativeProps;
|
|
}
|
|
};
|
|
|
|
module.exports = ReactDOMButton;
|
|
|
|
/***/ }),
|
|
/* 105 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMInput
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDOMIDOperations = __webpack_require__(27);
|
|
var LinkedValueUtils = __webpack_require__(106);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
var instancesByReactID = {};
|
|
|
|
function forceUpdateIfMounted() {
|
|
if (this._rootNodeID) {
|
|
// DOM component is still mounted; update
|
|
ReactDOMInput.updateWrapper(this);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements an <input> native 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
|
|
*/
|
|
var ReactDOMInput = {
|
|
getNativeProps: function (inst, props, context) {
|
|
var value = LinkedValueUtils.getValue(props);
|
|
var checked = LinkedValueUtils.getChecked(props);
|
|
|
|
var nativeProps = assign({}, props, {
|
|
defaultChecked: undefined,
|
|
defaultValue: undefined,
|
|
value: value != null ? value : inst._wrapperState.initialValue,
|
|
checked: checked != null ? checked : inst._wrapperState.initialChecked,
|
|
onChange: inst._wrapperState.onChange
|
|
});
|
|
|
|
return nativeProps;
|
|
},
|
|
|
|
mountWrapper: function (inst, props) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
|
|
}
|
|
|
|
var defaultValue = props.defaultValue;
|
|
inst._wrapperState = {
|
|
initialChecked: props.defaultChecked || false,
|
|
initialValue: defaultValue != null ? defaultValue : null,
|
|
onChange: _handleChange.bind(inst)
|
|
};
|
|
},
|
|
|
|
mountReadyWrapper: function (inst) {
|
|
// Can't be in mountWrapper or else server rendering leaks.
|
|
instancesByReactID[inst._rootNodeID] = inst;
|
|
},
|
|
|
|
unmountWrapper: function (inst) {
|
|
delete instancesByReactID[inst._rootNodeID];
|
|
},
|
|
|
|
updateWrapper: function (inst) {
|
|
var props = inst._currentElement.props;
|
|
|
|
// TODO: Shouldn't this be getChecked(props)?
|
|
var checked = props.checked;
|
|
if (checked != null) {
|
|
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false);
|
|
}
|
|
|
|
var value = LinkedValueUtils.getValue(props);
|
|
if (value != null) {
|
|
// Cast `value` to a string to ensure the value is set correctly. While
|
|
// browsers typically do this as necessary, jsdom doesn't.
|
|
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
|
|
}
|
|
}
|
|
};
|
|
|
|
function _handleChange(event) {
|
|
var props = this._currentElement.props;
|
|
|
|
var returnValue = LinkedValueUtils.executeOnChange(props, event);
|
|
|
|
// Here we use asap to wait until all updates have propagated, which
|
|
// is important when using controlled components within layers:
|
|
// https://github.com/facebook/react/issues/1698
|
|
ReactUpdates.asap(forceUpdateIfMounted, this);
|
|
|
|
var name = props.name;
|
|
if (props.type === 'radio' && name != null) {
|
|
var rootNode = ReactMount.getNode(this._rootNodeID);
|
|
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, let's just use the global
|
|
// `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 with non-React.
|
|
var otherID = ReactMount.getID(otherNode);
|
|
!otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
|
|
var otherInstance = instancesByReactID[otherID];
|
|
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
|
|
// 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.
|
|
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
|
|
}
|
|
}
|
|
|
|
return returnValue;
|
|
}
|
|
|
|
module.exports = ReactDOMInput;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 106 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule LinkedValueUtils
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactPropTypes = __webpack_require__(107);
|
|
var ReactPropTypeLocations = __webpack_require__(65);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var hasReadOnlyValue = {
|
|
'button': true,
|
|
'checkbox': true,
|
|
'image': true,
|
|
'hidden': true,
|
|
'radio': true,
|
|
'reset': true,
|
|
'submit': true
|
|
};
|
|
|
|
function _assertSingleLink(inputProps) {
|
|
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined;
|
|
}
|
|
function _assertValueLink(inputProps) {
|
|
_assertSingleLink(inputProps);
|
|
!(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined;
|
|
}
|
|
|
|
function _assertCheckedLink(inputProps) {
|
|
_assertSingleLink(inputProps);
|
|
!(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined;
|
|
}
|
|
|
|
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`.');
|
|
},
|
|
onChange: ReactPropTypes.func
|
|
};
|
|
|
|
var loggedTypeFailures = {};
|
|
function getDeclarationErrorAddendum(owner) {
|
|
if (owner) {
|
|
var name = owner.getName();
|
|
if (name) {
|
|
return ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Provide a linked `value` attribute for controlled forms. You should not use
|
|
* this outside of the ReactDOM controlled form components.
|
|
*/
|
|
var LinkedValueUtils = {
|
|
checkPropTypes: function (tagName, props, owner) {
|
|
for (var propName in propTypes) {
|
|
if (propTypes.hasOwnProperty(propName)) {
|
|
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
}
|
|
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 addendum = getDeclarationErrorAddendum(owner);
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined;
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* @param {object} inputProps Props for form component
|
|
* @return {*} current value of the input either from value prop or link.
|
|
*/
|
|
getValue: function (inputProps) {
|
|
if (inputProps.valueLink) {
|
|
_assertValueLink(inputProps);
|
|
return inputProps.valueLink.value;
|
|
}
|
|
return inputProps.value;
|
|
},
|
|
|
|
/**
|
|
* @param {object} inputProps Props for form component
|
|
* @return {*} current checked status of the input either from checked prop
|
|
* or link.
|
|
*/
|
|
getChecked: function (inputProps) {
|
|
if (inputProps.checkedLink) {
|
|
_assertCheckedLink(inputProps);
|
|
return inputProps.checkedLink.value;
|
|
}
|
|
return inputProps.checked;
|
|
},
|
|
|
|
/**
|
|
* @param {object} inputProps Props for form component
|
|
* @param {SyntheticEvent} event change event to handle
|
|
*/
|
|
executeOnChange: function (inputProps, event) {
|
|
if (inputProps.valueLink) {
|
|
_assertValueLink(inputProps);
|
|
return inputProps.valueLink.requestChange(event.target.value);
|
|
} else if (inputProps.checkedLink) {
|
|
_assertCheckedLink(inputProps);
|
|
return inputProps.checkedLink.requestChange(event.target.checked);
|
|
} else if (inputProps.onChange) {
|
|
return inputProps.onChange.call(undefined, event);
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = LinkedValueUtils;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 107 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactPropTypes
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactPropTypeLocationNames = __webpack_require__(66);
|
|
|
|
var emptyFunction = __webpack_require__(15);
|
|
var getIteratorFn = __webpack_require__(108);
|
|
|
|
/**
|
|
* Collection of methods that allow declaration and validation of props that are
|
|
* supplied to React components. Example usage:
|
|
*
|
|
* var Props = require('ReactPropTypes');
|
|
* var MyArticle = React.createClass({
|
|
* propTypes: {
|
|
* // An optional string prop named "description".
|
|
* description: Props.string,
|
|
*
|
|
* // A required enum prop named "category".
|
|
* category: Props.oneOf(['News','Photos']).isRequired,
|
|
*
|
|
* // A prop named "dialog" that requires an instance of Dialog.
|
|
* dialog: Props.instanceOf(Dialog).isRequired
|
|
* },
|
|
* render: function() { ... }
|
|
* });
|
|
*
|
|
* A more formal specification of how these methods are used:
|
|
*
|
|
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
|
|
* decl := ReactPropTypes.{type}(.isRequired)?
|
|
*
|
|
* Each and every declaration produces a function with the same signature. This
|
|
* allows the creation of custom validation functions. For example:
|
|
*
|
|
* var MyLink = React.createClass({
|
|
* propTypes: {
|
|
* // An optional string or URI prop named "href".
|
|
* href: function(props, propName, componentName) {
|
|
* var propValue = props[propName];
|
|
* if (propValue != null && typeof propValue !== 'string' &&
|
|
* !(propValue instanceof URI)) {
|
|
* return new Error(
|
|
* 'Expected a string or an URI for ' + propName + ' in ' +
|
|
* componentName
|
|
* );
|
|
* }
|
|
* }
|
|
* },
|
|
* render: function() {...}
|
|
* });
|
|
*
|
|
* @internal
|
|
*/
|
|
|
|
var ANONYMOUS = '<<anonymous>>';
|
|
|
|
var ReactPropTypes = {
|
|
array: createPrimitiveTypeChecker('array'),
|
|
bool: createPrimitiveTypeChecker('boolean'),
|
|
func: createPrimitiveTypeChecker('function'),
|
|
number: createPrimitiveTypeChecker('number'),
|
|
object: createPrimitiveTypeChecker('object'),
|
|
string: createPrimitiveTypeChecker('string'),
|
|
|
|
any: createAnyTypeChecker(),
|
|
arrayOf: createArrayOfTypeChecker,
|
|
element: createElementTypeChecker(),
|
|
instanceOf: createInstanceTypeChecker,
|
|
node: createNodeChecker(),
|
|
objectOf: createObjectOfTypeChecker,
|
|
oneOf: createEnumTypeChecker,
|
|
oneOfType: createUnionTypeChecker,
|
|
shape: createShapeTypeChecker
|
|
};
|
|
|
|
function createChainableTypeChecker(validate) {
|
|
function checkType(isRequired, props, propName, componentName, location, propFullName) {
|
|
componentName = componentName || ANONYMOUS;
|
|
propFullName = propFullName || propName;
|
|
if (props[propName] == null) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
if (isRequired) {
|
|
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
|
|
}
|
|
return null;
|
|
} else {
|
|
return validate(props, propName, componentName, location, propFullName);
|
|
}
|
|
}
|
|
|
|
var chainedCheckType = checkType.bind(null, false);
|
|
chainedCheckType.isRequired = checkType.bind(null, true);
|
|
|
|
return chainedCheckType;
|
|
}
|
|
|
|
function createPrimitiveTypeChecker(expectedType) {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
var propValue = props[propName];
|
|
var propType = getPropType(propValue);
|
|
if (propType !== expectedType) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
// `propValue` being instance of, say, date/regexp, pass the 'object'
|
|
// check, but we can offer a more precise error message here rather than
|
|
// 'of type `object`'.
|
|
var preciseType = getPreciseType(propValue);
|
|
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createAnyTypeChecker() {
|
|
return createChainableTypeChecker(emptyFunction.thatReturns(null));
|
|
}
|
|
|
|
function createArrayOfTypeChecker(typeChecker) {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
var propValue = props[propName];
|
|
if (!Array.isArray(propValue)) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
var propType = getPropType(propValue);
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
|
|
}
|
|
for (var i = 0; i < propValue.length; i++) {
|
|
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
if (error instanceof Error) {
|
|
return error;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createElementTypeChecker() {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
if (!ReactElement.isValidElement(props[propName])) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.'));
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createInstanceTypeChecker(expectedClass) {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
if (!(props[propName] instanceof expectedClass)) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
var expectedClassName = expectedClass.name || ANONYMOUS;
|
|
var actualClassName = getClassName(props[propName]);
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createEnumTypeChecker(expectedValues) {
|
|
if (!Array.isArray(expectedValues)) {
|
|
return createChainableTypeChecker(function () {
|
|
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
|
|
});
|
|
}
|
|
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
var propValue = props[propName];
|
|
for (var i = 0; i < expectedValues.length; i++) {
|
|
if (propValue === expectedValues[i]) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
var valuesString = JSON.stringify(expectedValues);
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createObjectOfTypeChecker(typeChecker) {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
var propValue = props[propName];
|
|
var propType = getPropType(propValue);
|
|
if (propType !== 'object') {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
|
|
}
|
|
for (var key in propValue) {
|
|
if (propValue.hasOwnProperty(key)) {
|
|
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
if (error instanceof Error) {
|
|
return error;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createUnionTypeChecker(arrayOfTypeCheckers) {
|
|
if (!Array.isArray(arrayOfTypeCheckers)) {
|
|
return createChainableTypeChecker(function () {
|
|
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
|
|
});
|
|
}
|
|
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
|
|
var checker = arrayOfTypeCheckers[i];
|
|
if (checker(props, propName, componentName, location, propFullName, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED') == null) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createNodeChecker() {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
if (!isNode(props[propName])) {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function createShapeTypeChecker(shapeTypes) {
|
|
function validate(props, propName, componentName, location, propFullName) {
|
|
var propValue = props[propName];
|
|
var propType = getPropType(propValue);
|
|
if (propType !== 'object') {
|
|
var locationName = ReactPropTypeLocationNames[location];
|
|
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
|
|
}
|
|
for (var key in shapeTypes) {
|
|
var checker = shapeTypes[key];
|
|
if (!checker) {
|
|
continue;
|
|
}
|
|
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
if (error) {
|
|
return error;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
return createChainableTypeChecker(validate);
|
|
}
|
|
|
|
function isNode(propValue) {
|
|
switch (typeof propValue) {
|
|
case 'number':
|
|
case 'string':
|
|
case 'undefined':
|
|
return true;
|
|
case 'boolean':
|
|
return !propValue;
|
|
case 'object':
|
|
if (Array.isArray(propValue)) {
|
|
return propValue.every(isNode);
|
|
}
|
|
if (propValue === null || ReactElement.isValidElement(propValue)) {
|
|
return true;
|
|
}
|
|
|
|
var iteratorFn = getIteratorFn(propValue);
|
|
if (iteratorFn) {
|
|
var iterator = iteratorFn.call(propValue);
|
|
var step;
|
|
if (iteratorFn !== propValue.entries) {
|
|
while (!(step = iterator.next()).done) {
|
|
if (!isNode(step.value)) {
|
|
return false;
|
|
}
|
|
}
|
|
} else {
|
|
// Iterator will provide entry [k,v] tuples rather than values.
|
|
while (!(step = iterator.next()).done) {
|
|
var entry = step.value;
|
|
if (entry) {
|
|
if (!isNode(entry[1])) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Equivalent of `typeof` but with special handling for array and regexp.
|
|
function getPropType(propValue) {
|
|
var propType = typeof propValue;
|
|
if (Array.isArray(propValue)) {
|
|
return 'array';
|
|
}
|
|
if (propValue instanceof RegExp) {
|
|
// Old webkits (at least until Android 4.0) return 'function' rather than
|
|
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
|
|
// passes PropTypes.object.
|
|
return 'object';
|
|
}
|
|
return propType;
|
|
}
|
|
|
|
// This handles more types than `getPropType`. Only used for error messages.
|
|
// See `createPrimitiveTypeChecker`.
|
|
function getPreciseType(propValue) {
|
|
var propType = getPropType(propValue);
|
|
if (propType === 'object') {
|
|
if (propValue instanceof Date) {
|
|
return 'date';
|
|
} else if (propValue instanceof RegExp) {
|
|
return 'regexp';
|
|
}
|
|
}
|
|
return propType;
|
|
}
|
|
|
|
// Returns class name of the object, if any.
|
|
function getClassName(propValue) {
|
|
if (!propValue.constructor || !propValue.constructor.name) {
|
|
return '<<anonymous>>';
|
|
}
|
|
return propValue.constructor.name;
|
|
}
|
|
|
|
module.exports = ReactPropTypes;
|
|
|
|
/***/ }),
|
|
/* 108 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getIteratorFn
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/* global Symbol */
|
|
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
|
|
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
|
|
|
|
/**
|
|
* Returns the iterator method function contained on the iterable object.
|
|
*
|
|
* Be sure to invoke the function with the iterable as context:
|
|
*
|
|
* var iteratorFn = getIteratorFn(myIterable);
|
|
* if (iteratorFn) {
|
|
* var iterator = iteratorFn.call(myIterable);
|
|
* ...
|
|
* }
|
|
*
|
|
* @param {?object} maybeIterable
|
|
* @return {?function}
|
|
*/
|
|
function getIteratorFn(maybeIterable) {
|
|
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
|
|
if (typeof iteratorFn === 'function') {
|
|
return iteratorFn;
|
|
}
|
|
}
|
|
|
|
module.exports = getIteratorFn;
|
|
|
|
/***/ }),
|
|
/* 109 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMOption
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactChildren = __webpack_require__(110);
|
|
var ReactDOMSelect = __webpack_require__(112);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var valueContextKey = ReactDOMSelect.valueContextKey;
|
|
|
|
/**
|
|
* Implements an <option> native component that warns when `selected` is set.
|
|
*/
|
|
var ReactDOMOption = {
|
|
mountWrapper: function (inst, props, context) {
|
|
// TODO (yungsters): Remove support for `selected` in <option>.
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined;
|
|
}
|
|
|
|
// Look up whether this option is 'selected' via context
|
|
var selectValue = context[valueContextKey];
|
|
|
|
// If context key is null (e.g., no specified value or after initial mount)
|
|
// or missing (e.g., for <datalist>), we don't change props.selected
|
|
var selected = null;
|
|
if (selectValue != null) {
|
|
selected = false;
|
|
if (Array.isArray(selectValue)) {
|
|
// multiple
|
|
for (var i = 0; i < selectValue.length; i++) {
|
|
if ('' + selectValue[i] === '' + props.value) {
|
|
selected = true;
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
selected = '' + selectValue === '' + props.value;
|
|
}
|
|
}
|
|
|
|
inst._wrapperState = { selected: selected };
|
|
},
|
|
|
|
getNativeProps: function (inst, props, context) {
|
|
var nativeProps = assign({ selected: undefined, children: undefined }, props);
|
|
|
|
// Read state only from initial mount because <select> updates value
|
|
// manually; we need the initial state only for server rendering
|
|
if (inst._wrapperState.selected != null) {
|
|
nativeProps.selected = inst._wrapperState.selected;
|
|
}
|
|
|
|
var content = '';
|
|
|
|
// Flatten children and warn if they aren't strings or numbers;
|
|
// invalid types are ignored.
|
|
ReactChildren.forEach(props.children, function (child) {
|
|
if (child == null) {
|
|
return;
|
|
}
|
|
if (typeof child === 'string' || typeof child === 'number') {
|
|
content += child;
|
|
} else {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined;
|
|
}
|
|
});
|
|
|
|
if (content) {
|
|
nativeProps.children = content;
|
|
}
|
|
|
|
return nativeProps;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactDOMOption;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 110 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactChildren
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var PooledClass = __webpack_require__(56);
|
|
var ReactElement = __webpack_require__(42);
|
|
|
|
var emptyFunction = __webpack_require__(15);
|
|
var traverseAllChildren = __webpack_require__(111);
|
|
|
|
var twoArgumentPooler = PooledClass.twoArgumentPooler;
|
|
var fourArgumentPooler = PooledClass.fourArgumentPooler;
|
|
|
|
var userProvidedKeyEscapeRegex = /\/(?!\/)/g;
|
|
function escapeUserProvidedKey(text) {
|
|
return ('' + text).replace(userProvidedKeyEscapeRegex, '//');
|
|
}
|
|
|
|
/**
|
|
* PooledClass representing the bookkeeping associated with performing a child
|
|
* traversal. Allows avoiding binding callbacks.
|
|
*
|
|
* @constructor ForEachBookKeeping
|
|
* @param {!function} forEachFunction Function to perform traversal with.
|
|
* @param {?*} forEachContext Context to perform context with.
|
|
*/
|
|
function ForEachBookKeeping(forEachFunction, forEachContext) {
|
|
this.func = forEachFunction;
|
|
this.context = forEachContext;
|
|
this.count = 0;
|
|
}
|
|
ForEachBookKeeping.prototype.destructor = function () {
|
|
this.func = null;
|
|
this.context = null;
|
|
this.count = 0;
|
|
};
|
|
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
|
|
|
|
function forEachSingleChild(bookKeeping, child, name) {
|
|
var func = bookKeeping.func;
|
|
var context = bookKeeping.context;
|
|
|
|
func.call(context, child, bookKeeping.count++);
|
|
}
|
|
|
|
/**
|
|
* Iterates through children that are typically specified as `props.children`.
|
|
*
|
|
* The provided forEachFunc(child, index) will be called for each
|
|
* leaf child.
|
|
*
|
|
* @param {?*} children Children tree container.
|
|
* @param {function(*, int)} forEachFunc
|
|
* @param {*} forEachContext Context for forEachContext.
|
|
*/
|
|
function forEachChildren(children, forEachFunc, forEachContext) {
|
|
if (children == null) {
|
|
return children;
|
|
}
|
|
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
|
|
traverseAllChildren(children, forEachSingleChild, traverseContext);
|
|
ForEachBookKeeping.release(traverseContext);
|
|
}
|
|
|
|
/**
|
|
* PooledClass representing the bookkeeping associated with performing a child
|
|
* mapping. Allows avoiding binding callbacks.
|
|
*
|
|
* @constructor MapBookKeeping
|
|
* @param {!*} mapResult Object containing the ordered map of results.
|
|
* @param {!function} mapFunction Function to perform mapping with.
|
|
* @param {?*} mapContext Context to perform mapping with.
|
|
*/
|
|
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
|
|
this.result = mapResult;
|
|
this.keyPrefix = keyPrefix;
|
|
this.func = mapFunction;
|
|
this.context = mapContext;
|
|
this.count = 0;
|
|
}
|
|
MapBookKeeping.prototype.destructor = function () {
|
|
this.result = null;
|
|
this.keyPrefix = null;
|
|
this.func = null;
|
|
this.context = null;
|
|
this.count = 0;
|
|
};
|
|
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
|
|
|
|
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
|
|
var result = bookKeeping.result;
|
|
var keyPrefix = bookKeeping.keyPrefix;
|
|
var func = bookKeeping.func;
|
|
var context = bookKeeping.context;
|
|
|
|
var mappedChild = func.call(context, child, bookKeeping.count++);
|
|
if (Array.isArray(mappedChild)) {
|
|
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
|
|
} else if (mappedChild != null) {
|
|
if (ReactElement.isValidElement(mappedChild)) {
|
|
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
|
|
// Keep both the (mapped) and old keys if they differ, just as
|
|
// traverseAllChildren used to do for objects as children
|
|
keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey);
|
|
}
|
|
result.push(mappedChild);
|
|
}
|
|
}
|
|
|
|
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
|
|
var escapedPrefix = '';
|
|
if (prefix != null) {
|
|
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
|
|
}
|
|
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
|
|
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
|
|
MapBookKeeping.release(traverseContext);
|
|
}
|
|
|
|
/**
|
|
* Maps children that are typically specified as `props.children`.
|
|
*
|
|
* The provided mapFunction(child, key, index) will be called for each
|
|
* leaf child.
|
|
*
|
|
* @param {?*} children Children tree container.
|
|
* @param {function(*, int)} func The map function.
|
|
* @param {*} context Context for mapFunction.
|
|
* @return {object} Object containing the ordered map of results.
|
|
*/
|
|
function mapChildren(children, func, context) {
|
|
if (children == null) {
|
|
return children;
|
|
}
|
|
var result = [];
|
|
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
|
|
return result;
|
|
}
|
|
|
|
function forEachSingleChildDummy(traverseContext, child, name) {
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Count the number of children that are typically specified as
|
|
* `props.children`.
|
|
*
|
|
* @param {?*} children Children tree container.
|
|
* @return {number} The number of children.
|
|
*/
|
|
function countChildren(children, context) {
|
|
return traverseAllChildren(children, forEachSingleChildDummy, null);
|
|
}
|
|
|
|
/**
|
|
* Flatten a children object (typically specified as `props.children`) and
|
|
* return an array with appropriately re-keyed children.
|
|
*/
|
|
function toArray(children) {
|
|
var result = [];
|
|
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
|
|
return result;
|
|
}
|
|
|
|
var ReactChildren = {
|
|
forEach: forEachChildren,
|
|
map: mapChildren,
|
|
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
|
|
count: countChildren,
|
|
toArray: toArray
|
|
};
|
|
|
|
module.exports = ReactChildren;
|
|
|
|
/***/ }),
|
|
/* 111 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule traverseAllChildren
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
|
|
var getIteratorFn = __webpack_require__(108);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
|
|
var SUBSEPARATOR = ':';
|
|
|
|
/**
|
|
* TODO: Test that a single child and an array with one item have the same key
|
|
* pattern.
|
|
*/
|
|
|
|
var userProvidedKeyEscaperLookup = {
|
|
'=': '=0',
|
|
'.': '=1',
|
|
':': '=2'
|
|
};
|
|
|
|
var userProvidedKeyEscapeRegex = /[=.:]/g;
|
|
|
|
var didWarnAboutMaps = false;
|
|
|
|
function userProvidedKeyEscaper(match) {
|
|
return userProvidedKeyEscaperLookup[match];
|
|
}
|
|
|
|
/**
|
|
* Generate a key string that identifies a component within a set.
|
|
*
|
|
* @param {*} component A component that could contain a manual key.
|
|
* @param {number} index Index that is used if a manual key is not provided.
|
|
* @return {string}
|
|
*/
|
|
function getComponentKey(component, index) {
|
|
if (component && component.key != null) {
|
|
// Explicit key
|
|
return wrapUserProvidedKey(component.key);
|
|
}
|
|
// Implicit key determined by the index in the set
|
|
return index.toString(36);
|
|
}
|
|
|
|
/**
|
|
* Escape a component key so that it is safe to use in a reactid.
|
|
*
|
|
* @param {*} text Component key to be escaped.
|
|
* @return {string} An escaped string.
|
|
*/
|
|
function escapeUserProvidedKey(text) {
|
|
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
|
|
}
|
|
|
|
/**
|
|
* Wrap a `key` value explicitly provided by the user to distinguish it from
|
|
* implicitly-generated keys generated by a component's index in its parent.
|
|
*
|
|
* @param {string} key Value of a user-provided `key` attribute
|
|
* @return {string}
|
|
*/
|
|
function wrapUserProvidedKey(key) {
|
|
return '$' + escapeUserProvidedKey(key);
|
|
}
|
|
|
|
/**
|
|
* @param {?*} children Children tree container.
|
|
* @param {!string} nameSoFar Name of the key path so far.
|
|
* @param {!function} callback Callback to invoke with each child found.
|
|
* @param {?*} traverseContext Used to pass information throughout the traversal
|
|
* process.
|
|
* @return {!number} The number of children in this subtree.
|
|
*/
|
|
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
|
|
var type = typeof children;
|
|
|
|
if (type === 'undefined' || type === 'boolean') {
|
|
// All of the above are perceived as null.
|
|
children = null;
|
|
}
|
|
|
|
if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) {
|
|
callback(traverseContext, children,
|
|
// If it's the only child, treat the name as if it was wrapped in an array
|
|
// so that it's consistent if the number of children grows.
|
|
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
|
|
return 1;
|
|
}
|
|
|
|
var child;
|
|
var nextName;
|
|
var subtreeCount = 0; // Count of children found in the current subtree.
|
|
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
|
|
|
|
if (Array.isArray(children)) {
|
|
for (var i = 0; i < children.length; i++) {
|
|
child = children[i];
|
|
nextName = nextNamePrefix + getComponentKey(child, i);
|
|
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
|
|
}
|
|
} else {
|
|
var iteratorFn = getIteratorFn(children);
|
|
if (iteratorFn) {
|
|
var iterator = iteratorFn.call(children);
|
|
var step;
|
|
if (iteratorFn !== children.entries) {
|
|
var ii = 0;
|
|
while (!(step = iterator.next()).done) {
|
|
child = step.value;
|
|
nextName = nextNamePrefix + getComponentKey(child, ii++);
|
|
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
|
|
}
|
|
} else {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined;
|
|
didWarnAboutMaps = true;
|
|
}
|
|
// Iterator will provide entry [k,v] tuples rather than values.
|
|
while (!(step = iterator.next()).done) {
|
|
var entry = step.value;
|
|
if (entry) {
|
|
child = entry[1];
|
|
nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
|
|
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
|
|
}
|
|
}
|
|
}
|
|
} else if (type === 'object') {
|
|
var addendum = '';
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
|
|
if (children._isReactElement) {
|
|
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
|
|
}
|
|
if (ReactCurrentOwner.current) {
|
|
var name = ReactCurrentOwner.current.getName();
|
|
if (name) {
|
|
addendum += ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
}
|
|
var childrenString = String(children);
|
|
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined;
|
|
}
|
|
}
|
|
|
|
return subtreeCount;
|
|
}
|
|
|
|
/**
|
|
* Traverses children that are typically specified as `props.children`, but
|
|
* might also be specified through attributes:
|
|
*
|
|
* - `traverseAllChildren(this.props.children, ...)`
|
|
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
|
|
*
|
|
* The `traverseContext` is an optional argument that is passed through the
|
|
* entire traversal. It can be used to store accumulations or anything else that
|
|
* the callback might find relevant.
|
|
*
|
|
* @param {?*} children Children tree object.
|
|
* @param {!function} callback To invoke upon traversing each child.
|
|
* @param {?*} traverseContext Context for traversal.
|
|
* @return {!number} The number of children in this subtree.
|
|
*/
|
|
function traverseAllChildren(children, callback, traverseContext) {
|
|
if (children == null) {
|
|
return 0;
|
|
}
|
|
|
|
return traverseAllChildrenImpl(children, '', callback, traverseContext);
|
|
}
|
|
|
|
module.exports = traverseAllChildren;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 112 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMSelect
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var LinkedValueUtils = __webpack_require__(106);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2);
|
|
|
|
function updateOptionsIfPendingUpdateAndMounted() {
|
|
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
|
|
this._wrapperState.pendingUpdate = false;
|
|
|
|
var props = this._currentElement.props;
|
|
var value = LinkedValueUtils.getValue(props);
|
|
|
|
if (value != null) {
|
|
updateOptions(this, Boolean(props.multiple), value);
|
|
}
|
|
}
|
|
}
|
|
|
|
function getDeclarationErrorAddendum(owner) {
|
|
if (owner) {
|
|
var name = owner.getName();
|
|
if (name) {
|
|
return ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
var valuePropNames = ['value', 'defaultValue'];
|
|
|
|
/**
|
|
* Validation function for `value` and `defaultValue`.
|
|
* @private
|
|
*/
|
|
function checkSelectPropTypes(inst, props) {
|
|
var owner = inst._currentElement._owner;
|
|
LinkedValueUtils.checkPropTypes('select', props, owner);
|
|
|
|
for (var i = 0; i < valuePropNames.length; i++) {
|
|
var propName = valuePropNames[i];
|
|
if (props[propName] == null) {
|
|
continue;
|
|
}
|
|
if (props.multiple) {
|
|
process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
|
|
} else {
|
|
process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param {ReactDOMComponent} inst
|
|
* @param {boolean} multiple
|
|
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
|
|
* @private
|
|
*/
|
|
function updateOptions(inst, multiple, propValue) {
|
|
var selectedValue, i;
|
|
var options = ReactMount.getNode(inst._rootNodeID).options;
|
|
|
|
if (multiple) {
|
|
selectedValue = {};
|
|
for (i = 0; i < propValue.length; i++) {
|
|
selectedValue['' + propValue[i]] = true;
|
|
}
|
|
for (i = 0; i < options.length; i++) {
|
|
var selected = selectedValue.hasOwnProperty(options[i].value);
|
|
if (options[i].selected !== selected) {
|
|
options[i].selected = selected;
|
|
}
|
|
}
|
|
} else {
|
|
// Do not set `select.value` as exact behavior isn't consistent across all
|
|
// browsers for all cases.
|
|
selectedValue = '' + propValue;
|
|
for (i = 0; i < options.length; i++) {
|
|
if (options[i].value === selectedValue) {
|
|
options[i].selected = true;
|
|
return;
|
|
}
|
|
}
|
|
if (options.length) {
|
|
options[0].selected = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements a <select> native component that allows optionally setting the
|
|
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
|
|
* stringable. If `multiple` is true, the prop must be an array of stringables.
|
|
*
|
|
* If `value` is not supplied (or null/undefined), user actions that change the
|
|
* selected option will trigger updates to the rendered options.
|
|
*
|
|
* If it is supplied (and not null/undefined), the rendered options will not
|
|
* update in response to user actions. Instead, the `value` prop must change in
|
|
* order for the rendered options to update.
|
|
*
|
|
* If `defaultValue` is provided, any options with the supplied values will be
|
|
* selected.
|
|
*/
|
|
var ReactDOMSelect = {
|
|
valueContextKey: valueContextKey,
|
|
|
|
getNativeProps: function (inst, props, context) {
|
|
return assign({}, props, {
|
|
onChange: inst._wrapperState.onChange,
|
|
value: undefined
|
|
});
|
|
},
|
|
|
|
mountWrapper: function (inst, props) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
checkSelectPropTypes(inst, props);
|
|
}
|
|
|
|
var value = LinkedValueUtils.getValue(props);
|
|
inst._wrapperState = {
|
|
pendingUpdate: false,
|
|
initialValue: value != null ? value : props.defaultValue,
|
|
onChange: _handleChange.bind(inst),
|
|
wasMultiple: Boolean(props.multiple)
|
|
};
|
|
},
|
|
|
|
processChildContext: function (inst, props, context) {
|
|
// Pass down initial value so initial generated markup has correct
|
|
// `selected` attributes
|
|
var childContext = assign({}, context);
|
|
childContext[valueContextKey] = inst._wrapperState.initialValue;
|
|
return childContext;
|
|
},
|
|
|
|
postUpdateWrapper: function (inst) {
|
|
var props = inst._currentElement.props;
|
|
|
|
// After the initial mount, we control selected-ness manually so don't pass
|
|
// the context value down
|
|
inst._wrapperState.initialValue = undefined;
|
|
|
|
var wasMultiple = inst._wrapperState.wasMultiple;
|
|
inst._wrapperState.wasMultiple = Boolean(props.multiple);
|
|
|
|
var value = LinkedValueUtils.getValue(props);
|
|
if (value != null) {
|
|
inst._wrapperState.pendingUpdate = false;
|
|
updateOptions(inst, Boolean(props.multiple), value);
|
|
} else if (wasMultiple !== Boolean(props.multiple)) {
|
|
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
|
|
if (props.defaultValue != null) {
|
|
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
|
|
} else {
|
|
// Revert the select back to its default unselected state.
|
|
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
function _handleChange(event) {
|
|
var props = this._currentElement.props;
|
|
var returnValue = LinkedValueUtils.executeOnChange(props, event);
|
|
|
|
this._wrapperState.pendingUpdate = true;
|
|
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
|
|
return returnValue;
|
|
}
|
|
|
|
module.exports = ReactDOMSelect;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 113 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMTextarea
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var LinkedValueUtils = __webpack_require__(106);
|
|
var ReactDOMIDOperations = __webpack_require__(27);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
function forceUpdateIfMounted() {
|
|
if (this._rootNodeID) {
|
|
// DOM component is still mounted; update
|
|
ReactDOMTextarea.updateWrapper(this);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements a <textarea> native component that allows setting `value`, and
|
|
* `defaultValue`. This differs from the traditional DOM API because value is
|
|
* usually set as PCDATA children.
|
|
*
|
|
* If `value` is not supplied (or null/undefined), user actions that affect the
|
|
* value will trigger updates to the element.
|
|
*
|
|
* If `value` is supplied (and not null/undefined), the rendered element will
|
|
* not trigger updates to the element. Instead, the `value` prop must change in
|
|
* order for the rendered element to be updated.
|
|
*
|
|
* The rendered element will be initialized with an empty value, the prop
|
|
* `defaultValue` if specified, or the children content (deprecated).
|
|
*/
|
|
var ReactDOMTextarea = {
|
|
getNativeProps: function (inst, props, context) {
|
|
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined;
|
|
|
|
// Always set children to the same thing. In IE9, the selection range will
|
|
// get reset if `textContent` is mutated.
|
|
var nativeProps = assign({}, props, {
|
|
defaultValue: undefined,
|
|
value: undefined,
|
|
children: inst._wrapperState.initialValue,
|
|
onChange: inst._wrapperState.onChange
|
|
});
|
|
|
|
return nativeProps;
|
|
},
|
|
|
|
mountWrapper: function (inst, props) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
|
|
}
|
|
|
|
var defaultValue = props.defaultValue;
|
|
// TODO (yungsters): Remove support for children content in <textarea>.
|
|
var children = props.children;
|
|
if (children != null) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined;
|
|
}
|
|
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined;
|
|
if (Array.isArray(children)) {
|
|
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined;
|
|
children = children[0];
|
|
}
|
|
|
|
defaultValue = '' + children;
|
|
}
|
|
if (defaultValue == null) {
|
|
defaultValue = '';
|
|
}
|
|
var value = LinkedValueUtils.getValue(props);
|
|
|
|
inst._wrapperState = {
|
|
// We save the initial value so that `ReactDOMComponent` doesn't update
|
|
// `textContent` (unnecessary since we update value).
|
|
// The initial value can be a boolean or object so that's why it's
|
|
// forced to be a string.
|
|
initialValue: '' + (value != null ? value : defaultValue),
|
|
onChange: _handleChange.bind(inst)
|
|
};
|
|
},
|
|
|
|
updateWrapper: function (inst) {
|
|
var props = inst._currentElement.props;
|
|
var value = LinkedValueUtils.getValue(props);
|
|
if (value != null) {
|
|
// Cast `value` to a string to ensure the value is set correctly. While
|
|
// browsers typically do this as necessary, jsdom doesn't.
|
|
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
|
|
}
|
|
}
|
|
};
|
|
|
|
function _handleChange(event) {
|
|
var props = this._currentElement.props;
|
|
var returnValue = LinkedValueUtils.executeOnChange(props, event);
|
|
ReactUpdates.asap(forceUpdateIfMounted, this);
|
|
return returnValue;
|
|
}
|
|
|
|
module.exports = ReactDOMTextarea;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 114 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactMultiChild
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactComponentEnvironment = __webpack_require__(64);
|
|
var ReactMultiChildUpdateTypes = __webpack_require__(16);
|
|
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
var ReactReconciler = __webpack_require__(50);
|
|
var ReactChildReconciler = __webpack_require__(115);
|
|
|
|
var flattenChildren = __webpack_require__(116);
|
|
|
|
/**
|
|
* Updating children of a component may trigger recursive updates. The depth is
|
|
* used to batch recursive updates to render markup more efficiently.
|
|
*
|
|
* @type {number}
|
|
* @private
|
|
*/
|
|
var updateDepth = 0;
|
|
|
|
/**
|
|
* Queue of update configuration objects.
|
|
*
|
|
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
|
|
*
|
|
* @type {array<object>}
|
|
* @private
|
|
*/
|
|
var updateQueue = [];
|
|
|
|
/**
|
|
* Queue of markup to be rendered.
|
|
*
|
|
* @type {array<string>}
|
|
* @private
|
|
*/
|
|
var markupQueue = [];
|
|
|
|
/**
|
|
* Enqueues markup to be rendered and inserted at a supplied index.
|
|
*
|
|
* @param {string} parentID ID of the parent component.
|
|
* @param {string} markup Markup that renders into an element.
|
|
* @param {number} toIndex Destination index.
|
|
* @private
|
|
*/
|
|
function enqueueInsertMarkup(parentID, markup, toIndex) {
|
|
// NOTE: Null values reduce hidden classes.
|
|
updateQueue.push({
|
|
parentID: parentID,
|
|
parentNode: null,
|
|
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
|
|
markupIndex: markupQueue.push(markup) - 1,
|
|
content: null,
|
|
fromIndex: null,
|
|
toIndex: toIndex
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Enqueues moving an existing element to another index.
|
|
*
|
|
* @param {string} parentID ID of the parent component.
|
|
* @param {number} fromIndex Source index of the existing element.
|
|
* @param {number} toIndex Destination index of the element.
|
|
* @private
|
|
*/
|
|
function enqueueMove(parentID, fromIndex, toIndex) {
|
|
// NOTE: Null values reduce hidden classes.
|
|
updateQueue.push({
|
|
parentID: parentID,
|
|
parentNode: null,
|
|
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
|
|
markupIndex: null,
|
|
content: null,
|
|
fromIndex: fromIndex,
|
|
toIndex: toIndex
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Enqueues removing an element at an index.
|
|
*
|
|
* @param {string} parentID ID of the parent component.
|
|
* @param {number} fromIndex Index of the element to remove.
|
|
* @private
|
|
*/
|
|
function enqueueRemove(parentID, fromIndex) {
|
|
// NOTE: Null values reduce hidden classes.
|
|
updateQueue.push({
|
|
parentID: parentID,
|
|
parentNode: null,
|
|
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
|
|
markupIndex: null,
|
|
content: null,
|
|
fromIndex: fromIndex,
|
|
toIndex: null
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Enqueues setting the markup of a node.
|
|
*
|
|
* @param {string} parentID ID of the parent component.
|
|
* @param {string} markup Markup that renders into an element.
|
|
* @private
|
|
*/
|
|
function enqueueSetMarkup(parentID, markup) {
|
|
// NOTE: Null values reduce hidden classes.
|
|
updateQueue.push({
|
|
parentID: parentID,
|
|
parentNode: null,
|
|
type: ReactMultiChildUpdateTypes.SET_MARKUP,
|
|
markupIndex: null,
|
|
content: markup,
|
|
fromIndex: null,
|
|
toIndex: null
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Enqueues setting the text content.
|
|
*
|
|
* @param {string} parentID ID of the parent component.
|
|
* @param {string} textContent Text content to set.
|
|
* @private
|
|
*/
|
|
function enqueueTextContent(parentID, textContent) {
|
|
// NOTE: Null values reduce hidden classes.
|
|
updateQueue.push({
|
|
parentID: parentID,
|
|
parentNode: null,
|
|
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
|
|
markupIndex: null,
|
|
content: textContent,
|
|
fromIndex: null,
|
|
toIndex: null
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Processes any enqueued updates.
|
|
*
|
|
* @private
|
|
*/
|
|
function processQueue() {
|
|
if (updateQueue.length) {
|
|
ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue);
|
|
clearQueue();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Clears any enqueued updates.
|
|
*
|
|
* @private
|
|
*/
|
|
function clearQueue() {
|
|
updateQueue.length = 0;
|
|
markupQueue.length = 0;
|
|
}
|
|
|
|
/**
|
|
* ReactMultiChild are capable of reconciling multiple children.
|
|
*
|
|
* @class ReactMultiChild
|
|
* @internal
|
|
*/
|
|
var ReactMultiChild = {
|
|
|
|
/**
|
|
* Provides common functionality for components that must reconcile multiple
|
|
* children. This is used by `ReactDOMComponent` to mount, update, and
|
|
* unmount child components.
|
|
*
|
|
* @lends {ReactMultiChild.prototype}
|
|
*/
|
|
Mixin: {
|
|
|
|
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (this._currentElement) {
|
|
try {
|
|
ReactCurrentOwner.current = this._currentElement._owner;
|
|
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
|
|
} finally {
|
|
ReactCurrentOwner.current = null;
|
|
}
|
|
}
|
|
}
|
|
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
|
|
},
|
|
|
|
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) {
|
|
var nextChildren;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (this._currentElement) {
|
|
try {
|
|
ReactCurrentOwner.current = this._currentElement._owner;
|
|
nextChildren = flattenChildren(nextNestedChildrenElements);
|
|
} finally {
|
|
ReactCurrentOwner.current = null;
|
|
}
|
|
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
|
|
}
|
|
}
|
|
nextChildren = flattenChildren(nextNestedChildrenElements);
|
|
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
|
|
},
|
|
|
|
/**
|
|
* Generates a "mount image" for each of the supplied children. In the case
|
|
* of `ReactDOMComponent`, a mount image is a string of markup.
|
|
*
|
|
* @param {?object} nestedChildren Nested child maps.
|
|
* @return {array} An array of mounted representations.
|
|
* @internal
|
|
*/
|
|
mountChildren: function (nestedChildren, transaction, context) {
|
|
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
|
|
this._renderedChildren = children;
|
|
var mountImages = [];
|
|
var index = 0;
|
|
for (var name in children) {
|
|
if (children.hasOwnProperty(name)) {
|
|
var child = children[name];
|
|
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
|
|
var rootID = this._rootNodeID + name;
|
|
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
|
|
child._mountIndex = index++;
|
|
mountImages.push(mountImage);
|
|
}
|
|
}
|
|
return mountImages;
|
|
},
|
|
|
|
/**
|
|
* Replaces any rendered children with a text content string.
|
|
*
|
|
* @param {string} nextContent String of content.
|
|
* @internal
|
|
*/
|
|
updateTextContent: function (nextContent) {
|
|
updateDepth++;
|
|
var errorThrown = true;
|
|
try {
|
|
var prevChildren = this._renderedChildren;
|
|
// Remove any rendered children.
|
|
ReactChildReconciler.unmountChildren(prevChildren);
|
|
// TODO: The setTextContent operation should be enough
|
|
for (var name in prevChildren) {
|
|
if (prevChildren.hasOwnProperty(name)) {
|
|
this._unmountChild(prevChildren[name]);
|
|
}
|
|
}
|
|
// Set new text content.
|
|
this.setTextContent(nextContent);
|
|
errorThrown = false;
|
|
} finally {
|
|
updateDepth--;
|
|
if (!updateDepth) {
|
|
if (errorThrown) {
|
|
clearQueue();
|
|
} else {
|
|
processQueue();
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Replaces any rendered children with a markup string.
|
|
*
|
|
* @param {string} nextMarkup String of markup.
|
|
* @internal
|
|
*/
|
|
updateMarkup: function (nextMarkup) {
|
|
updateDepth++;
|
|
var errorThrown = true;
|
|
try {
|
|
var prevChildren = this._renderedChildren;
|
|
// Remove any rendered children.
|
|
ReactChildReconciler.unmountChildren(prevChildren);
|
|
for (var name in prevChildren) {
|
|
if (prevChildren.hasOwnProperty(name)) {
|
|
this._unmountChildByName(prevChildren[name], name);
|
|
}
|
|
}
|
|
this.setMarkup(nextMarkup);
|
|
errorThrown = false;
|
|
} finally {
|
|
updateDepth--;
|
|
if (!updateDepth) {
|
|
if (errorThrown) {
|
|
clearQueue();
|
|
} else {
|
|
processQueue();
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Updates the rendered children with new children.
|
|
*
|
|
* @param {?object} nextNestedChildrenElements Nested child element maps.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
*/
|
|
updateChildren: function (nextNestedChildrenElements, transaction, context) {
|
|
updateDepth++;
|
|
var errorThrown = true;
|
|
try {
|
|
this._updateChildren(nextNestedChildrenElements, transaction, context);
|
|
errorThrown = false;
|
|
} finally {
|
|
updateDepth--;
|
|
if (!updateDepth) {
|
|
if (errorThrown) {
|
|
clearQueue();
|
|
} else {
|
|
processQueue();
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Improve performance by isolating this hot code path from the try/catch
|
|
* block in `updateChildren`.
|
|
*
|
|
* @param {?object} nextNestedChildrenElements Nested child element maps.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @final
|
|
* @protected
|
|
*/
|
|
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
|
|
var prevChildren = this._renderedChildren;
|
|
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context);
|
|
this._renderedChildren = nextChildren;
|
|
if (!nextChildren && !prevChildren) {
|
|
return;
|
|
}
|
|
var name;
|
|
// `nextIndex` will increment for each child in `nextChildren`, but
|
|
// `lastIndex` will be the last index visited in `prevChildren`.
|
|
var lastIndex = 0;
|
|
var nextIndex = 0;
|
|
for (name in nextChildren) {
|
|
if (!nextChildren.hasOwnProperty(name)) {
|
|
continue;
|
|
}
|
|
var prevChild = prevChildren && prevChildren[name];
|
|
var nextChild = nextChildren[name];
|
|
if (prevChild === nextChild) {
|
|
this.moveChild(prevChild, nextIndex, lastIndex);
|
|
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
|
|
prevChild._mountIndex = nextIndex;
|
|
} else {
|
|
if (prevChild) {
|
|
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
|
|
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
|
|
this._unmountChild(prevChild);
|
|
}
|
|
// The child must be instantiated before it's mounted.
|
|
this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context);
|
|
}
|
|
nextIndex++;
|
|
}
|
|
// Remove children that are no longer present.
|
|
for (name in prevChildren) {
|
|
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
|
|
this._unmountChild(prevChildren[name]);
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Unmounts all rendered children. This should be used to clean up children
|
|
* when this component is unmounted.
|
|
*
|
|
* @internal
|
|
*/
|
|
unmountChildren: function () {
|
|
var renderedChildren = this._renderedChildren;
|
|
ReactChildReconciler.unmountChildren(renderedChildren);
|
|
this._renderedChildren = null;
|
|
},
|
|
|
|
/**
|
|
* Moves a child component to the supplied index.
|
|
*
|
|
* @param {ReactComponent} child Component to move.
|
|
* @param {number} toIndex Destination index of the element.
|
|
* @param {number} lastIndex Last index visited of the siblings of `child`.
|
|
* @protected
|
|
*/
|
|
moveChild: function (child, toIndex, lastIndex) {
|
|
// If the index of `child` is less than `lastIndex`, then it needs to
|
|
// be moved. Otherwise, we do not need to move it because a child will be
|
|
// inserted or moved before `child`.
|
|
if (child._mountIndex < lastIndex) {
|
|
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Creates a child component.
|
|
*
|
|
* @param {ReactComponent} child Component to create.
|
|
* @param {string} mountImage Markup to insert.
|
|
* @protected
|
|
*/
|
|
createChild: function (child, mountImage) {
|
|
enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex);
|
|
},
|
|
|
|
/**
|
|
* Removes a child component.
|
|
*
|
|
* @param {ReactComponent} child Child to remove.
|
|
* @protected
|
|
*/
|
|
removeChild: function (child) {
|
|
enqueueRemove(this._rootNodeID, child._mountIndex);
|
|
},
|
|
|
|
/**
|
|
* Sets this text content string.
|
|
*
|
|
* @param {string} textContent Text content to set.
|
|
* @protected
|
|
*/
|
|
setTextContent: function (textContent) {
|
|
enqueueTextContent(this._rootNodeID, textContent);
|
|
},
|
|
|
|
/**
|
|
* Sets this markup string.
|
|
*
|
|
* @param {string} markup Markup to set.
|
|
* @protected
|
|
*/
|
|
setMarkup: function (markup) {
|
|
enqueueSetMarkup(this._rootNodeID, markup);
|
|
},
|
|
|
|
/**
|
|
* Mounts a child with the supplied name.
|
|
*
|
|
* NOTE: This is part of `updateChildren` and is here for readability.
|
|
*
|
|
* @param {ReactComponent} child Component to mount.
|
|
* @param {string} name Name of the child.
|
|
* @param {number} index Index at which to insert the child.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @private
|
|
*/
|
|
_mountChildByNameAtIndex: function (child, name, index, transaction, context) {
|
|
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
|
|
var rootID = this._rootNodeID + name;
|
|
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
|
|
child._mountIndex = index;
|
|
this.createChild(child, mountImage);
|
|
},
|
|
|
|
/**
|
|
* Unmounts a rendered child.
|
|
*
|
|
* NOTE: This is part of `updateChildren` and is here for readability.
|
|
*
|
|
* @param {ReactComponent} child Component to unmount.
|
|
* @private
|
|
*/
|
|
_unmountChild: function (child) {
|
|
this.removeChild(child);
|
|
child._mountIndex = null;
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactMultiChild;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 115 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactChildReconciler
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactReconciler = __webpack_require__(50);
|
|
|
|
var instantiateReactComponent = __webpack_require__(62);
|
|
var shouldUpdateReactComponent = __webpack_require__(67);
|
|
var traverseAllChildren = __webpack_require__(111);
|
|
var warning = __webpack_require__(25);
|
|
|
|
function instantiateChild(childInstances, child, name) {
|
|
// We found a component instance.
|
|
var keyUnique = childInstances[name] === undefined;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
|
|
}
|
|
if (child != null && keyUnique) {
|
|
childInstances[name] = instantiateReactComponent(child, null);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* ReactChildReconciler provides helpers for initializing or updating a set of
|
|
* children. Its output is suitable for passing it onto ReactMultiChild which
|
|
* does diffed reordering and insertion.
|
|
*/
|
|
var ReactChildReconciler = {
|
|
/**
|
|
* Generates a "mount image" for each of the supplied children. In the case
|
|
* of `ReactDOMComponent`, a mount image is a string of markup.
|
|
*
|
|
* @param {?object} nestedChildNodes Nested child maps.
|
|
* @return {?object} A set of child instances.
|
|
* @internal
|
|
*/
|
|
instantiateChildren: function (nestedChildNodes, transaction, context) {
|
|
if (nestedChildNodes == null) {
|
|
return null;
|
|
}
|
|
var childInstances = {};
|
|
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
|
|
return childInstances;
|
|
},
|
|
|
|
/**
|
|
* Updates the rendered children and returns a new set of children.
|
|
*
|
|
* @param {?object} prevChildren Previously initialized set of children.
|
|
* @param {?object} nextChildren Flat child element maps.
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @param {object} context
|
|
* @return {?object} A new set of child instances.
|
|
* @internal
|
|
*/
|
|
updateChildren: function (prevChildren, nextChildren, transaction, context) {
|
|
// We currently don't have a way to track moves here but if we use iterators
|
|
// instead of for..in we can zip the iterators and check if an item has
|
|
// moved.
|
|
// TODO: If nothing has changed, return the prevChildren object so that we
|
|
// can quickly bailout if nothing has changed.
|
|
if (!nextChildren && !prevChildren) {
|
|
return null;
|
|
}
|
|
var name;
|
|
for (name in nextChildren) {
|
|
if (!nextChildren.hasOwnProperty(name)) {
|
|
continue;
|
|
}
|
|
var prevChild = prevChildren && prevChildren[name];
|
|
var prevElement = prevChild && prevChild._currentElement;
|
|
var nextElement = nextChildren[name];
|
|
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
|
|
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
|
|
nextChildren[name] = prevChild;
|
|
} else {
|
|
if (prevChild) {
|
|
ReactReconciler.unmountComponent(prevChild, name);
|
|
}
|
|
// The child must be instantiated before it's mounted.
|
|
var nextChildInstance = instantiateReactComponent(nextElement, null);
|
|
nextChildren[name] = nextChildInstance;
|
|
}
|
|
}
|
|
// Unmount children that are no longer present.
|
|
for (name in prevChildren) {
|
|
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
|
|
ReactReconciler.unmountComponent(prevChildren[name]);
|
|
}
|
|
}
|
|
return nextChildren;
|
|
},
|
|
|
|
/**
|
|
* Unmounts all rendered children. This should be used to clean up children
|
|
* when this component is unmounted.
|
|
*
|
|
* @param {?object} renderedChildren Previously initialized set of children.
|
|
* @internal
|
|
*/
|
|
unmountChildren: function (renderedChildren) {
|
|
for (var name in renderedChildren) {
|
|
if (renderedChildren.hasOwnProperty(name)) {
|
|
var renderedChild = renderedChildren[name];
|
|
ReactReconciler.unmountComponent(renderedChild);
|
|
}
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactChildReconciler;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 116 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule flattenChildren
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var traverseAllChildren = __webpack_require__(111);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* @param {function} traverseContext Context passed through traversal.
|
|
* @param {?ReactComponent} child React child component.
|
|
* @param {!string} name String name of key path to child.
|
|
*/
|
|
function flattenSingleChildIntoContext(traverseContext, child, name) {
|
|
// We found a component instance.
|
|
var result = traverseContext;
|
|
var keyUnique = result[name] === undefined;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
|
|
}
|
|
if (keyUnique && child != null) {
|
|
result[name] = child;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Flattens children that are typically specified as `props.children`. Any null
|
|
* children will not be included in the resulting object.
|
|
* @return {!object} flattened children keyed by name.
|
|
*/
|
|
function flattenChildren(children) {
|
|
if (children == null) {
|
|
return children;
|
|
}
|
|
var result = {};
|
|
traverseAllChildren(children, flattenSingleChildIntoContext, result);
|
|
return result;
|
|
}
|
|
|
|
module.exports = flattenChildren;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 117 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule shallowEqual
|
|
* @typechecks
|
|
*
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
|
|
/**
|
|
* Performs equality by iterating through keys on an object and returning false
|
|
* when any key has values which are not strictly equal between the arguments.
|
|
* Returns true when the values of all keys are strictly equal.
|
|
*/
|
|
function shallowEqual(objA, objB) {
|
|
if (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.
|
|
var bHasOwnProperty = hasOwnProperty.bind(objB);
|
|
for (var i = 0; i < keysA.length; i++) {
|
|
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
module.exports = shallowEqual;
|
|
|
|
/***/ }),
|
|
/* 118 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactEventListener
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventListener = __webpack_require__(119);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var PooledClass = __webpack_require__(56);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var getEventTarget = __webpack_require__(81);
|
|
var getUnboundedScrollPosition = __webpack_require__(120);
|
|
|
|
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
|
|
|
|
/**
|
|
* Finds the parent React component of `node`.
|
|
*
|
|
* @param {*} node
|
|
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
|
|
* is not nested.
|
|
*/
|
|
function findParent(node) {
|
|
// 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.
|
|
var nodeID = ReactMount.getID(node);
|
|
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
|
|
var container = ReactMount.findReactContainerForID(rootID);
|
|
var parent = ReactMount.getFirstReactDOM(container);
|
|
return parent;
|
|
}
|
|
|
|
// Used to store ancestor hierarchy in top level callback
|
|
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
|
|
this.topLevelType = topLevelType;
|
|
this.nativeEvent = nativeEvent;
|
|
this.ancestors = [];
|
|
}
|
|
assign(TopLevelCallbackBookKeeping.prototype, {
|
|
destructor: function () {
|
|
this.topLevelType = null;
|
|
this.nativeEvent = null;
|
|
this.ancestors.length = 0;
|
|
}
|
|
});
|
|
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
|
|
|
|
function handleTopLevelImpl(bookKeeping) {
|
|
// TODO: Re-enable event.path handling
|
|
//
|
|
// if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) {
|
|
// // New browsers have a path attribute on native events
|
|
// handleTopLevelWithPath(bookKeeping);
|
|
// } else {
|
|
// // Legacy browsers don't have a path attribute on native events
|
|
// handleTopLevelWithoutPath(bookKeeping);
|
|
// }
|
|
|
|
void handleTopLevelWithPath; // temporarily unused
|
|
handleTopLevelWithoutPath(bookKeeping);
|
|
}
|
|
|
|
// Legacy browsers don't have a path attribute on native events
|
|
function handleTopLevelWithoutPath(bookKeeping) {
|
|
var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window;
|
|
|
|
// 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 = topLevelTarget;
|
|
while (ancestor) {
|
|
bookKeeping.ancestors.push(ancestor);
|
|
ancestor = findParent(ancestor);
|
|
}
|
|
|
|
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
|
|
topLevelTarget = bookKeeping.ancestors[i];
|
|
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
|
|
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
|
|
}
|
|
}
|
|
|
|
// New browsers have a path attribute on native events
|
|
function handleTopLevelWithPath(bookKeeping) {
|
|
var path = bookKeeping.nativeEvent.path;
|
|
var currentNativeTarget = path[0];
|
|
var eventsFired = 0;
|
|
for (var i = 0; i < path.length; i++) {
|
|
var currentPathElement = path[i];
|
|
if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) {
|
|
currentNativeTarget = path[i + 1];
|
|
}
|
|
// TODO: slow
|
|
var reactParent = ReactMount.getFirstReactDOM(currentPathElement);
|
|
if (reactParent === currentPathElement) {
|
|
var currentPathElementID = ReactMount.getID(currentPathElement);
|
|
var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID);
|
|
bookKeeping.ancestors.push(currentPathElement);
|
|
|
|
var topLevelTargetID = ReactMount.getID(currentPathElement) || '';
|
|
eventsFired++;
|
|
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget);
|
|
|
|
// Jump to the root of this React render tree
|
|
while (currentPathElementID !== newRootID) {
|
|
i++;
|
|
currentPathElement = path[i];
|
|
currentPathElementID = ReactMount.getID(currentPathElement);
|
|
}
|
|
}
|
|
}
|
|
if (eventsFired === 0) {
|
|
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
|
|
}
|
|
}
|
|
|
|
function scrollValueMonitor(cb) {
|
|
var scrollPosition = getUnboundedScrollPosition(window);
|
|
cb(scrollPosition);
|
|
}
|
|
|
|
var ReactEventListener = {
|
|
_enabled: true,
|
|
_handleTopLevel: null,
|
|
|
|
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
|
|
|
|
setHandleTopLevel: function (handleTopLevel) {
|
|
ReactEventListener._handleTopLevel = handleTopLevel;
|
|
},
|
|
|
|
setEnabled: function (enabled) {
|
|
ReactEventListener._enabled = !!enabled;
|
|
},
|
|
|
|
isEnabled: function () {
|
|
return ReactEventListener._enabled;
|
|
},
|
|
|
|
/**
|
|
* Traps top-level events by using event bubbling.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {string} handlerBaseName Event name (e.g. "click").
|
|
* @param {object} handle Element on which to attach listener.
|
|
* @return {?object} An object with a remove function which will forcefully
|
|
* remove the listener.
|
|
* @internal
|
|
*/
|
|
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
|
|
var element = handle;
|
|
if (!element) {
|
|
return null;
|
|
}
|
|
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
|
|
},
|
|
|
|
/**
|
|
* Traps a top-level event by using event capturing.
|
|
*
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {string} handlerBaseName Event name (e.g. "click").
|
|
* @param {object} handle Element on which to attach listener.
|
|
* @return {?object} An object with a remove function which will forcefully
|
|
* remove the listener.
|
|
* @internal
|
|
*/
|
|
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
|
|
var element = handle;
|
|
if (!element) {
|
|
return null;
|
|
}
|
|
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
|
|
},
|
|
|
|
monitorScrollValue: function (refresh) {
|
|
var callback = scrollValueMonitor.bind(null, refresh);
|
|
EventListener.listen(window, 'scroll', callback);
|
|
},
|
|
|
|
dispatchEvent: function (topLevelType, nativeEvent) {
|
|
if (!ReactEventListener._enabled) {
|
|
return;
|
|
}
|
|
|
|
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
|
|
try {
|
|
// Event queue being processed in the same cycle allows
|
|
// `preventDefault`.
|
|
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
|
|
} finally {
|
|
TopLevelCallbackBookKeeping.release(bookKeeping);
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = ReactEventListener;
|
|
|
|
/***/ }),
|
|
/* 119 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* @providesModule EventListener
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var emptyFunction = __webpack_require__(15);
|
|
|
|
/**
|
|
* Upstream version of event listener. Does not take into account specific
|
|
* nature of platform.
|
|
*/
|
|
var EventListener = {
|
|
/**
|
|
* Listen to DOM events during the bubble phase.
|
|
*
|
|
* @param {DOMEventTarget} target DOM element to register listener on.
|
|
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
|
|
* @param {function} callback Callback function.
|
|
* @return {object} Object with a `remove` method.
|
|
*/
|
|
listen: function (target, eventType, callback) {
|
|
if (target.addEventListener) {
|
|
target.addEventListener(eventType, callback, false);
|
|
return {
|
|
remove: function () {
|
|
target.removeEventListener(eventType, callback, false);
|
|
}
|
|
};
|
|
} else if (target.attachEvent) {
|
|
target.attachEvent('on' + eventType, callback);
|
|
return {
|
|
remove: function () {
|
|
target.detachEvent('on' + eventType, callback);
|
|
}
|
|
};
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Listen to DOM events during the capture phase.
|
|
*
|
|
* @param {DOMEventTarget} target DOM element to register listener on.
|
|
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
|
|
* @param {function} callback Callback function.
|
|
* @return {object} Object with a `remove` method.
|
|
*/
|
|
capture: function (target, eventType, callback) {
|
|
if (target.addEventListener) {
|
|
target.addEventListener(eventType, callback, true);
|
|
return {
|
|
remove: function () {
|
|
target.removeEventListener(eventType, callback, true);
|
|
}
|
|
};
|
|
} else {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
|
|
}
|
|
return {
|
|
remove: emptyFunction
|
|
};
|
|
}
|
|
},
|
|
|
|
registerDefault: function () {}
|
|
};
|
|
|
|
module.exports = EventListener;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 120 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getUnboundedScrollPosition
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Gets the scroll position of the supplied element or window.
|
|
*
|
|
* The return values are unbounded, unlike `getScrollPosition`. This means they
|
|
* may be negative or exceed the element boundaries (which is possible using
|
|
* inertial scrolling).
|
|
*
|
|
* @param {DOMWindow|DOMElement} scrollable
|
|
* @return {object} Map with `x` and `y` keys.
|
|
*/
|
|
function getUnboundedScrollPosition(scrollable) {
|
|
if (scrollable === window) {
|
|
return {
|
|
x: window.pageXOffset || document.documentElement.scrollLeft,
|
|
y: window.pageYOffset || document.documentElement.scrollTop
|
|
};
|
|
}
|
|
return {
|
|
x: scrollable.scrollLeft,
|
|
y: scrollable.scrollTop
|
|
};
|
|
}
|
|
|
|
module.exports = getUnboundedScrollPosition;
|
|
|
|
/***/ }),
|
|
/* 121 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactInjection
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
var EventPluginHub = __webpack_require__(31);
|
|
var ReactComponentEnvironment = __webpack_require__(64);
|
|
var ReactClass = __webpack_require__(122);
|
|
var ReactEmptyComponent = __webpack_require__(68);
|
|
var ReactBrowserEventEmitter = __webpack_require__(29);
|
|
var ReactNativeComponent = __webpack_require__(69);
|
|
var ReactPerf = __webpack_require__(18);
|
|
var ReactRootIndex = __webpack_require__(46);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var ReactInjection = {
|
|
Component: ReactComponentEnvironment.injection,
|
|
Class: ReactClass.injection,
|
|
DOMProperty: DOMProperty.injection,
|
|
EmptyComponent: ReactEmptyComponent.injection,
|
|
EventPluginHub: EventPluginHub.injection,
|
|
EventEmitter: ReactBrowserEventEmitter.injection,
|
|
NativeComponent: ReactNativeComponent.injection,
|
|
Perf: ReactPerf.injection,
|
|
RootIndex: ReactRootIndex.injection,
|
|
Updates: ReactUpdates.injection
|
|
};
|
|
|
|
module.exports = ReactInjection;
|
|
|
|
/***/ }),
|
|
/* 122 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactClass
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactComponent = __webpack_require__(123);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactPropTypeLocations = __webpack_require__(65);
|
|
var ReactPropTypeLocationNames = __webpack_require__(66);
|
|
var ReactNoopUpdateQueue = __webpack_require__(124);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyObject = __webpack_require__(58);
|
|
var invariant = __webpack_require__(13);
|
|
var keyMirror = __webpack_require__(17);
|
|
var keyOf = __webpack_require__(79);
|
|
var warning = __webpack_require__(25);
|
|
|
|
var MIXINS_KEY = keyOf({ mixins: null });
|
|
|
|
/**
|
|
* Policies that describe methods in `ReactClassInterface`.
|
|
*/
|
|
var SpecPolicy = keyMirror({
|
|
/**
|
|
* These methods may be defined only once by the class specification or mixin.
|
|
*/
|
|
DEFINE_ONCE: null,
|
|
/**
|
|
* These methods may be defined by both the class specification and mixins.
|
|
* Subsequent definitions will be chained. These methods must return void.
|
|
*/
|
|
DEFINE_MANY: null,
|
|
/**
|
|
* These methods are overriding the base class.
|
|
*/
|
|
OVERRIDE_BASE: null,
|
|
/**
|
|
* These methods are similar to DEFINE_MANY, except we assume they return
|
|
* objects. We try to merge the keys of the return values of all the mixed in
|
|
* functions. If there is a key conflict we throw.
|
|
*/
|
|
DEFINE_MANY_MERGED: null
|
|
});
|
|
|
|
var injectedMixins = [];
|
|
|
|
var warnedSetProps = false;
|
|
function warnSetProps() {
|
|
if (!warnedSetProps) {
|
|
warnedSetProps = true;
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Composite components are higher-level components that compose other composite
|
|
* or native components.
|
|
*
|
|
* To create a new type of `ReactClass`, pass a specification of
|
|
* your new class to `React.createClass`. The only requirement of your class
|
|
* specification is that you implement a `render` method.
|
|
*
|
|
* var MyComponent = React.createClass({
|
|
* render: function() {
|
|
* return <div>Hello World</div>;
|
|
* }
|
|
* });
|
|
*
|
|
* The class specification supports a specific protocol of methods that have
|
|
* special meaning (e.g. `render`). See `ReactClassInterface` for
|
|
* more the comprehensive protocol. Any other properties and methods in the
|
|
* class specification will be available on the prototype.
|
|
*
|
|
* @interface ReactClassInterface
|
|
* @internal
|
|
*/
|
|
var ReactClassInterface = {
|
|
|
|
/**
|
|
* An array of Mixin objects to include when defining your component.
|
|
*
|
|
* @type {array}
|
|
* @optional
|
|
*/
|
|
mixins: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* An object containing properties and methods that should be defined on
|
|
* the component's constructor instead of its prototype (static methods).
|
|
*
|
|
* @type {object}
|
|
* @optional
|
|
*/
|
|
statics: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Definition of prop types for this component.
|
|
*
|
|
* @type {object}
|
|
* @optional
|
|
*/
|
|
propTypes: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Definition of context types for this component.
|
|
*
|
|
* @type {object}
|
|
* @optional
|
|
*/
|
|
contextTypes: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Definition of context types this component sets for its children.
|
|
*
|
|
* @type {object}
|
|
* @optional
|
|
*/
|
|
childContextTypes: SpecPolicy.DEFINE_MANY,
|
|
|
|
// ==== Definition methods ====
|
|
|
|
/**
|
|
* Invoked when the component is mounted. Values in the mapping will be set on
|
|
* `this.props` if that prop is not specified (i.e. using an `in` check).
|
|
*
|
|
* This method is invoked before `getInitialState` and therefore cannot rely
|
|
* on `this.state` or use `this.setState`.
|
|
*
|
|
* @return {object}
|
|
* @optional
|
|
*/
|
|
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
|
|
|
|
/**
|
|
* Invoked once before the component is mounted. The return value will be used
|
|
* as the initial value of `this.state`.
|
|
*
|
|
* getInitialState: function() {
|
|
* return {
|
|
* isOn: false,
|
|
* fooBaz: new BazFoo()
|
|
* }
|
|
* }
|
|
*
|
|
* @return {object}
|
|
* @optional
|
|
*/
|
|
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
|
|
|
|
/**
|
|
* @return {object}
|
|
* @optional
|
|
*/
|
|
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
|
|
|
|
/**
|
|
* Uses props from `this.props` and state from `this.state` to render the
|
|
* structure of the component.
|
|
*
|
|
* No guarantees are made about when or how often this method is invoked, so
|
|
* it must not have side effects.
|
|
*
|
|
* render: function() {
|
|
* var name = this.props.name;
|
|
* return <div>Hello, {name}!</div>;
|
|
* }
|
|
*
|
|
* @return {ReactComponent}
|
|
* @nosideeffects
|
|
* @required
|
|
*/
|
|
render: SpecPolicy.DEFINE_ONCE,
|
|
|
|
// ==== Delegate methods ====
|
|
|
|
/**
|
|
* Invoked when the component is initially created and about to be mounted.
|
|
* This may have side effects, but any external subscriptions or data created
|
|
* by this method must be cleaned up in `componentWillUnmount`.
|
|
*
|
|
* @optional
|
|
*/
|
|
componentWillMount: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Invoked when the component has been mounted and has a DOM representation.
|
|
* However, there is no guarantee that the DOM node is in the document.
|
|
*
|
|
* Use this as an opportunity to operate on the DOM when the component has
|
|
* been mounted (initialized and rendered) for the first time.
|
|
*
|
|
* @param {DOMElement} rootNode DOM element representing the component.
|
|
* @optional
|
|
*/
|
|
componentDidMount: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Invoked before the component receives new props.
|
|
*
|
|
* Use this as an opportunity to react to a prop transition by updating the
|
|
* state using `this.setState`. Current props are accessed via `this.props`.
|
|
*
|
|
* componentWillReceiveProps: function(nextProps, nextContext) {
|
|
* this.setState({
|
|
* likesIncreasing: nextProps.likeCount > this.props.likeCount
|
|
* });
|
|
* }
|
|
*
|
|
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
|
|
* transition may cause a state change, but the opposite is not true. If you
|
|
* need it, you are probably looking for `componentWillUpdate`.
|
|
*
|
|
* @param {object} nextProps
|
|
* @optional
|
|
*/
|
|
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Invoked while deciding if the component should be updated as a result of
|
|
* receiving new props, state and/or context.
|
|
*
|
|
* Use this as an opportunity to `return false` when you're certain that the
|
|
* transition to the new props/state/context will not require a component
|
|
* update.
|
|
*
|
|
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
|
|
* return !equal(nextProps, this.props) ||
|
|
* !equal(nextState, this.state) ||
|
|
* !equal(nextContext, this.context);
|
|
* }
|
|
*
|
|
* @param {object} nextProps
|
|
* @param {?object} nextState
|
|
* @param {?object} nextContext
|
|
* @return {boolean} True if the component should update.
|
|
* @optional
|
|
*/
|
|
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
|
|
|
|
/**
|
|
* Invoked when the component is about to update due to a transition from
|
|
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
|
|
* and `nextContext`.
|
|
*
|
|
* Use this as an opportunity to perform preparation before an update occurs.
|
|
*
|
|
* NOTE: You **cannot** use `this.setState()` in this method.
|
|
*
|
|
* @param {object} nextProps
|
|
* @param {?object} nextState
|
|
* @param {?object} nextContext
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @optional
|
|
*/
|
|
componentWillUpdate: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Invoked when the component's DOM representation has been updated.
|
|
*
|
|
* Use this as an opportunity to operate on the DOM when the component has
|
|
* been updated.
|
|
*
|
|
* @param {object} prevProps
|
|
* @param {?object} prevState
|
|
* @param {?object} prevContext
|
|
* @param {DOMElement} rootNode DOM element representing the component.
|
|
* @optional
|
|
*/
|
|
componentDidUpdate: SpecPolicy.DEFINE_MANY,
|
|
|
|
/**
|
|
* Invoked when the component is about to be removed from its parent and have
|
|
* its DOM representation destroyed.
|
|
*
|
|
* Use this as an opportunity to deallocate any external resources.
|
|
*
|
|
* NOTE: There is no `componentDidUnmount` since your component will have been
|
|
* destroyed by that point.
|
|
*
|
|
* @optional
|
|
*/
|
|
componentWillUnmount: SpecPolicy.DEFINE_MANY,
|
|
|
|
// ==== Advanced methods ====
|
|
|
|
/**
|
|
* Updates the component's currently mounted DOM representation.
|
|
*
|
|
* By default, this implements React's rendering and reconciliation algorithm.
|
|
* Sophisticated clients may wish to override this.
|
|
*
|
|
* @param {ReactReconcileTransaction} transaction
|
|
* @internal
|
|
* @overridable
|
|
*/
|
|
updateComponent: SpecPolicy.OVERRIDE_BASE
|
|
|
|
};
|
|
|
|
/**
|
|
* Mapping from class specification keys to special processing functions.
|
|
*
|
|
* Although these are declared like instance properties in the specification
|
|
* when defining classes using `React.createClass`, they are actually static
|
|
* and are accessible on the constructor instead of the prototype. Despite
|
|
* being static, they must be defined outside of the "statics" key under
|
|
* which all other static methods are defined.
|
|
*/
|
|
var RESERVED_SPEC_KEYS = {
|
|
displayName: function (Constructor, displayName) {
|
|
Constructor.displayName = displayName;
|
|
},
|
|
mixins: function (Constructor, mixins) {
|
|
if (mixins) {
|
|
for (var i = 0; i < mixins.length; i++) {
|
|
mixSpecIntoComponent(Constructor, mixins[i]);
|
|
}
|
|
}
|
|
},
|
|
childContextTypes: function (Constructor, childContextTypes) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
|
|
}
|
|
Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes);
|
|
},
|
|
contextTypes: function (Constructor, contextTypes) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context);
|
|
}
|
|
Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes);
|
|
},
|
|
/**
|
|
* Special case getDefaultProps which should move into statics but requires
|
|
* automatic merging.
|
|
*/
|
|
getDefaultProps: function (Constructor, getDefaultProps) {
|
|
if (Constructor.getDefaultProps) {
|
|
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
|
|
} else {
|
|
Constructor.getDefaultProps = getDefaultProps;
|
|
}
|
|
},
|
|
propTypes: function (Constructor, propTypes) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
|
|
}
|
|
Constructor.propTypes = assign({}, Constructor.propTypes, propTypes);
|
|
},
|
|
statics: function (Constructor, statics) {
|
|
mixStaticSpecIntoComponent(Constructor, statics);
|
|
},
|
|
autobind: function () {} };
|
|
|
|
// noop
|
|
function validateTypeDef(Constructor, typeDef, location) {
|
|
for (var propName in typeDef) {
|
|
if (typeDef.hasOwnProperty(propName)) {
|
|
// use a warning instead of an invariant so components
|
|
// don't show up in prod but not in __DEV__
|
|
process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
function validateMethodOverride(proto, name) {
|
|
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
|
|
|
|
// Disallow overriding of base class methods unless explicitly allowed.
|
|
if (ReactClassMixin.hasOwnProperty(name)) {
|
|
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined;
|
|
}
|
|
|
|
// Disallow defining methods more than once unless explicitly allowed.
|
|
if (proto.hasOwnProperty(name)) {
|
|
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mixin helper which handles policy validation and reserved
|
|
* specification keys when building React classses.
|
|
*/
|
|
function mixSpecIntoComponent(Constructor, spec) {
|
|
if (!spec) {
|
|
return;
|
|
}
|
|
|
|
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
|
|
!!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
|
|
|
|
var proto = Constructor.prototype;
|
|
|
|
// By handling mixins before any other properties, we ensure the same
|
|
// chaining order is applied to methods with DEFINE_MANY policy, whether
|
|
// mixins are listed before or after these methods in the spec.
|
|
if (spec.hasOwnProperty(MIXINS_KEY)) {
|
|
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
|
|
}
|
|
|
|
for (var name in spec) {
|
|
if (!spec.hasOwnProperty(name)) {
|
|
continue;
|
|
}
|
|
|
|
if (name === MIXINS_KEY) {
|
|
// We have already handled mixins in a special case above.
|
|
continue;
|
|
}
|
|
|
|
var property = spec[name];
|
|
validateMethodOverride(proto, name);
|
|
|
|
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
|
|
RESERVED_SPEC_KEYS[name](Constructor, property);
|
|
} else {
|
|
// Setup methods on prototype:
|
|
// The following member methods should not be automatically bound:
|
|
// 1. Expected ReactClass methods (in the "interface").
|
|
// 2. Overridden methods (that were mixed in).
|
|
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
|
|
var isAlreadyDefined = proto.hasOwnProperty(name);
|
|
var isFunction = typeof property === 'function';
|
|
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
|
|
|
|
if (shouldAutoBind) {
|
|
if (!proto.__reactAutoBindMap) {
|
|
proto.__reactAutoBindMap = {};
|
|
}
|
|
proto.__reactAutoBindMap[name] = property;
|
|
proto[name] = property;
|
|
} else {
|
|
if (isAlreadyDefined) {
|
|
var specPolicy = ReactClassInterface[name];
|
|
|
|
// These cases should already be caught by validateMethodOverride.
|
|
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
|
|
|
|
// For methods which are defined more than once, call the existing
|
|
// methods before calling the new property, merging if appropriate.
|
|
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
|
|
proto[name] = createMergedResultFunction(proto[name], property);
|
|
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
|
|
proto[name] = createChainedFunction(proto[name], property);
|
|
}
|
|
} else {
|
|
proto[name] = property;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// Add verbose displayName to the function, which helps when looking
|
|
// at profiling tools.
|
|
if (typeof property === 'function' && spec.displayName) {
|
|
proto[name].displayName = spec.displayName + '_' + name;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function mixStaticSpecIntoComponent(Constructor, statics) {
|
|
if (!statics) {
|
|
return;
|
|
}
|
|
for (var name in statics) {
|
|
var property = statics[name];
|
|
if (!statics.hasOwnProperty(name)) {
|
|
continue;
|
|
}
|
|
|
|
var isReserved = (name in RESERVED_SPEC_KEYS);
|
|
!!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined;
|
|
|
|
var isInherited = (name in Constructor);
|
|
!!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined;
|
|
Constructor[name] = property;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Merge two objects, but throw if both contain the same key.
|
|
*
|
|
* @param {object} one The first object, which is mutated.
|
|
* @param {object} two The second object
|
|
* @return {object} one after it has been mutated to contain everything in two.
|
|
*/
|
|
function mergeIntoWithNoDuplicateKeys(one, two) {
|
|
!(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined;
|
|
|
|
for (var key in two) {
|
|
if (two.hasOwnProperty(key)) {
|
|
!(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined;
|
|
one[key] = two[key];
|
|
}
|
|
}
|
|
return one;
|
|
}
|
|
|
|
/**
|
|
* Creates a function that invokes two functions and merges their return values.
|
|
*
|
|
* @param {function} one Function to invoke first.
|
|
* @param {function} two Function to invoke second.
|
|
* @return {function} Function that invokes the two argument functions.
|
|
* @private
|
|
*/
|
|
function createMergedResultFunction(one, two) {
|
|
return function mergedResult() {
|
|
var a = one.apply(this, arguments);
|
|
var b = two.apply(this, arguments);
|
|
if (a == null) {
|
|
return b;
|
|
} else if (b == null) {
|
|
return a;
|
|
}
|
|
var c = {};
|
|
mergeIntoWithNoDuplicateKeys(c, a);
|
|
mergeIntoWithNoDuplicateKeys(c, b);
|
|
return c;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Creates a function that invokes two functions and ignores their return vales.
|
|
*
|
|
* @param {function} one Function to invoke first.
|
|
* @param {function} two Function to invoke second.
|
|
* @return {function} Function that invokes the two argument functions.
|
|
* @private
|
|
*/
|
|
function createChainedFunction(one, two) {
|
|
return function chainedFunction() {
|
|
one.apply(this, arguments);
|
|
two.apply(this, arguments);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Binds a method to the component.
|
|
*
|
|
* @param {object} component Component whose method is going to be bound.
|
|
* @param {function} method Method to be bound.
|
|
* @return {function} The bound method.
|
|
*/
|
|
function bindAutoBindMethod(component, method) {
|
|
var boundMethod = method.bind(component);
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
boundMethod.__reactBoundContext = component;
|
|
boundMethod.__reactBoundMethod = method;
|
|
boundMethod.__reactBoundArguments = null;
|
|
var componentName = component.constructor.displayName;
|
|
var _bind = boundMethod.bind;
|
|
/* eslint-disable block-scoped-var, no-undef */
|
|
boundMethod.bind = function (newThis) {
|
|
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
args[_key - 1] = arguments[_key];
|
|
}
|
|
|
|
// User is trying to bind() an autobound method; we effectively will
|
|
// ignore the value of "this" that the user is trying to use, so
|
|
// let's warn.
|
|
if (newThis !== component && newThis !== null) {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined;
|
|
} else if (!args.length) {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined;
|
|
return boundMethod;
|
|
}
|
|
var reboundMethod = _bind.apply(boundMethod, arguments);
|
|
reboundMethod.__reactBoundContext = component;
|
|
reboundMethod.__reactBoundMethod = method;
|
|
reboundMethod.__reactBoundArguments = args;
|
|
return reboundMethod;
|
|
/* eslint-enable */
|
|
};
|
|
}
|
|
return boundMethod;
|
|
}
|
|
|
|
/**
|
|
* Binds all auto-bound methods in a component.
|
|
*
|
|
* @param {object} component Component whose method is going to be bound.
|
|
*/
|
|
function bindAutoBindMethods(component) {
|
|
for (var autoBindKey in component.__reactAutoBindMap) {
|
|
if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
|
|
var method = component.__reactAutoBindMap[autoBindKey];
|
|
component[autoBindKey] = bindAutoBindMethod(component, method);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Add more to the ReactClass base class. These are all legacy features and
|
|
* therefore not already part of the modern ReactComponent.
|
|
*/
|
|
var ReactClassMixin = {
|
|
|
|
/**
|
|
* TODO: This will be deprecated because state should always keep a consistent
|
|
* type signature and the only use case for this, is to avoid that.
|
|
*/
|
|
replaceState: function (newState, callback) {
|
|
this.updater.enqueueReplaceState(this, newState);
|
|
if (callback) {
|
|
this.updater.enqueueCallback(this, callback);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Checks whether or not this composite component is mounted.
|
|
* @return {boolean} True if mounted, false otherwise.
|
|
* @protected
|
|
* @final
|
|
*/
|
|
isMounted: function () {
|
|
return this.updater.isMounted(this);
|
|
},
|
|
|
|
/**
|
|
* Sets a subset of the props.
|
|
*
|
|
* @param {object} partialProps Subset of the next props.
|
|
* @param {?function} callback Called after props are updated.
|
|
* @final
|
|
* @public
|
|
* @deprecated
|
|
*/
|
|
setProps: function (partialProps, callback) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
warnSetProps();
|
|
}
|
|
this.updater.enqueueSetProps(this, partialProps);
|
|
if (callback) {
|
|
this.updater.enqueueCallback(this, callback);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Replace all the props.
|
|
*
|
|
* @param {object} newProps Subset of the next props.
|
|
* @param {?function} callback Called after props are updated.
|
|
* @final
|
|
* @public
|
|
* @deprecated
|
|
*/
|
|
replaceProps: function (newProps, callback) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
warnSetProps();
|
|
}
|
|
this.updater.enqueueReplaceProps(this, newProps);
|
|
if (callback) {
|
|
this.updater.enqueueCallback(this, callback);
|
|
}
|
|
}
|
|
};
|
|
|
|
var ReactClassComponent = function () {};
|
|
assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
|
|
|
|
/**
|
|
* Module for creating composite components.
|
|
*
|
|
* @class ReactClass
|
|
*/
|
|
var ReactClass = {
|
|
|
|
/**
|
|
* Creates a composite component class given a class specification.
|
|
*
|
|
* @param {object} spec Class specification (which must define `render`).
|
|
* @return {function} Component constructor function.
|
|
* @public
|
|
*/
|
|
createClass: function (spec) {
|
|
var Constructor = function (props, context, updater) {
|
|
// This constructor is overridden by mocks. The argument is used
|
|
// by mocks to assert on what gets mounted.
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
|
|
}
|
|
|
|
// Wire up auto-binding
|
|
if (this.__reactAutoBindMap) {
|
|
bindAutoBindMethods(this);
|
|
}
|
|
|
|
this.props = props;
|
|
this.context = context;
|
|
this.refs = emptyObject;
|
|
this.updater = updater || ReactNoopUpdateQueue;
|
|
|
|
this.state = null;
|
|
|
|
// ReactClasses doesn't have constructors. Instead, they use the
|
|
// getInitialState and componentWillMount methods for initialization.
|
|
|
|
var initialState = this.getInitialState ? this.getInitialState() : null;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// We allow auto-mocks to proceed as if they're returning null.
|
|
if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) {
|
|
// This is probably bad practice. Consider warning here and
|
|
// deprecating this convenience.
|
|
initialState = null;
|
|
}
|
|
}
|
|
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
|
|
|
|
this.state = initialState;
|
|
};
|
|
Constructor.prototype = new ReactClassComponent();
|
|
Constructor.prototype.constructor = Constructor;
|
|
|
|
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
|
|
|
|
mixSpecIntoComponent(Constructor, spec);
|
|
|
|
// Initialize the defaultProps property after all mixins have been merged.
|
|
if (Constructor.getDefaultProps) {
|
|
Constructor.defaultProps = Constructor.getDefaultProps();
|
|
}
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
// This is a tag to indicate that the use of these method names is ok,
|
|
// since it's used with createClass. If it's not, then it's likely a
|
|
// mistake so we'll warn you to use the static property, property
|
|
// initializer or constructor respectively.
|
|
if (Constructor.getDefaultProps) {
|
|
Constructor.getDefaultProps.isReactClassApproved = {};
|
|
}
|
|
if (Constructor.prototype.getInitialState) {
|
|
Constructor.prototype.getInitialState.isReactClassApproved = {};
|
|
}
|
|
}
|
|
|
|
!Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined;
|
|
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined;
|
|
}
|
|
|
|
// Reduce time spent doing lookups by setting these on the prototype.
|
|
for (var methodName in ReactClassInterface) {
|
|
if (!Constructor.prototype[methodName]) {
|
|
Constructor.prototype[methodName] = null;
|
|
}
|
|
}
|
|
|
|
return Constructor;
|
|
},
|
|
|
|
injection: {
|
|
injectMixin: function (mixin) {
|
|
injectedMixins.push(mixin);
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactClass;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 123 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactComponent
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactNoopUpdateQueue = __webpack_require__(124);
|
|
|
|
var canDefineProperty = __webpack_require__(43);
|
|
var emptyObject = __webpack_require__(58);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* Base class helpers for the updating state of a component.
|
|
*/
|
|
function ReactComponent(props, context, updater) {
|
|
this.props = props;
|
|
this.context = context;
|
|
this.refs = emptyObject;
|
|
// We initialize the default updater but the real one gets injected by the
|
|
// renderer.
|
|
this.updater = updater || ReactNoopUpdateQueue;
|
|
}
|
|
|
|
ReactComponent.prototype.isReactComponent = {};
|
|
|
|
/**
|
|
* Sets a subset of the state. Always use this to mutate
|
|
* state. You should treat `this.state` as immutable.
|
|
*
|
|
* There is no guarantee that `this.state` will be immediately updated, so
|
|
* accessing `this.state` after calling this method may return the old value.
|
|
*
|
|
* There is no guarantee that calls to `setState` will run synchronously,
|
|
* as they may eventually be batched together. You can provide an optional
|
|
* callback that will be executed when the call to setState is actually
|
|
* completed.
|
|
*
|
|
* When a function is provided to setState, it will be called at some point in
|
|
* the future (not synchronously). It will be called with the up to date
|
|
* component arguments (state, props, context). These values can be different
|
|
* from this.* because your function may be called after receiveProps but before
|
|
* shouldComponentUpdate, and this new state, props, and context will not yet be
|
|
* assigned to this.
|
|
*
|
|
* @param {object|function} partialState Next partial state or function to
|
|
* produce next partial state to be merged with current state.
|
|
* @param {?function} callback Called after state is updated.
|
|
* @final
|
|
* @protected
|
|
*/
|
|
ReactComponent.prototype.setState = function (partialState, callback) {
|
|
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined;
|
|
}
|
|
this.updater.enqueueSetState(this, partialState);
|
|
if (callback) {
|
|
this.updater.enqueueCallback(this, callback);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Forces an update. This should only be invoked when it is known with
|
|
* certainty that we are **not** in a DOM transaction.
|
|
*
|
|
* You may want to call this when you know that some deeper aspect of the
|
|
* component's state has changed but `setState` was not called.
|
|
*
|
|
* This will not invoke `shouldComponentUpdate`, but it will invoke
|
|
* `componentWillUpdate` and `componentDidUpdate`.
|
|
*
|
|
* @param {?function} callback Called after update is complete.
|
|
* @final
|
|
* @protected
|
|
*/
|
|
ReactComponent.prototype.forceUpdate = function (callback) {
|
|
this.updater.enqueueForceUpdate(this);
|
|
if (callback) {
|
|
this.updater.enqueueCallback(this, callback);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Deprecated APIs. These APIs used to exist on classic React classes but since
|
|
* we would like to deprecate them, we're not going to move them over to this
|
|
* modern base class. Instead, we define a getter that warns if it's accessed.
|
|
*/
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var deprecatedAPIs = {
|
|
getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'],
|
|
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
|
|
replaceProps: ['replaceProps', 'Instead, call render again at the top level.'],
|
|
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'],
|
|
setProps: ['setProps', 'Instead, call render again at the top level.']
|
|
};
|
|
var defineDeprecationWarning = function (methodName, info) {
|
|
if (canDefineProperty) {
|
|
Object.defineProperty(ReactComponent.prototype, methodName, {
|
|
get: function () {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined;
|
|
return undefined;
|
|
}
|
|
});
|
|
}
|
|
};
|
|
for (var fnName in deprecatedAPIs) {
|
|
if (deprecatedAPIs.hasOwnProperty(fnName)) {
|
|
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = ReactComponent;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 124 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactNoopUpdateQueue
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var warning = __webpack_require__(25);
|
|
|
|
function warnTDZ(publicInstance, callerName) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* This is the abstract API for an update queue.
|
|
*/
|
|
var ReactNoopUpdateQueue = {
|
|
|
|
/**
|
|
* Checks whether or not this composite component is mounted.
|
|
* @param {ReactClass} publicInstance The instance we want to test.
|
|
* @return {boolean} True if mounted, false otherwise.
|
|
* @protected
|
|
* @final
|
|
*/
|
|
isMounted: function (publicInstance) {
|
|
return false;
|
|
},
|
|
|
|
/**
|
|
* Enqueue a callback that will be executed after all the pending updates
|
|
* have processed.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance to use as `this` context.
|
|
* @param {?function} callback Called after state is updated.
|
|
* @internal
|
|
*/
|
|
enqueueCallback: function (publicInstance, callback) {},
|
|
|
|
/**
|
|
* Forces an update. This should only be invoked when it is known with
|
|
* certainty that we are **not** in a DOM transaction.
|
|
*
|
|
* You may want to call this when you know that some deeper aspect of the
|
|
* component's state has changed but `setState` was not called.
|
|
*
|
|
* This will not invoke `shouldComponentUpdate`, but it will invoke
|
|
* `componentWillUpdate` and `componentDidUpdate`.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @internal
|
|
*/
|
|
enqueueForceUpdate: function (publicInstance) {
|
|
warnTDZ(publicInstance, 'forceUpdate');
|
|
},
|
|
|
|
/**
|
|
* Replaces all of the state. Always use this or `setState` to mutate state.
|
|
* You should treat `this.state` as immutable.
|
|
*
|
|
* There is no guarantee that `this.state` will be immediately updated, so
|
|
* accessing `this.state` after calling this method may return the old value.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} completeState Next state.
|
|
* @internal
|
|
*/
|
|
enqueueReplaceState: function (publicInstance, completeState) {
|
|
warnTDZ(publicInstance, 'replaceState');
|
|
},
|
|
|
|
/**
|
|
* Sets a subset of the state. This only exists because _pendingState is
|
|
* internal. This provides a merging strategy that is not available to deep
|
|
* properties which is confusing. TODO: Expose pendingState or don't use it
|
|
* during the merge.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} partialState Next partial state to be merged with state.
|
|
* @internal
|
|
*/
|
|
enqueueSetState: function (publicInstance, partialState) {
|
|
warnTDZ(publicInstance, 'setState');
|
|
},
|
|
|
|
/**
|
|
* Sets a subset of the props.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} partialProps Subset of the next props.
|
|
* @internal
|
|
*/
|
|
enqueueSetProps: function (publicInstance, partialProps) {
|
|
warnTDZ(publicInstance, 'setProps');
|
|
},
|
|
|
|
/**
|
|
* Replaces all of the props.
|
|
*
|
|
* @param {ReactClass} publicInstance The instance that should rerender.
|
|
* @param {object} props New props.
|
|
* @internal
|
|
*/
|
|
enqueueReplaceProps: function (publicInstance, props) {
|
|
warnTDZ(publicInstance, 'replaceProps');
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactNoopUpdateQueue;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 125 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactReconcileTransaction
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var CallbackQueue = __webpack_require__(55);
|
|
var PooledClass = __webpack_require__(56);
|
|
var ReactBrowserEventEmitter = __webpack_require__(29);
|
|
var ReactDOMFeatureFlags = __webpack_require__(41);
|
|
var ReactInputSelection = __webpack_require__(126);
|
|
var Transaction = __webpack_require__(57);
|
|
|
|
var assign = __webpack_require__(39);
|
|
|
|
/**
|
|
* Ensures that, when possible, the selection range (currently selected text
|
|
* input) is not disturbed by performing the transaction.
|
|
*/
|
|
var SELECTION_RESTORATION = {
|
|
/**
|
|
* @return {Selection} Selection information.
|
|
*/
|
|
initialize: ReactInputSelection.getSelectionInformation,
|
|
/**
|
|
* @param {Selection} sel Selection information returned from `initialize`.
|
|
*/
|
|
close: ReactInputSelection.restoreSelection
|
|
};
|
|
|
|
/**
|
|
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
|
|
* high level DOM manipulations (like temporarily removing a text input from the
|
|
* DOM).
|
|
*/
|
|
var EVENT_SUPPRESSION = {
|
|
/**
|
|
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
|
|
* the reconciliation.
|
|
*/
|
|
initialize: function () {
|
|
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
|
|
ReactBrowserEventEmitter.setEnabled(false);
|
|
return currentlyEnabled;
|
|
},
|
|
|
|
/**
|
|
* @param {boolean} previouslyEnabled Enabled status of
|
|
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
|
|
* restores the previous value.
|
|
*/
|
|
close: function (previouslyEnabled) {
|
|
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Provides a queue for collecting `componentDidMount` and
|
|
* `componentDidUpdate` callbacks during the the transaction.
|
|
*/
|
|
var ON_DOM_READY_QUEUEING = {
|
|
/**
|
|
* Initializes the internal `onDOMReady` queue.
|
|
*/
|
|
initialize: function () {
|
|
this.reactMountReady.reset();
|
|
},
|
|
|
|
/**
|
|
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
|
|
*/
|
|
close: function () {
|
|
this.reactMountReady.notifyAll();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Executed within the scope of the `Transaction` instance. Consider these as
|
|
* being member methods, but with an implied ordering while being isolated from
|
|
* each other.
|
|
*/
|
|
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
|
|
|
|
/**
|
|
* Currently:
|
|
* - The order that these are listed in the transaction is critical:
|
|
* - Suppresses events.
|
|
* - Restores selection range.
|
|
*
|
|
* Future:
|
|
* - Restore document/overflow scroll positions that were unintentionally
|
|
* modified via DOM insertions above the top viewport boundary.
|
|
* - Implement/integrate with customized constraint based layout system and keep
|
|
* track of which dimensions must be remeasured.
|
|
*
|
|
* @class ReactReconcileTransaction
|
|
*/
|
|
function ReactReconcileTransaction(forceHTML) {
|
|
this.reinitializeTransaction();
|
|
// Only server-side rendering really needs this option (see
|
|
// `ReactServerRendering`), but server-side uses
|
|
// `ReactServerRenderingTransaction` instead. This option is here so that it's
|
|
// accessible and defaults to false when `ReactDOMComponent` and
|
|
// `ReactTextComponent` checks it in `mountComponent`.`
|
|
this.renderToStaticMarkup = false;
|
|
this.reactMountReady = CallbackQueue.getPooled(null);
|
|
this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement;
|
|
}
|
|
|
|
var Mixin = {
|
|
/**
|
|
* @see Transaction
|
|
* @abstract
|
|
* @final
|
|
* @return {array<object>} List of operation wrap procedures.
|
|
* TODO: convert to array<TransactionWrapper>
|
|
*/
|
|
getTransactionWrappers: function () {
|
|
return TRANSACTION_WRAPPERS;
|
|
},
|
|
|
|
/**
|
|
* @return {object} The queue to collect `onDOMReady` callbacks with.
|
|
*/
|
|
getReactMountReady: function () {
|
|
return this.reactMountReady;
|
|
},
|
|
|
|
/**
|
|
* `PooledClass` looks for this, and will invoke this before allowing this
|
|
* instance to be reused.
|
|
*/
|
|
destructor: function () {
|
|
CallbackQueue.release(this.reactMountReady);
|
|
this.reactMountReady = null;
|
|
}
|
|
};
|
|
|
|
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
|
|
|
|
PooledClass.addPoolingTo(ReactReconcileTransaction);
|
|
|
|
module.exports = ReactReconcileTransaction;
|
|
|
|
/***/ }),
|
|
/* 126 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactInputSelection
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDOMSelection = __webpack_require__(127);
|
|
|
|
var containsNode = __webpack_require__(59);
|
|
var focusNode = __webpack_require__(95);
|
|
var getActiveElement = __webpack_require__(129);
|
|
|
|
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.
|
|
*/
|
|
var ReactInputSelection = {
|
|
|
|
hasSelectionCapabilities: function (elem) {
|
|
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
|
|
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
|
|
},
|
|
|
|
getSelectionInformation: function () {
|
|
var focusedElem = getActiveElement();
|
|
return {
|
|
focusedElem: focusedElem,
|
|
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
|
|
};
|
|
},
|
|
|
|
/**
|
|
* @restoreSelection: If any selection information was potentially lost,
|
|
* restore it. This is useful when performing operations that could remove dom
|
|
* nodes and place them back in, resulting in focus being lost.
|
|
*/
|
|
restoreSelection: function (priorSelectionInformation) {
|
|
var curFocusedElem = getActiveElement();
|
|
var priorFocusedElem = priorSelectionInformation.focusedElem;
|
|
var priorSelectionRange = priorSelectionInformation.selectionRange;
|
|
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
|
|
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
|
|
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
|
|
}
|
|
focusNode(priorFocusedElem);
|
|
}
|
|
},
|
|
|
|
/**
|
|
* @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}
|
|
*/
|
|
getSelection: function (input) {
|
|
var selection;
|
|
|
|
if ('selectionStart' in input) {
|
|
// Modern browser with input or textarea.
|
|
selection = {
|
|
start: input.selectionStart,
|
|
end: input.selectionEnd
|
|
};
|
|
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
|
|
// IE8 input.
|
|
var range = document.selection.createRange();
|
|
// There can only be one selection per document in IE, so it must
|
|
// be in our element.
|
|
if (range.parentElement() === input) {
|
|
selection = {
|
|
start: -range.moveStart('character', -input.value.length),
|
|
end: -range.moveEnd('character', -input.value.length)
|
|
};
|
|
}
|
|
} else {
|
|
// Content editable or old IE textarea.
|
|
selection = ReactDOMSelection.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*
|
|
*/
|
|
setSelection: function (input, offsets) {
|
|
var start = offsets.start;
|
|
var end = offsets.end;
|
|
if (typeof end === 'undefined') {
|
|
end = start;
|
|
}
|
|
|
|
if ('selectionStart' in input) {
|
|
input.selectionStart = start;
|
|
input.selectionEnd = Math.min(end, input.value.length);
|
|
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
|
|
var range = input.createTextRange();
|
|
range.collapse(true);
|
|
range.moveStart('character', start);
|
|
range.moveEnd('character', end - start);
|
|
range.select();
|
|
} else {
|
|
ReactDOMSelection.setOffsets(input, offsets);
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = ReactInputSelection;
|
|
|
|
/***/ }),
|
|
/* 127 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMSelection
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var getNodeForCharacterOffset = __webpack_require__(128);
|
|
var getTextContentAccessor = __webpack_require__(75);
|
|
|
|
/**
|
|
* While `isCollapsed` is available on the Selection object and `collapsed`
|
|
* is available on the Range object, IE11 sometimes gets them wrong.
|
|
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
|
|
*/
|
|
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
|
|
return anchorNode === focusNode && anchorOffset === focusOffset;
|
|
}
|
|
|
|
/**
|
|
* Get the appropriate anchor and focus node/offset pairs for IE.
|
|
*
|
|
* The catch here is that IE's selection API doesn't provide information
|
|
* about whether the selection is forward or backward, so we have to
|
|
* behave as though it's always forward.
|
|
*
|
|
* IE text differs from modern selection in that it behaves as though
|
|
* block elements end with a new line. This means character offsets will
|
|
* differ between the two APIs.
|
|
*
|
|
* @param {DOMElement} node
|
|
* @return {object}
|
|
*/
|
|
function getIEOffsets(node) {
|
|
var selection = document.selection;
|
|
var selectedRange = selection.createRange();
|
|
var selectedLength = selectedRange.text.length;
|
|
|
|
// Duplicate selection so we can move range without breaking user selection.
|
|
var fromStart = selectedRange.duplicate();
|
|
fromStart.moveToElementText(node);
|
|
fromStart.setEndPoint('EndToStart', selectedRange);
|
|
|
|
var startOffset = fromStart.text.length;
|
|
var endOffset = startOffset + selectedLength;
|
|
|
|
return {
|
|
start: startOffset,
|
|
end: endOffset
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @param {DOMElement} node
|
|
* @return {?object}
|
|
*/
|
|
function getModernOffsets(node) {
|
|
var selection = window.getSelection && window.getSelection();
|
|
|
|
if (!selection || selection.rangeCount === 0) {
|
|
return null;
|
|
}
|
|
|
|
var anchorNode = selection.anchorNode;
|
|
var anchorOffset = selection.anchorOffset;
|
|
var focusNode = selection.focusNode;
|
|
var focusOffset = selection.focusOffset;
|
|
|
|
var currentRange = selection.getRangeAt(0);
|
|
|
|
// In Firefox, range.startContainer and range.endContainer can be "anonymous
|
|
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
|
|
// divs do not seem to expose properties, triggering a "Permission denied
|
|
// error" if any of its properties are accessed. The only seemingly possible
|
|
// way to avoid erroring is to access a property that typically works for
|
|
// non-anonymous divs and catch any error that may otherwise arise. See
|
|
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
|
|
try {
|
|
/* eslint-disable no-unused-expressions */
|
|
currentRange.startContainer.nodeType;
|
|
currentRange.endContainer.nodeType;
|
|
/* eslint-enable no-unused-expressions */
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
|
|
// If the node and offset values are the same, the selection is collapsed.
|
|
// `Selection.isCollapsed` is available natively, but IE sometimes gets
|
|
// this value wrong.
|
|
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
|
|
|
|
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
|
|
|
|
var tempRange = currentRange.cloneRange();
|
|
tempRange.selectNodeContents(node);
|
|
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
|
|
|
|
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
|
|
|
|
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
|
|
var end = start + rangeLength;
|
|
|
|
// Detect whether the selection is backward.
|
|
var detectionRange = document.createRange();
|
|
detectionRange.setStart(anchorNode, anchorOffset);
|
|
detectionRange.setEnd(focusNode, focusOffset);
|
|
var isBackward = detectionRange.collapsed;
|
|
|
|
return {
|
|
start: isBackward ? end : start,
|
|
end: isBackward ? start : end
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @param {DOMElement|DOMTextNode} node
|
|
* @param {object} offsets
|
|
*/
|
|
function setIEOffsets(node, offsets) {
|
|
var range = document.selection.createRange().duplicate();
|
|
var start, end;
|
|
|
|
if (typeof offsets.end === 'undefined') {
|
|
start = offsets.start;
|
|
end = start;
|
|
} else if (offsets.start > offsets.end) {
|
|
start = offsets.end;
|
|
end = offsets.start;
|
|
} else {
|
|
start = offsets.start;
|
|
end = offsets.end;
|
|
}
|
|
|
|
range.moveToElementText(node);
|
|
range.moveStart('character', start);
|
|
range.setEndPoint('EndToStart', range);
|
|
range.moveEnd('character', end - start);
|
|
range.select();
|
|
}
|
|
|
|
/**
|
|
* 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 programatically 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 setModernOffsets(node, offsets) {
|
|
if (!window.getSelection) {
|
|
return;
|
|
}
|
|
|
|
var selection = window.getSelection();
|
|
var length = node[getTextContentAccessor()].length;
|
|
var start = Math.min(offsets.start, length);
|
|
var end = typeof 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) {
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
|
|
|
|
var ReactDOMSelection = {
|
|
/**
|
|
* @param {DOMElement} node
|
|
*/
|
|
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
|
|
|
|
/**
|
|
* @param {DOMElement|DOMTextNode} node
|
|
* @param {object} offsets
|
|
*/
|
|
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
|
|
};
|
|
|
|
module.exports = ReactDOMSelection;
|
|
|
|
/***/ }),
|
|
/* 128 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getNodeForCharacterOffset
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* 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 === 3) {
|
|
nodeEnd = nodeStart + node.textContent.length;
|
|
|
|
if (nodeStart <= offset && nodeEnd >= offset) {
|
|
return {
|
|
node: node,
|
|
offset: offset - nodeStart
|
|
};
|
|
}
|
|
|
|
nodeStart = nodeEnd;
|
|
}
|
|
|
|
node = getLeafNode(getSiblingNode(node));
|
|
}
|
|
}
|
|
|
|
module.exports = getNodeForCharacterOffset;
|
|
|
|
/***/ }),
|
|
/* 129 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getActiveElement
|
|
* @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.
|
|
*/
|
|
'use strict';
|
|
|
|
function getActiveElement() /*?DOMElement*/{
|
|
if (typeof document === 'undefined') {
|
|
return null;
|
|
}
|
|
try {
|
|
return document.activeElement || document.body;
|
|
} catch (e) {
|
|
return document.body;
|
|
}
|
|
}
|
|
|
|
module.exports = getActiveElement;
|
|
|
|
/***/ }),
|
|
/* 130 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SelectEventPlugin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventPropagators = __webpack_require__(73);
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
var ReactInputSelection = __webpack_require__(126);
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
var getActiveElement = __webpack_require__(129);
|
|
var isTextInputElement = __webpack_require__(82);
|
|
var keyOf = __webpack_require__(79);
|
|
var shallowEqual = __webpack_require__(117);
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
|
|
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
|
|
|
|
var eventTypes = {
|
|
select: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onSelect: null }),
|
|
captured: keyOf({ onSelectCapture: null })
|
|
},
|
|
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
|
|
}
|
|
};
|
|
|
|
var activeElement = null;
|
|
var activeElementID = null;
|
|
var lastSelection = null;
|
|
var mouseDown = false;
|
|
|
|
// Track whether a listener exists for this plugin. If none exist, we do
|
|
// not extract events.
|
|
var hasListener = false;
|
|
var ON_SELECT_KEY = keyOf({ onSelect: null });
|
|
|
|
/**
|
|
* 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 && ReactInputSelection.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
|
|
};
|
|
} else if (document.selection) {
|
|
var range = document.selection.createRange();
|
|
return {
|
|
parentElement: range.parentElement(),
|
|
text: range.text,
|
|
top: range.boundingTop,
|
|
left: range.boundingLeft
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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 == null || activeElement !== getActiveElement()) {
|
|
return null;
|
|
}
|
|
|
|
// Only fire when selection has actually changed.
|
|
var currentSelection = getSelection(activeElement);
|
|
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
|
|
lastSelection = currentSelection;
|
|
|
|
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget);
|
|
|
|
syntheticEvent.type = 'select';
|
|
syntheticEvent.target = activeElement;
|
|
|
|
EventPropagators.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,
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @see {EventPluginHub.extractEvents}
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
if (!hasListener) {
|
|
return null;
|
|
}
|
|
|
|
switch (topLevelType) {
|
|
// Track the input node that has focus.
|
|
case topLevelTypes.topFocus:
|
|
if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') {
|
|
activeElement = topLevelTarget;
|
|
activeElementID = topLevelTargetID;
|
|
lastSelection = null;
|
|
}
|
|
break;
|
|
case topLevelTypes.topBlur:
|
|
activeElement = null;
|
|
activeElementID = null;
|
|
lastSelection = null;
|
|
break;
|
|
|
|
// Don't fire the event while the user is dragging. This matches the
|
|
// semantics of the native select event.
|
|
case topLevelTypes.topMouseDown:
|
|
mouseDown = true;
|
|
break;
|
|
case topLevelTypes.topContextMenu:
|
|
case topLevelTypes.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 topLevelTypes.topSelectionChange:
|
|
if (skipSelectionChangeEvent) {
|
|
break;
|
|
}
|
|
// falls through
|
|
case topLevelTypes.topKeyDown:
|
|
case topLevelTypes.topKeyUp:
|
|
return constructSelectEvent(nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
return null;
|
|
},
|
|
|
|
didPutListener: function (id, registrationName, listener) {
|
|
if (registrationName === ON_SELECT_KEY) {
|
|
hasListener = true;
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = SelectEventPlugin;
|
|
|
|
/***/ }),
|
|
/* 131 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ServerReactRootIndex
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Size of the reactRoot ID space. We generate random numbers for React root
|
|
* IDs and if there's a collision the events and DOM update system will
|
|
* get confused. In the future we need a way to generate GUIDs but for
|
|
* now this will work on a smaller scale.
|
|
*/
|
|
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
|
|
|
|
var ServerReactRootIndex = {
|
|
createReactRootIndex: function () {
|
|
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
|
|
}
|
|
};
|
|
|
|
module.exports = ServerReactRootIndex;
|
|
|
|
/***/ }),
|
|
/* 132 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SimpleEventPlugin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var EventConstants = __webpack_require__(30);
|
|
var EventListener = __webpack_require__(119);
|
|
var EventPropagators = __webpack_require__(73);
|
|
var ReactMount = __webpack_require__(28);
|
|
var SyntheticClipboardEvent = __webpack_require__(133);
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
var SyntheticFocusEvent = __webpack_require__(134);
|
|
var SyntheticKeyboardEvent = __webpack_require__(135);
|
|
var SyntheticMouseEvent = __webpack_require__(86);
|
|
var SyntheticDragEvent = __webpack_require__(138);
|
|
var SyntheticTouchEvent = __webpack_require__(139);
|
|
var SyntheticUIEvent = __webpack_require__(87);
|
|
var SyntheticWheelEvent = __webpack_require__(140);
|
|
|
|
var emptyFunction = __webpack_require__(15);
|
|
var getEventCharCode = __webpack_require__(136);
|
|
var invariant = __webpack_require__(13);
|
|
var keyOf = __webpack_require__(79);
|
|
|
|
var topLevelTypes = EventConstants.topLevelTypes;
|
|
|
|
var eventTypes = {
|
|
abort: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onAbort: true }),
|
|
captured: keyOf({ onAbortCapture: true })
|
|
}
|
|
},
|
|
blur: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onBlur: true }),
|
|
captured: keyOf({ onBlurCapture: true })
|
|
}
|
|
},
|
|
canPlay: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCanPlay: true }),
|
|
captured: keyOf({ onCanPlayCapture: true })
|
|
}
|
|
},
|
|
canPlayThrough: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCanPlayThrough: true }),
|
|
captured: keyOf({ onCanPlayThroughCapture: true })
|
|
}
|
|
},
|
|
click: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onClick: true }),
|
|
captured: keyOf({ onClickCapture: true })
|
|
}
|
|
},
|
|
contextMenu: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onContextMenu: true }),
|
|
captured: keyOf({ onContextMenuCapture: true })
|
|
}
|
|
},
|
|
copy: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCopy: true }),
|
|
captured: keyOf({ onCopyCapture: true })
|
|
}
|
|
},
|
|
cut: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onCut: true }),
|
|
captured: keyOf({ onCutCapture: true })
|
|
}
|
|
},
|
|
doubleClick: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDoubleClick: true }),
|
|
captured: keyOf({ onDoubleClickCapture: true })
|
|
}
|
|
},
|
|
drag: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDrag: true }),
|
|
captured: keyOf({ onDragCapture: true })
|
|
}
|
|
},
|
|
dragEnd: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragEnd: true }),
|
|
captured: keyOf({ onDragEndCapture: true })
|
|
}
|
|
},
|
|
dragEnter: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragEnter: true }),
|
|
captured: keyOf({ onDragEnterCapture: true })
|
|
}
|
|
},
|
|
dragExit: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragExit: true }),
|
|
captured: keyOf({ onDragExitCapture: true })
|
|
}
|
|
},
|
|
dragLeave: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragLeave: true }),
|
|
captured: keyOf({ onDragLeaveCapture: true })
|
|
}
|
|
},
|
|
dragOver: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragOver: true }),
|
|
captured: keyOf({ onDragOverCapture: true })
|
|
}
|
|
},
|
|
dragStart: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDragStart: true }),
|
|
captured: keyOf({ onDragStartCapture: true })
|
|
}
|
|
},
|
|
drop: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDrop: true }),
|
|
captured: keyOf({ onDropCapture: true })
|
|
}
|
|
},
|
|
durationChange: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onDurationChange: true }),
|
|
captured: keyOf({ onDurationChangeCapture: true })
|
|
}
|
|
},
|
|
emptied: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onEmptied: true }),
|
|
captured: keyOf({ onEmptiedCapture: true })
|
|
}
|
|
},
|
|
encrypted: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onEncrypted: true }),
|
|
captured: keyOf({ onEncryptedCapture: true })
|
|
}
|
|
},
|
|
ended: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onEnded: true }),
|
|
captured: keyOf({ onEndedCapture: true })
|
|
}
|
|
},
|
|
error: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onError: true }),
|
|
captured: keyOf({ onErrorCapture: true })
|
|
}
|
|
},
|
|
focus: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onFocus: true }),
|
|
captured: keyOf({ onFocusCapture: true })
|
|
}
|
|
},
|
|
input: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onInput: true }),
|
|
captured: keyOf({ onInputCapture: true })
|
|
}
|
|
},
|
|
keyDown: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onKeyDown: true }),
|
|
captured: keyOf({ onKeyDownCapture: true })
|
|
}
|
|
},
|
|
keyPress: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onKeyPress: true }),
|
|
captured: keyOf({ onKeyPressCapture: true })
|
|
}
|
|
},
|
|
keyUp: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onKeyUp: true }),
|
|
captured: keyOf({ onKeyUpCapture: true })
|
|
}
|
|
},
|
|
load: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onLoad: true }),
|
|
captured: keyOf({ onLoadCapture: true })
|
|
}
|
|
},
|
|
loadedData: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onLoadedData: true }),
|
|
captured: keyOf({ onLoadedDataCapture: true })
|
|
}
|
|
},
|
|
loadedMetadata: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onLoadedMetadata: true }),
|
|
captured: keyOf({ onLoadedMetadataCapture: true })
|
|
}
|
|
},
|
|
loadStart: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onLoadStart: true }),
|
|
captured: keyOf({ onLoadStartCapture: true })
|
|
}
|
|
},
|
|
// Note: We do not allow listening to mouseOver events. Instead, use the
|
|
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
|
|
mouseDown: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onMouseDown: true }),
|
|
captured: keyOf({ onMouseDownCapture: true })
|
|
}
|
|
},
|
|
mouseMove: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onMouseMove: true }),
|
|
captured: keyOf({ onMouseMoveCapture: true })
|
|
}
|
|
},
|
|
mouseOut: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onMouseOut: true }),
|
|
captured: keyOf({ onMouseOutCapture: true })
|
|
}
|
|
},
|
|
mouseOver: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onMouseOver: true }),
|
|
captured: keyOf({ onMouseOverCapture: true })
|
|
}
|
|
},
|
|
mouseUp: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onMouseUp: true }),
|
|
captured: keyOf({ onMouseUpCapture: true })
|
|
}
|
|
},
|
|
paste: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onPaste: true }),
|
|
captured: keyOf({ onPasteCapture: true })
|
|
}
|
|
},
|
|
pause: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onPause: true }),
|
|
captured: keyOf({ onPauseCapture: true })
|
|
}
|
|
},
|
|
play: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onPlay: true }),
|
|
captured: keyOf({ onPlayCapture: true })
|
|
}
|
|
},
|
|
playing: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onPlaying: true }),
|
|
captured: keyOf({ onPlayingCapture: true })
|
|
}
|
|
},
|
|
progress: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onProgress: true }),
|
|
captured: keyOf({ onProgressCapture: true })
|
|
}
|
|
},
|
|
rateChange: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onRateChange: true }),
|
|
captured: keyOf({ onRateChangeCapture: true })
|
|
}
|
|
},
|
|
reset: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onReset: true }),
|
|
captured: keyOf({ onResetCapture: true })
|
|
}
|
|
},
|
|
scroll: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onScroll: true }),
|
|
captured: keyOf({ onScrollCapture: true })
|
|
}
|
|
},
|
|
seeked: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onSeeked: true }),
|
|
captured: keyOf({ onSeekedCapture: true })
|
|
}
|
|
},
|
|
seeking: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onSeeking: true }),
|
|
captured: keyOf({ onSeekingCapture: true })
|
|
}
|
|
},
|
|
stalled: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onStalled: true }),
|
|
captured: keyOf({ onStalledCapture: true })
|
|
}
|
|
},
|
|
submit: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onSubmit: true }),
|
|
captured: keyOf({ onSubmitCapture: true })
|
|
}
|
|
},
|
|
suspend: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onSuspend: true }),
|
|
captured: keyOf({ onSuspendCapture: true })
|
|
}
|
|
},
|
|
timeUpdate: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onTimeUpdate: true }),
|
|
captured: keyOf({ onTimeUpdateCapture: true })
|
|
}
|
|
},
|
|
touchCancel: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onTouchCancel: true }),
|
|
captured: keyOf({ onTouchCancelCapture: true })
|
|
}
|
|
},
|
|
touchEnd: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onTouchEnd: true }),
|
|
captured: keyOf({ onTouchEndCapture: true })
|
|
}
|
|
},
|
|
touchMove: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onTouchMove: true }),
|
|
captured: keyOf({ onTouchMoveCapture: true })
|
|
}
|
|
},
|
|
touchStart: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onTouchStart: true }),
|
|
captured: keyOf({ onTouchStartCapture: true })
|
|
}
|
|
},
|
|
volumeChange: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onVolumeChange: true }),
|
|
captured: keyOf({ onVolumeChangeCapture: true })
|
|
}
|
|
},
|
|
waiting: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onWaiting: true }),
|
|
captured: keyOf({ onWaitingCapture: true })
|
|
}
|
|
},
|
|
wheel: {
|
|
phasedRegistrationNames: {
|
|
bubbled: keyOf({ onWheel: true }),
|
|
captured: keyOf({ onWheelCapture: true })
|
|
}
|
|
}
|
|
};
|
|
|
|
var topLevelEventsToDispatchConfig = {
|
|
topAbort: eventTypes.abort,
|
|
topBlur: eventTypes.blur,
|
|
topCanPlay: eventTypes.canPlay,
|
|
topCanPlayThrough: eventTypes.canPlayThrough,
|
|
topClick: eventTypes.click,
|
|
topContextMenu: eventTypes.contextMenu,
|
|
topCopy: eventTypes.copy,
|
|
topCut: eventTypes.cut,
|
|
topDoubleClick: eventTypes.doubleClick,
|
|
topDrag: eventTypes.drag,
|
|
topDragEnd: eventTypes.dragEnd,
|
|
topDragEnter: eventTypes.dragEnter,
|
|
topDragExit: eventTypes.dragExit,
|
|
topDragLeave: eventTypes.dragLeave,
|
|
topDragOver: eventTypes.dragOver,
|
|
topDragStart: eventTypes.dragStart,
|
|
topDrop: eventTypes.drop,
|
|
topDurationChange: eventTypes.durationChange,
|
|
topEmptied: eventTypes.emptied,
|
|
topEncrypted: eventTypes.encrypted,
|
|
topEnded: eventTypes.ended,
|
|
topError: eventTypes.error,
|
|
topFocus: eventTypes.focus,
|
|
topInput: eventTypes.input,
|
|
topKeyDown: eventTypes.keyDown,
|
|
topKeyPress: eventTypes.keyPress,
|
|
topKeyUp: eventTypes.keyUp,
|
|
topLoad: eventTypes.load,
|
|
topLoadedData: eventTypes.loadedData,
|
|
topLoadedMetadata: eventTypes.loadedMetadata,
|
|
topLoadStart: eventTypes.loadStart,
|
|
topMouseDown: eventTypes.mouseDown,
|
|
topMouseMove: eventTypes.mouseMove,
|
|
topMouseOut: eventTypes.mouseOut,
|
|
topMouseOver: eventTypes.mouseOver,
|
|
topMouseUp: eventTypes.mouseUp,
|
|
topPaste: eventTypes.paste,
|
|
topPause: eventTypes.pause,
|
|
topPlay: eventTypes.play,
|
|
topPlaying: eventTypes.playing,
|
|
topProgress: eventTypes.progress,
|
|
topRateChange: eventTypes.rateChange,
|
|
topReset: eventTypes.reset,
|
|
topScroll: eventTypes.scroll,
|
|
topSeeked: eventTypes.seeked,
|
|
topSeeking: eventTypes.seeking,
|
|
topStalled: eventTypes.stalled,
|
|
topSubmit: eventTypes.submit,
|
|
topSuspend: eventTypes.suspend,
|
|
topTimeUpdate: eventTypes.timeUpdate,
|
|
topTouchCancel: eventTypes.touchCancel,
|
|
topTouchEnd: eventTypes.touchEnd,
|
|
topTouchMove: eventTypes.touchMove,
|
|
topTouchStart: eventTypes.touchStart,
|
|
topVolumeChange: eventTypes.volumeChange,
|
|
topWaiting: eventTypes.waiting,
|
|
topWheel: eventTypes.wheel
|
|
};
|
|
|
|
for (var type in topLevelEventsToDispatchConfig) {
|
|
topLevelEventsToDispatchConfig[type].dependencies = [type];
|
|
}
|
|
|
|
var ON_CLICK_KEY = keyOf({ onClick: null });
|
|
var onClickListeners = {};
|
|
|
|
var SimpleEventPlugin = {
|
|
|
|
eventTypes: eventTypes,
|
|
|
|
/**
|
|
* @param {string} topLevelType Record from `EventConstants`.
|
|
* @param {DOMEventTarget} topLevelTarget The listening component root node.
|
|
* @param {string} topLevelTargetID ID of `topLevelTarget`.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {*} An accumulation of synthetic events.
|
|
* @see {EventPluginHub.extractEvents}
|
|
*/
|
|
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
|
|
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
|
|
if (!dispatchConfig) {
|
|
return null;
|
|
}
|
|
var EventConstructor;
|
|
switch (topLevelType) {
|
|
case topLevelTypes.topAbort:
|
|
case topLevelTypes.topCanPlay:
|
|
case topLevelTypes.topCanPlayThrough:
|
|
case topLevelTypes.topDurationChange:
|
|
case topLevelTypes.topEmptied:
|
|
case topLevelTypes.topEncrypted:
|
|
case topLevelTypes.topEnded:
|
|
case topLevelTypes.topError:
|
|
case topLevelTypes.topInput:
|
|
case topLevelTypes.topLoad:
|
|
case topLevelTypes.topLoadedData:
|
|
case topLevelTypes.topLoadedMetadata:
|
|
case topLevelTypes.topLoadStart:
|
|
case topLevelTypes.topPause:
|
|
case topLevelTypes.topPlay:
|
|
case topLevelTypes.topPlaying:
|
|
case topLevelTypes.topProgress:
|
|
case topLevelTypes.topRateChange:
|
|
case topLevelTypes.topReset:
|
|
case topLevelTypes.topSeeked:
|
|
case topLevelTypes.topSeeking:
|
|
case topLevelTypes.topStalled:
|
|
case topLevelTypes.topSubmit:
|
|
case topLevelTypes.topSuspend:
|
|
case topLevelTypes.topTimeUpdate:
|
|
case topLevelTypes.topVolumeChange:
|
|
case topLevelTypes.topWaiting:
|
|
// HTML Events
|
|
// @see http://www.w3.org/TR/html5/index.html#events-0
|
|
EventConstructor = SyntheticEvent;
|
|
break;
|
|
case topLevelTypes.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 topLevelTypes.topKeyDown:
|
|
case topLevelTypes.topKeyUp:
|
|
EventConstructor = SyntheticKeyboardEvent;
|
|
break;
|
|
case topLevelTypes.topBlur:
|
|
case topLevelTypes.topFocus:
|
|
EventConstructor = SyntheticFocusEvent;
|
|
break;
|
|
case topLevelTypes.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 topLevelTypes.topContextMenu:
|
|
case topLevelTypes.topDoubleClick:
|
|
case topLevelTypes.topMouseDown:
|
|
case topLevelTypes.topMouseMove:
|
|
case topLevelTypes.topMouseOut:
|
|
case topLevelTypes.topMouseOver:
|
|
case topLevelTypes.topMouseUp:
|
|
EventConstructor = SyntheticMouseEvent;
|
|
break;
|
|
case topLevelTypes.topDrag:
|
|
case topLevelTypes.topDragEnd:
|
|
case topLevelTypes.topDragEnter:
|
|
case topLevelTypes.topDragExit:
|
|
case topLevelTypes.topDragLeave:
|
|
case topLevelTypes.topDragOver:
|
|
case topLevelTypes.topDragStart:
|
|
case topLevelTypes.topDrop:
|
|
EventConstructor = SyntheticDragEvent;
|
|
break;
|
|
case topLevelTypes.topTouchCancel:
|
|
case topLevelTypes.topTouchEnd:
|
|
case topLevelTypes.topTouchMove:
|
|
case topLevelTypes.topTouchStart:
|
|
EventConstructor = SyntheticTouchEvent;
|
|
break;
|
|
case topLevelTypes.topScroll:
|
|
EventConstructor = SyntheticUIEvent;
|
|
break;
|
|
case topLevelTypes.topWheel:
|
|
EventConstructor = SyntheticWheelEvent;
|
|
break;
|
|
case topLevelTypes.topCopy:
|
|
case topLevelTypes.topCut:
|
|
case topLevelTypes.topPaste:
|
|
EventConstructor = SyntheticClipboardEvent;
|
|
break;
|
|
}
|
|
!EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined;
|
|
var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget);
|
|
EventPropagators.accumulateTwoPhaseDispatches(event);
|
|
return event;
|
|
},
|
|
|
|
didPutListener: function (id, registrationName, listener) {
|
|
// Mobile Safari does not fire properly bubble click events on
|
|
// non-interactive elements, which means delegated click listeners do not
|
|
// fire. The workaround for this bug involves attaching an empty click
|
|
// listener on the target node.
|
|
if (registrationName === ON_CLICK_KEY) {
|
|
var node = ReactMount.getNode(id);
|
|
if (!onClickListeners[id]) {
|
|
onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction);
|
|
}
|
|
}
|
|
},
|
|
|
|
willDeleteListener: function (id, registrationName) {
|
|
if (registrationName === ON_CLICK_KEY) {
|
|
onClickListeners[id].remove();
|
|
delete onClickListeners[id];
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = SimpleEventPlugin;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 133 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticClipboardEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticEvent = __webpack_require__(77);
|
|
|
|
/**
|
|
* @interface Event
|
|
* @see http://www.w3.org/TR/clipboard-apis/
|
|
*/
|
|
var ClipboardEventInterface = {
|
|
clipboardData: function (event) {
|
|
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
|
|
|
|
module.exports = SyntheticClipboardEvent;
|
|
|
|
/***/ }),
|
|
/* 134 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticFocusEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticUIEvent = __webpack_require__(87);
|
|
|
|
/**
|
|
* @interface FocusEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var FocusEventInterface = {
|
|
relatedTarget: null
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
|
|
|
|
module.exports = SyntheticFocusEvent;
|
|
|
|
/***/ }),
|
|
/* 135 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticKeyboardEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticUIEvent = __webpack_require__(87);
|
|
|
|
var getEventCharCode = __webpack_require__(136);
|
|
var getEventKey = __webpack_require__(137);
|
|
var getEventModifierState = __webpack_require__(88);
|
|
|
|
/**
|
|
* @interface KeyboardEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var KeyboardEventInterface = {
|
|
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;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
|
|
|
|
module.exports = SyntheticKeyboardEvent;
|
|
|
|
/***/ }),
|
|
/* 136 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getEventCharCode
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* `charCode` represents the actual "character code" and is safe to use with
|
|
* `String.fromCharCode`. As such, only keys that correspond to printable
|
|
* characters produce a valid `charCode`, the only exception to this is Enter.
|
|
* The Tab-key is considered non-printable and does not have a `charCode`,
|
|
* presumably because it does not produce a tab-character in browsers.
|
|
*
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @return {number} Normalized `charCode` property.
|
|
*/
|
|
function getEventCharCode(nativeEvent) {
|
|
var charCode;
|
|
var keyCode = nativeEvent.keyCode;
|
|
|
|
if ('charCode' in nativeEvent) {
|
|
charCode = nativeEvent.charCode;
|
|
|
|
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
|
|
if (charCode === 0 && keyCode === 13) {
|
|
charCode = 13;
|
|
}
|
|
} else {
|
|
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
|
|
charCode = keyCode;
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
module.exports = getEventCharCode;
|
|
|
|
/***/ }),
|
|
/* 137 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule getEventKey
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var getEventCharCode = __webpack_require__(136);
|
|
|
|
/**
|
|
* 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 '';
|
|
}
|
|
|
|
module.exports = getEventKey;
|
|
|
|
/***/ }),
|
|
/* 138 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticDragEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticMouseEvent = __webpack_require__(86);
|
|
|
|
/**
|
|
* @interface DragEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var DragEventInterface = {
|
|
dataTransfer: null
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
|
|
|
|
module.exports = SyntheticDragEvent;
|
|
|
|
/***/ }),
|
|
/* 139 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticTouchEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticUIEvent = __webpack_require__(87);
|
|
|
|
var getEventModifierState = __webpack_require__(88);
|
|
|
|
/**
|
|
* @interface TouchEvent
|
|
* @see http://www.w3.org/TR/touch-events/
|
|
*/
|
|
var TouchEventInterface = {
|
|
touches: null,
|
|
targetTouches: null,
|
|
changedTouches: null,
|
|
altKey: null,
|
|
metaKey: null,
|
|
ctrlKey: null,
|
|
shiftKey: null,
|
|
getModifierState: getEventModifierState
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticUIEvent}
|
|
*/
|
|
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
|
|
|
|
module.exports = SyntheticTouchEvent;
|
|
|
|
/***/ }),
|
|
/* 140 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SyntheticWheelEvent
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var SyntheticMouseEvent = __webpack_require__(86);
|
|
|
|
/**
|
|
* @interface WheelEvent
|
|
* @see http://www.w3.org/TR/DOM-Level-3-Events/
|
|
*/
|
|
var WheelEventInterface = {
|
|
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
|
|
};
|
|
|
|
/**
|
|
* @param {object} dispatchConfig Configuration used to dispatch this event.
|
|
* @param {string} dispatchMarker Marker identifying the event target.
|
|
* @param {object} nativeEvent Native browser event.
|
|
* @extends {SyntheticMouseEvent}
|
|
*/
|
|
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
|
|
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
|
|
}
|
|
|
|
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
|
|
|
|
module.exports = SyntheticWheelEvent;
|
|
|
|
/***/ }),
|
|
/* 141 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule SVGDOMPropertyConfig
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
|
|
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
|
|
|
|
var NS = {
|
|
xlink: 'http://www.w3.org/1999/xlink',
|
|
xml: 'http://www.w3.org/XML/1998/namespace'
|
|
};
|
|
|
|
var SVGDOMPropertyConfig = {
|
|
Properties: {
|
|
clipPath: MUST_USE_ATTRIBUTE,
|
|
cx: MUST_USE_ATTRIBUTE,
|
|
cy: MUST_USE_ATTRIBUTE,
|
|
d: MUST_USE_ATTRIBUTE,
|
|
dx: MUST_USE_ATTRIBUTE,
|
|
dy: MUST_USE_ATTRIBUTE,
|
|
fill: MUST_USE_ATTRIBUTE,
|
|
fillOpacity: MUST_USE_ATTRIBUTE,
|
|
fontFamily: MUST_USE_ATTRIBUTE,
|
|
fontSize: MUST_USE_ATTRIBUTE,
|
|
fx: MUST_USE_ATTRIBUTE,
|
|
fy: MUST_USE_ATTRIBUTE,
|
|
gradientTransform: MUST_USE_ATTRIBUTE,
|
|
gradientUnits: MUST_USE_ATTRIBUTE,
|
|
markerEnd: MUST_USE_ATTRIBUTE,
|
|
markerMid: MUST_USE_ATTRIBUTE,
|
|
markerStart: MUST_USE_ATTRIBUTE,
|
|
offset: MUST_USE_ATTRIBUTE,
|
|
opacity: MUST_USE_ATTRIBUTE,
|
|
patternContentUnits: MUST_USE_ATTRIBUTE,
|
|
patternUnits: MUST_USE_ATTRIBUTE,
|
|
points: MUST_USE_ATTRIBUTE,
|
|
preserveAspectRatio: MUST_USE_ATTRIBUTE,
|
|
r: MUST_USE_ATTRIBUTE,
|
|
rx: MUST_USE_ATTRIBUTE,
|
|
ry: MUST_USE_ATTRIBUTE,
|
|
spreadMethod: MUST_USE_ATTRIBUTE,
|
|
stopColor: MUST_USE_ATTRIBUTE,
|
|
stopOpacity: MUST_USE_ATTRIBUTE,
|
|
stroke: MUST_USE_ATTRIBUTE,
|
|
strokeDasharray: MUST_USE_ATTRIBUTE,
|
|
strokeLinecap: MUST_USE_ATTRIBUTE,
|
|
strokeOpacity: MUST_USE_ATTRIBUTE,
|
|
strokeWidth: MUST_USE_ATTRIBUTE,
|
|
textAnchor: MUST_USE_ATTRIBUTE,
|
|
transform: MUST_USE_ATTRIBUTE,
|
|
version: MUST_USE_ATTRIBUTE,
|
|
viewBox: MUST_USE_ATTRIBUTE,
|
|
x1: MUST_USE_ATTRIBUTE,
|
|
x2: MUST_USE_ATTRIBUTE,
|
|
x: MUST_USE_ATTRIBUTE,
|
|
xlinkActuate: MUST_USE_ATTRIBUTE,
|
|
xlinkArcrole: MUST_USE_ATTRIBUTE,
|
|
xlinkHref: MUST_USE_ATTRIBUTE,
|
|
xlinkRole: MUST_USE_ATTRIBUTE,
|
|
xlinkShow: MUST_USE_ATTRIBUTE,
|
|
xlinkTitle: MUST_USE_ATTRIBUTE,
|
|
xlinkType: MUST_USE_ATTRIBUTE,
|
|
xmlBase: MUST_USE_ATTRIBUTE,
|
|
xmlLang: MUST_USE_ATTRIBUTE,
|
|
xmlSpace: MUST_USE_ATTRIBUTE,
|
|
y1: MUST_USE_ATTRIBUTE,
|
|
y2: MUST_USE_ATTRIBUTE,
|
|
y: MUST_USE_ATTRIBUTE
|
|
},
|
|
DOMAttributeNamespaces: {
|
|
xlinkActuate: NS.xlink,
|
|
xlinkArcrole: NS.xlink,
|
|
xlinkHref: NS.xlink,
|
|
xlinkRole: NS.xlink,
|
|
xlinkShow: NS.xlink,
|
|
xlinkTitle: NS.xlink,
|
|
xlinkType: NS.xlink,
|
|
xmlBase: NS.xml,
|
|
xmlLang: NS.xml,
|
|
xmlSpace: NS.xml
|
|
},
|
|
DOMAttributeNames: {
|
|
clipPath: 'clip-path',
|
|
fillOpacity: 'fill-opacity',
|
|
fontFamily: 'font-family',
|
|
fontSize: 'font-size',
|
|
gradientTransform: 'gradientTransform',
|
|
gradientUnits: 'gradientUnits',
|
|
markerEnd: 'marker-end',
|
|
markerMid: 'marker-mid',
|
|
markerStart: 'marker-start',
|
|
patternContentUnits: 'patternContentUnits',
|
|
patternUnits: 'patternUnits',
|
|
preserveAspectRatio: 'preserveAspectRatio',
|
|
spreadMethod: 'spreadMethod',
|
|
stopColor: 'stop-color',
|
|
stopOpacity: 'stop-opacity',
|
|
strokeDasharray: 'stroke-dasharray',
|
|
strokeLinecap: 'stroke-linecap',
|
|
strokeOpacity: 'stroke-opacity',
|
|
strokeWidth: 'stroke-width',
|
|
textAnchor: 'text-anchor',
|
|
viewBox: 'viewBox',
|
|
xlinkActuate: 'xlink:actuate',
|
|
xlinkArcrole: 'xlink:arcrole',
|
|
xlinkHref: 'xlink:href',
|
|
xlinkRole: 'xlink:role',
|
|
xlinkShow: 'xlink:show',
|
|
xlinkTitle: 'xlink:title',
|
|
xlinkType: 'xlink:type',
|
|
xmlBase: 'xml:base',
|
|
xmlLang: 'xml:lang',
|
|
xmlSpace: 'xml:space'
|
|
}
|
|
};
|
|
|
|
module.exports = SVGDOMPropertyConfig;
|
|
|
|
/***/ }),
|
|
/* 142 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDefaultPerf
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var DOMProperty = __webpack_require__(23);
|
|
var ReactDefaultPerfAnalysis = __webpack_require__(143);
|
|
var ReactMount = __webpack_require__(28);
|
|
var ReactPerf = __webpack_require__(18);
|
|
|
|
var performanceNow = __webpack_require__(144);
|
|
|
|
function roundFloat(val) {
|
|
return Math.floor(val * 100) / 100;
|
|
}
|
|
|
|
function addValue(obj, key, val) {
|
|
obj[key] = (obj[key] || 0) + val;
|
|
}
|
|
|
|
var ReactDefaultPerf = {
|
|
_allMeasurements: [], // last item in the list is the current one
|
|
_mountStack: [0],
|
|
_injected: false,
|
|
|
|
start: function () {
|
|
if (!ReactDefaultPerf._injected) {
|
|
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
|
|
}
|
|
|
|
ReactDefaultPerf._allMeasurements.length = 0;
|
|
ReactPerf.enableMeasure = true;
|
|
},
|
|
|
|
stop: function () {
|
|
ReactPerf.enableMeasure = false;
|
|
},
|
|
|
|
getLastMeasurements: function () {
|
|
return ReactDefaultPerf._allMeasurements;
|
|
},
|
|
|
|
printExclusive: function (measurements) {
|
|
measurements = measurements || ReactDefaultPerf._allMeasurements;
|
|
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
|
|
console.table(summary.map(function (item) {
|
|
return {
|
|
'Component class name': item.componentName,
|
|
'Total inclusive time (ms)': roundFloat(item.inclusive),
|
|
'Exclusive mount time (ms)': roundFloat(item.exclusive),
|
|
'Exclusive render time (ms)': roundFloat(item.render),
|
|
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
|
|
'Render time per instance (ms)': roundFloat(item.render / item.count),
|
|
'Instances': item.count
|
|
};
|
|
}));
|
|
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
|
|
// number.
|
|
},
|
|
|
|
printInclusive: function (measurements) {
|
|
measurements = measurements || ReactDefaultPerf._allMeasurements;
|
|
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
|
|
console.table(summary.map(function (item) {
|
|
return {
|
|
'Owner > component': item.componentName,
|
|
'Inclusive time (ms)': roundFloat(item.time),
|
|
'Instances': item.count
|
|
};
|
|
}));
|
|
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
|
|
},
|
|
|
|
getMeasurementsSummaryMap: function (measurements) {
|
|
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true);
|
|
return summary.map(function (item) {
|
|
return {
|
|
'Owner > component': item.componentName,
|
|
'Wasted time (ms)': item.time,
|
|
'Instances': item.count
|
|
};
|
|
});
|
|
},
|
|
|
|
printWasted: function (measurements) {
|
|
measurements = measurements || ReactDefaultPerf._allMeasurements;
|
|
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
|
|
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
|
|
},
|
|
|
|
printDOM: function (measurements) {
|
|
measurements = measurements || ReactDefaultPerf._allMeasurements;
|
|
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
|
|
console.table(summary.map(function (item) {
|
|
var result = {};
|
|
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
|
|
result.type = item.type;
|
|
result.args = JSON.stringify(item.args);
|
|
return result;
|
|
}));
|
|
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
|
|
},
|
|
|
|
_recordWrite: function (id, fnName, totalTime, args) {
|
|
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
|
|
var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes;
|
|
writes[id] = writes[id] || [];
|
|
writes[id].push({
|
|
type: fnName,
|
|
time: totalTime,
|
|
args: args
|
|
});
|
|
},
|
|
|
|
measure: function (moduleName, fnName, func) {
|
|
return function () {
|
|
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
|
|
args[_key] = arguments[_key];
|
|
}
|
|
|
|
var totalTime;
|
|
var rv;
|
|
var start;
|
|
|
|
if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') {
|
|
// A "measurement" is a set of metrics recorded for each flush. We want
|
|
// to group the metrics for a given flush together so we can look at the
|
|
// components that rendered and the DOM operations that actually
|
|
// happened to determine the amount of "wasted work" performed.
|
|
ReactDefaultPerf._allMeasurements.push({
|
|
exclusive: {},
|
|
inclusive: {},
|
|
render: {},
|
|
counts: {},
|
|
writes: {},
|
|
displayNames: {},
|
|
totalTime: 0,
|
|
created: {}
|
|
});
|
|
start = performanceNow();
|
|
rv = func.apply(this, args);
|
|
ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start;
|
|
return rv;
|
|
} else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') {
|
|
start = performanceNow();
|
|
rv = func.apply(this, args);
|
|
totalTime = performanceNow() - start;
|
|
|
|
if (fnName === '_mountImageIntoNode') {
|
|
var mountID = ReactMount.getID(args[1]);
|
|
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
|
|
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
|
|
// special format
|
|
args[0].forEach(function (update) {
|
|
var writeArgs = {};
|
|
if (update.fromIndex !== null) {
|
|
writeArgs.fromIndex = update.fromIndex;
|
|
}
|
|
if (update.toIndex !== null) {
|
|
writeArgs.toIndex = update.toIndex;
|
|
}
|
|
if (update.textContent !== null) {
|
|
writeArgs.textContent = update.textContent;
|
|
}
|
|
if (update.markupIndex !== null) {
|
|
writeArgs.markup = args[1][update.markupIndex];
|
|
}
|
|
ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs);
|
|
});
|
|
} else {
|
|
// basic format
|
|
var id = args[0];
|
|
if (typeof id === 'object') {
|
|
id = ReactMount.getID(args[0]);
|
|
}
|
|
ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1));
|
|
}
|
|
return rv;
|
|
} else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()?
|
|
fnName === '_renderValidatedComponent')) {
|
|
|
|
if (this._currentElement.type === ReactMount.TopLevelWrapper) {
|
|
return func.apply(this, args);
|
|
}
|
|
|
|
var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID;
|
|
var isRender = fnName === '_renderValidatedComponent';
|
|
var isMount = fnName === 'mountComponent';
|
|
|
|
var mountStack = ReactDefaultPerf._mountStack;
|
|
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
|
|
|
|
if (isRender) {
|
|
addValue(entry.counts, rootNodeID, 1);
|
|
} else if (isMount) {
|
|
entry.created[rootNodeID] = true;
|
|
mountStack.push(0);
|
|
}
|
|
|
|
start = performanceNow();
|
|
rv = func.apply(this, args);
|
|
totalTime = performanceNow() - start;
|
|
|
|
if (isRender) {
|
|
addValue(entry.render, rootNodeID, totalTime);
|
|
} else if (isMount) {
|
|
var subMountTime = mountStack.pop();
|
|
mountStack[mountStack.length - 1] += totalTime;
|
|
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
|
|
addValue(entry.inclusive, rootNodeID, totalTime);
|
|
} else {
|
|
addValue(entry.inclusive, rootNodeID, totalTime);
|
|
}
|
|
|
|
entry.displayNames[rootNodeID] = {
|
|
current: this.getName(),
|
|
owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>'
|
|
};
|
|
|
|
return rv;
|
|
} else {
|
|
return func.apply(this, args);
|
|
}
|
|
};
|
|
}
|
|
};
|
|
|
|
module.exports = ReactDefaultPerf;
|
|
|
|
/***/ }),
|
|
/* 143 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDefaultPerfAnalysis
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var assign = __webpack_require__(39);
|
|
|
|
// Don't try to save users less than 1.2ms (a number I made up)
|
|
var DONT_CARE_THRESHOLD = 1.2;
|
|
var DOM_OPERATION_TYPES = {
|
|
'_mountImageIntoNode': 'set innerHTML',
|
|
INSERT_MARKUP: 'set innerHTML',
|
|
MOVE_EXISTING: 'move',
|
|
REMOVE_NODE: 'remove',
|
|
SET_MARKUP: 'set innerHTML',
|
|
TEXT_CONTENT: 'set textContent',
|
|
'setValueForProperty': 'update attribute',
|
|
'setValueForAttribute': 'update attribute',
|
|
'deleteValueForProperty': 'remove attribute',
|
|
'setValueForStyles': 'update styles',
|
|
'replaceNodeWithMarkup': 'replace',
|
|
'updateTextContent': 'set textContent'
|
|
};
|
|
|
|
function getTotalTime(measurements) {
|
|
// TODO: return number of DOM ops? could be misleading.
|
|
// TODO: measure dropped frames after reconcile?
|
|
// TODO: log total time of each reconcile and the top-level component
|
|
// class that triggered it.
|
|
var totalTime = 0;
|
|
for (var i = 0; i < measurements.length; i++) {
|
|
var measurement = measurements[i];
|
|
totalTime += measurement.totalTime;
|
|
}
|
|
return totalTime;
|
|
}
|
|
|
|
function getDOMSummary(measurements) {
|
|
var items = [];
|
|
measurements.forEach(function (measurement) {
|
|
Object.keys(measurement.writes).forEach(function (id) {
|
|
measurement.writes[id].forEach(function (write) {
|
|
items.push({
|
|
id: id,
|
|
type: DOM_OPERATION_TYPES[write.type] || write.type,
|
|
args: write.args
|
|
});
|
|
});
|
|
});
|
|
});
|
|
return items;
|
|
}
|
|
|
|
function getExclusiveSummary(measurements) {
|
|
var candidates = {};
|
|
var displayName;
|
|
|
|
for (var i = 0; i < measurements.length; i++) {
|
|
var measurement = measurements[i];
|
|
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
|
|
|
|
for (var id in allIDs) {
|
|
displayName = measurement.displayNames[id].current;
|
|
|
|
candidates[displayName] = candidates[displayName] || {
|
|
componentName: displayName,
|
|
inclusive: 0,
|
|
exclusive: 0,
|
|
render: 0,
|
|
count: 0
|
|
};
|
|
if (measurement.render[id]) {
|
|
candidates[displayName].render += measurement.render[id];
|
|
}
|
|
if (measurement.exclusive[id]) {
|
|
candidates[displayName].exclusive += measurement.exclusive[id];
|
|
}
|
|
if (measurement.inclusive[id]) {
|
|
candidates[displayName].inclusive += measurement.inclusive[id];
|
|
}
|
|
if (measurement.counts[id]) {
|
|
candidates[displayName].count += measurement.counts[id];
|
|
}
|
|
}
|
|
}
|
|
|
|
// Now make a sorted array with the results.
|
|
var arr = [];
|
|
for (displayName in candidates) {
|
|
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
|
|
arr.push(candidates[displayName]);
|
|
}
|
|
}
|
|
|
|
arr.sort(function (a, b) {
|
|
return b.exclusive - a.exclusive;
|
|
});
|
|
|
|
return arr;
|
|
}
|
|
|
|
function getInclusiveSummary(measurements, onlyClean) {
|
|
var candidates = {};
|
|
var inclusiveKey;
|
|
|
|
for (var i = 0; i < measurements.length; i++) {
|
|
var measurement = measurements[i];
|
|
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
|
|
var cleanComponents;
|
|
|
|
if (onlyClean) {
|
|
cleanComponents = getUnchangedComponents(measurement);
|
|
}
|
|
|
|
for (var id in allIDs) {
|
|
if (onlyClean && !cleanComponents[id]) {
|
|
continue;
|
|
}
|
|
|
|
var displayName = measurement.displayNames[id];
|
|
|
|
// Inclusive time is not useful for many components without knowing where
|
|
// they are instantiated. So we aggregate inclusive time with both the
|
|
// owner and current displayName as the key.
|
|
inclusiveKey = displayName.owner + ' > ' + displayName.current;
|
|
|
|
candidates[inclusiveKey] = candidates[inclusiveKey] || {
|
|
componentName: inclusiveKey,
|
|
time: 0,
|
|
count: 0
|
|
};
|
|
|
|
if (measurement.inclusive[id]) {
|
|
candidates[inclusiveKey].time += measurement.inclusive[id];
|
|
}
|
|
if (measurement.counts[id]) {
|
|
candidates[inclusiveKey].count += measurement.counts[id];
|
|
}
|
|
}
|
|
}
|
|
|
|
// Now make a sorted array with the results.
|
|
var arr = [];
|
|
for (inclusiveKey in candidates) {
|
|
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
|
|
arr.push(candidates[inclusiveKey]);
|
|
}
|
|
}
|
|
|
|
arr.sort(function (a, b) {
|
|
return b.time - a.time;
|
|
});
|
|
|
|
return arr;
|
|
}
|
|
|
|
function getUnchangedComponents(measurement) {
|
|
// For a given reconcile, look at which components did not actually
|
|
// render anything to the DOM and return a mapping of their ID to
|
|
// the amount of time it took to render the entire subtree.
|
|
var cleanComponents = {};
|
|
var dirtyLeafIDs = Object.keys(measurement.writes);
|
|
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
|
|
|
|
for (var id in allIDs) {
|
|
var isDirty = false;
|
|
// For each component that rendered, see if a component that triggered
|
|
// a DOM op is in its subtree.
|
|
for (var i = 0; i < dirtyLeafIDs.length; i++) {
|
|
if (dirtyLeafIDs[i].indexOf(id) === 0) {
|
|
isDirty = true;
|
|
break;
|
|
}
|
|
}
|
|
// check if component newly created
|
|
if (measurement.created[id]) {
|
|
isDirty = true;
|
|
}
|
|
if (!isDirty && measurement.counts[id] > 0) {
|
|
cleanComponents[id] = true;
|
|
}
|
|
}
|
|
return cleanComponents;
|
|
}
|
|
|
|
var ReactDefaultPerfAnalysis = {
|
|
getExclusiveSummary: getExclusiveSummary,
|
|
getInclusiveSummary: getInclusiveSummary,
|
|
getDOMSummary: getDOMSummary,
|
|
getTotalTime: getTotalTime
|
|
};
|
|
|
|
module.exports = ReactDefaultPerfAnalysis;
|
|
|
|
/***/ }),
|
|
/* 144 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule performanceNow
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var performance = __webpack_require__(145);
|
|
|
|
var performanceNow;
|
|
|
|
/**
|
|
* Detect if we can use `window.performance.now()` and gracefully fallback to
|
|
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
|
|
* because of Facebook's testing infrastructure.
|
|
*/
|
|
if (performance.now) {
|
|
performanceNow = function () {
|
|
return performance.now();
|
|
};
|
|
} else {
|
|
performanceNow = function () {
|
|
return Date.now();
|
|
};
|
|
}
|
|
|
|
module.exports = performanceNow;
|
|
|
|
/***/ }),
|
|
/* 145 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule performance
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ExecutionEnvironment = __webpack_require__(9);
|
|
|
|
var performance;
|
|
|
|
if (ExecutionEnvironment.canUseDOM) {
|
|
performance = window.performance || window.msPerformance || window.webkitPerformance;
|
|
}
|
|
|
|
module.exports = performance || {};
|
|
|
|
/***/ }),
|
|
/* 146 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactVersion
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
module.exports = '0.14.10';
|
|
|
|
|
|
/***/ }),
|
|
/* 147 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule renderSubtreeIntoContainer
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactMount = __webpack_require__(28);
|
|
|
|
module.exports = ReactMount.renderSubtreeIntoContainer;
|
|
|
|
/***/ }),
|
|
/* 148 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMServer
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactDefaultInjection = __webpack_require__(71);
|
|
var ReactServerRendering = __webpack_require__(149);
|
|
var ReactVersion = __webpack_require__(146);
|
|
|
|
ReactDefaultInjection.inject();
|
|
|
|
var ReactDOMServer = {
|
|
renderToString: ReactServerRendering.renderToString,
|
|
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
|
|
version: ReactVersion
|
|
};
|
|
|
|
module.exports = ReactDOMServer;
|
|
|
|
/***/ }),
|
|
/* 149 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @typechecks static-only
|
|
* @providesModule ReactServerRendering
|
|
*/
|
|
'use strict';
|
|
|
|
var ReactDefaultBatchingStrategy = __webpack_require__(92);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactInstanceHandles = __webpack_require__(45);
|
|
var ReactMarkupChecksum = __webpack_require__(48);
|
|
var ReactServerBatchingStrategy = __webpack_require__(150);
|
|
var ReactServerRenderingTransaction = __webpack_require__(151);
|
|
var ReactUpdates = __webpack_require__(54);
|
|
|
|
var emptyObject = __webpack_require__(58);
|
|
var instantiateReactComponent = __webpack_require__(62);
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* @param {ReactElement} element
|
|
* @return {string} the HTML markup
|
|
*/
|
|
function renderToString(element) {
|
|
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
|
|
|
|
var transaction;
|
|
try {
|
|
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
|
|
|
|
var id = ReactInstanceHandles.createReactRootID();
|
|
transaction = ReactServerRenderingTransaction.getPooled(false);
|
|
|
|
return transaction.perform(function () {
|
|
var componentInstance = instantiateReactComponent(element, null);
|
|
var markup = componentInstance.mountComponent(id, transaction, emptyObject);
|
|
return ReactMarkupChecksum.addChecksumToMarkup(markup);
|
|
}, null);
|
|
} finally {
|
|
ReactServerRenderingTransaction.release(transaction);
|
|
// Revert to the DOM batching strategy since these two renderers
|
|
// currently share these stateful modules.
|
|
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param {ReactElement} element
|
|
* @return {string} the HTML markup, without the extra React ID and checksum
|
|
* (for generating static pages)
|
|
*/
|
|
function renderToStaticMarkup(element) {
|
|
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
|
|
|
|
var transaction;
|
|
try {
|
|
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
|
|
|
|
var id = ReactInstanceHandles.createReactRootID();
|
|
transaction = ReactServerRenderingTransaction.getPooled(true);
|
|
|
|
return transaction.perform(function () {
|
|
var componentInstance = instantiateReactComponent(element, null);
|
|
return componentInstance.mountComponent(id, transaction, emptyObject);
|
|
}, null);
|
|
} finally {
|
|
ReactServerRenderingTransaction.release(transaction);
|
|
// Revert to the DOM batching strategy since these two renderers
|
|
// currently share these stateful modules.
|
|
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
renderToString: renderToString,
|
|
renderToStaticMarkup: renderToStaticMarkup
|
|
};
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 150 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactServerBatchingStrategy
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactServerBatchingStrategy = {
|
|
isBatchingUpdates: false,
|
|
batchedUpdates: function (callback) {
|
|
// Don't do anything here. During the server rendering we don't want to
|
|
// schedule any updates. We will simply ignore them.
|
|
}
|
|
};
|
|
|
|
module.exports = ReactServerBatchingStrategy;
|
|
|
|
/***/ }),
|
|
/* 151 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactServerRenderingTransaction
|
|
* @typechecks
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var PooledClass = __webpack_require__(56);
|
|
var CallbackQueue = __webpack_require__(55);
|
|
var Transaction = __webpack_require__(57);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var emptyFunction = __webpack_require__(15);
|
|
|
|
/**
|
|
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
|
|
* during the performing of the transaction.
|
|
*/
|
|
var ON_DOM_READY_QUEUEING = {
|
|
/**
|
|
* Initializes the internal `onDOMReady` queue.
|
|
*/
|
|
initialize: function () {
|
|
this.reactMountReady.reset();
|
|
},
|
|
|
|
close: emptyFunction
|
|
};
|
|
|
|
/**
|
|
* Executed within the scope of the `Transaction` instance. Consider these as
|
|
* being member methods, but with an implied ordering while being isolated from
|
|
* each other.
|
|
*/
|
|
var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
|
|
|
|
/**
|
|
* @class ReactServerRenderingTransaction
|
|
* @param {boolean} renderToStaticMarkup
|
|
*/
|
|
function ReactServerRenderingTransaction(renderToStaticMarkup) {
|
|
this.reinitializeTransaction();
|
|
this.renderToStaticMarkup = renderToStaticMarkup;
|
|
this.reactMountReady = CallbackQueue.getPooled(null);
|
|
this.useCreateElement = false;
|
|
}
|
|
|
|
var Mixin = {
|
|
/**
|
|
* @see Transaction
|
|
* @abstract
|
|
* @final
|
|
* @return {array} Empty list of operation wrap procedures.
|
|
*/
|
|
getTransactionWrappers: function () {
|
|
return TRANSACTION_WRAPPERS;
|
|
},
|
|
|
|
/**
|
|
* @return {object} The queue to collect `onDOMReady` callbacks with.
|
|
*/
|
|
getReactMountReady: function () {
|
|
return this.reactMountReady;
|
|
},
|
|
|
|
/**
|
|
* `PooledClass` looks for this, and will invoke this before allowing this
|
|
* instance to be reused.
|
|
*/
|
|
destructor: function () {
|
|
CallbackQueue.release(this.reactMountReady);
|
|
this.reactMountReady = null;
|
|
}
|
|
};
|
|
|
|
assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
|
|
|
|
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
|
|
|
|
module.exports = ReactServerRenderingTransaction;
|
|
|
|
/***/ }),
|
|
/* 152 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactIsomorphic
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactChildren = __webpack_require__(110);
|
|
var ReactComponent = __webpack_require__(123);
|
|
var ReactClass = __webpack_require__(122);
|
|
var ReactDOMFactories = __webpack_require__(153);
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactElementValidator = __webpack_require__(154);
|
|
var ReactPropTypes = __webpack_require__(107);
|
|
var ReactVersion = __webpack_require__(146);
|
|
|
|
var assign = __webpack_require__(39);
|
|
var onlyChild = __webpack_require__(156);
|
|
|
|
var createElement = ReactElement.createElement;
|
|
var createFactory = ReactElement.createFactory;
|
|
var cloneElement = ReactElement.cloneElement;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
createElement = ReactElementValidator.createElement;
|
|
createFactory = ReactElementValidator.createFactory;
|
|
cloneElement = ReactElementValidator.cloneElement;
|
|
}
|
|
|
|
var React = {
|
|
|
|
// Modern
|
|
|
|
Children: {
|
|
map: ReactChildren.map,
|
|
forEach: ReactChildren.forEach,
|
|
count: ReactChildren.count,
|
|
toArray: ReactChildren.toArray,
|
|
only: onlyChild
|
|
},
|
|
|
|
Component: ReactComponent,
|
|
|
|
createElement: createElement,
|
|
cloneElement: cloneElement,
|
|
isValidElement: ReactElement.isValidElement,
|
|
|
|
// Classic
|
|
|
|
PropTypes: ReactPropTypes,
|
|
createClass: ReactClass.createClass,
|
|
createFactory: createFactory,
|
|
createMixin: function (mixin) {
|
|
// Currently a noop. Will be used to validate and trace mixins.
|
|
return mixin;
|
|
},
|
|
|
|
// This looks DOM specific but these are actually isomorphic helpers
|
|
// since they are just generating DOM strings.
|
|
DOM: ReactDOMFactories,
|
|
|
|
version: ReactVersion,
|
|
|
|
// Hook for JSX spread, don't use this for anything else.
|
|
__spread: assign
|
|
};
|
|
|
|
module.exports = React;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 153 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactDOMFactories
|
|
* @typechecks static-only
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactElementValidator = __webpack_require__(154);
|
|
|
|
var mapObject = __webpack_require__(155);
|
|
|
|
/**
|
|
* Create a factory that creates HTML tag elements.
|
|
*
|
|
* @param {string} tag Tag name (e.g. `div`).
|
|
* @private
|
|
*/
|
|
function createDOMFactory(tag) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
return ReactElementValidator.createFactory(tag);
|
|
}
|
|
return ReactElement.createFactory(tag);
|
|
}
|
|
|
|
/**
|
|
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
|
|
* This is also accessible via `React.DOM`.
|
|
*
|
|
* @public
|
|
*/
|
|
var ReactDOMFactories = mapObject({
|
|
a: 'a',
|
|
abbr: 'abbr',
|
|
address: 'address',
|
|
area: 'area',
|
|
article: 'article',
|
|
aside: 'aside',
|
|
audio: 'audio',
|
|
b: 'b',
|
|
base: 'base',
|
|
bdi: 'bdi',
|
|
bdo: 'bdo',
|
|
big: 'big',
|
|
blockquote: 'blockquote',
|
|
body: 'body',
|
|
br: 'br',
|
|
button: 'button',
|
|
canvas: 'canvas',
|
|
caption: 'caption',
|
|
cite: 'cite',
|
|
code: 'code',
|
|
col: 'col',
|
|
colgroup: 'colgroup',
|
|
data: 'data',
|
|
datalist: 'datalist',
|
|
dd: 'dd',
|
|
del: 'del',
|
|
details: 'details',
|
|
dfn: 'dfn',
|
|
dialog: 'dialog',
|
|
div: 'div',
|
|
dl: 'dl',
|
|
dt: 'dt',
|
|
em: 'em',
|
|
embed: 'embed',
|
|
fieldset: 'fieldset',
|
|
figcaption: 'figcaption',
|
|
figure: 'figure',
|
|
footer: 'footer',
|
|
form: 'form',
|
|
h1: 'h1',
|
|
h2: 'h2',
|
|
h3: 'h3',
|
|
h4: 'h4',
|
|
h5: 'h5',
|
|
h6: 'h6',
|
|
head: 'head',
|
|
header: 'header',
|
|
hgroup: 'hgroup',
|
|
hr: 'hr',
|
|
html: 'html',
|
|
i: 'i',
|
|
iframe: 'iframe',
|
|
img: 'img',
|
|
input: 'input',
|
|
ins: 'ins',
|
|
kbd: 'kbd',
|
|
keygen: 'keygen',
|
|
label: 'label',
|
|
legend: 'legend',
|
|
li: 'li',
|
|
link: 'link',
|
|
main: 'main',
|
|
map: 'map',
|
|
mark: 'mark',
|
|
menu: 'menu',
|
|
menuitem: 'menuitem',
|
|
meta: 'meta',
|
|
meter: 'meter',
|
|
nav: 'nav',
|
|
noscript: 'noscript',
|
|
object: 'object',
|
|
ol: 'ol',
|
|
optgroup: 'optgroup',
|
|
option: 'option',
|
|
output: 'output',
|
|
p: 'p',
|
|
param: 'param',
|
|
picture: 'picture',
|
|
pre: 'pre',
|
|
progress: 'progress',
|
|
q: 'q',
|
|
rp: 'rp',
|
|
rt: 'rt',
|
|
ruby: 'ruby',
|
|
s: 's',
|
|
samp: 'samp',
|
|
script: 'script',
|
|
section: 'section',
|
|
select: 'select',
|
|
small: 'small',
|
|
source: 'source',
|
|
span: 'span',
|
|
strong: 'strong',
|
|
style: 'style',
|
|
sub: 'sub',
|
|
summary: 'summary',
|
|
sup: 'sup',
|
|
table: 'table',
|
|
tbody: 'tbody',
|
|
td: 'td',
|
|
textarea: 'textarea',
|
|
tfoot: 'tfoot',
|
|
th: 'th',
|
|
thead: 'thead',
|
|
time: 'time',
|
|
title: 'title',
|
|
tr: 'tr',
|
|
track: 'track',
|
|
u: 'u',
|
|
ul: 'ul',
|
|
'var': 'var',
|
|
video: 'video',
|
|
wbr: 'wbr',
|
|
|
|
// SVG
|
|
circle: 'circle',
|
|
clipPath: 'clipPath',
|
|
defs: 'defs',
|
|
ellipse: 'ellipse',
|
|
g: 'g',
|
|
image: 'image',
|
|
line: 'line',
|
|
linearGradient: 'linearGradient',
|
|
mask: 'mask',
|
|
path: 'path',
|
|
pattern: 'pattern',
|
|
polygon: 'polygon',
|
|
polyline: 'polyline',
|
|
radialGradient: 'radialGradient',
|
|
rect: 'rect',
|
|
stop: 'stop',
|
|
svg: 'svg',
|
|
text: 'text',
|
|
tspan: 'tspan'
|
|
|
|
}, createDOMFactory);
|
|
|
|
module.exports = ReactDOMFactories;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 154 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2014-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactElementValidator
|
|
*/
|
|
|
|
/**
|
|
* ReactElementValidator provides a wrapper around a element factory
|
|
* which validates the props passed to the element. This is intended to be
|
|
* used only in DEV and could be replaced by a static type checker for languages
|
|
* that support it.
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var ReactElement = __webpack_require__(42);
|
|
var ReactPropTypeLocations = __webpack_require__(65);
|
|
var ReactPropTypeLocationNames = __webpack_require__(66);
|
|
var ReactCurrentOwner = __webpack_require__(5);
|
|
|
|
var canDefineProperty = __webpack_require__(43);
|
|
var getIteratorFn = __webpack_require__(108);
|
|
var invariant = __webpack_require__(13);
|
|
var warning = __webpack_require__(25);
|
|
|
|
function getDeclarationErrorAddendum() {
|
|
if (ReactCurrentOwner.current) {
|
|
var name = ReactCurrentOwner.current.getName();
|
|
if (name) {
|
|
return ' Check the render method of `' + name + '`.';
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Warn if there's no key explicitly set on dynamic arrays of children or
|
|
* object keys are not valid. This allows us to keep track of children between
|
|
* updates.
|
|
*/
|
|
var ownerHasKeyUseWarning = {};
|
|
|
|
var loggedTypeFailures = {};
|
|
|
|
/**
|
|
* Warn if the element doesn't have an explicit key assigned to it.
|
|
* This element is in an array. The array could grow and shrink or be
|
|
* reordered. All children that haven't already been validated are required to
|
|
* have a "key" property assigned to it.
|
|
*
|
|
* @internal
|
|
* @param {ReactElement} element Element that requires a key.
|
|
* @param {*} parentType element's parent's type.
|
|
*/
|
|
function validateExplicitKey(element, parentType) {
|
|
if (!element._store || element._store.validated || element.key != null) {
|
|
return;
|
|
}
|
|
element._store.validated = true;
|
|
|
|
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
|
|
if (addenda === null) {
|
|
// we already showed the warning
|
|
return;
|
|
}
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
|
|
}
|
|
|
|
/**
|
|
* Shared warning and monitoring code for the key warnings.
|
|
*
|
|
* @internal
|
|
* @param {string} messageType A key used for de-duping warnings.
|
|
* @param {ReactElement} element Component that requires a key.
|
|
* @param {*} parentType element's parent's type.
|
|
* @returns {?object} A set of addenda to use in the warning message, or null
|
|
* if the warning has already been shown before (and shouldn't be shown again).
|
|
*/
|
|
function getAddendaForKeyUse(messageType, element, parentType) {
|
|
var addendum = getDeclarationErrorAddendum();
|
|
if (!addendum) {
|
|
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
|
|
if (parentName) {
|
|
addendum = ' Check the top-level render call using <' + parentName + '>.';
|
|
}
|
|
}
|
|
|
|
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
|
|
if (memoizer[addendum]) {
|
|
return null;
|
|
}
|
|
memoizer[addendum] = true;
|
|
|
|
var addenda = {
|
|
parentOrOwner: addendum,
|
|
url: ' See https://fb.me/react-warning-keys for more information.',
|
|
childOwner: null
|
|
};
|
|
|
|
// Usually the current owner is the offender, but if it accepts children as a
|
|
// property, it may be the creator of the child that's responsible for
|
|
// assigning it a key.
|
|
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
|
|
// Give the component that originally created this child.
|
|
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
|
|
}
|
|
|
|
return addenda;
|
|
}
|
|
|
|
/**
|
|
* Ensure that every element either is passed in a static location, in an
|
|
* array with an explicit keys property defined, or in an object literal
|
|
* with valid key property.
|
|
*
|
|
* @internal
|
|
* @param {ReactNode} node Statically passed child of any type.
|
|
* @param {*} parentType node's parent's type.
|
|
*/
|
|
function validateChildKeys(node, parentType) {
|
|
if (typeof node !== 'object') {
|
|
return;
|
|
}
|
|
if (Array.isArray(node)) {
|
|
for (var i = 0; i < node.length; i++) {
|
|
var child = node[i];
|
|
if (ReactElement.isValidElement(child)) {
|
|
validateExplicitKey(child, parentType);
|
|
}
|
|
}
|
|
} else if (ReactElement.isValidElement(node)) {
|
|
// This element was passed in a valid location.
|
|
if (node._store) {
|
|
node._store.validated = true;
|
|
}
|
|
} else if (node) {
|
|
var iteratorFn = getIteratorFn(node);
|
|
// Entry iterators provide implicit keys.
|
|
if (iteratorFn) {
|
|
if (iteratorFn !== node.entries) {
|
|
var iterator = iteratorFn.call(node);
|
|
var step;
|
|
while (!(step = iterator.next()).done) {
|
|
if (ReactElement.isValidElement(step.value)) {
|
|
validateExplicitKey(step.value, parentType);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Assert that the props are valid
|
|
*
|
|
* @param {string} componentName Name of the component for error messages.
|
|
* @param {object} propTypes Map of prop name to a ReactPropType
|
|
* @param {object} props
|
|
* @param {string} location e.g. "prop", "context", "child context"
|
|
* @private
|
|
*/
|
|
function checkPropTypes(componentName, propTypes, props, location) {
|
|
for (var propName in propTypes) {
|
|
if (propTypes.hasOwnProperty(propName)) {
|
|
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.
|
|
!(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
|
|
error = propTypes[propName](props, propName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
} catch (ex) {
|
|
error = ex;
|
|
}
|
|
process.env.NODE_ENV !== 'production' ? 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', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
|
|
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 addendum = getDeclarationErrorAddendum();
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Given an element, validate that its props follow the propTypes definition,
|
|
* provided by the type.
|
|
*
|
|
* @param {ReactElement} element
|
|
*/
|
|
function validatePropTypes(element) {
|
|
var componentClass = element.type;
|
|
if (typeof componentClass !== 'function') {
|
|
return;
|
|
}
|
|
var name = componentClass.displayName || componentClass.name;
|
|
if (componentClass.propTypes) {
|
|
checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop);
|
|
}
|
|
if (typeof componentClass.getDefaultProps === 'function') {
|
|
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined;
|
|
}
|
|
}
|
|
|
|
var ReactElementValidator = {
|
|
|
|
createElement: function (type, props, children) {
|
|
var validType = typeof type === 'string' || typeof type === 'function';
|
|
// We warn in this case but don't throw. We expect the element creation to
|
|
// succeed and there will likely be errors in render.
|
|
process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined;
|
|
|
|
var element = ReactElement.createElement.apply(this, arguments);
|
|
|
|
// The result can be nullish if a mock or a custom function is used.
|
|
// TODO: Drop this when these are no longer allowed as the type argument.
|
|
if (element == null) {
|
|
return element;
|
|
}
|
|
|
|
// Skip key warning if the type isn't valid since our key validation logic
|
|
// doesn't expect a non-string/function type and can throw confusing errors.
|
|
// We don't want exception behavior to differ between dev and prod.
|
|
// (Rendering will throw with a helpful message and as soon as the type is
|
|
// fixed, the key warnings will appear.)
|
|
if (validType) {
|
|
for (var i = 2; i < arguments.length; i++) {
|
|
validateChildKeys(arguments[i], type);
|
|
}
|
|
}
|
|
|
|
validatePropTypes(element);
|
|
|
|
return element;
|
|
},
|
|
|
|
createFactory: function (type) {
|
|
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
|
|
// Legacy hook TODO: Warn if this is accessed
|
|
validatedFactory.type = type;
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
if (canDefineProperty) {
|
|
Object.defineProperty(validatedFactory, 'type', {
|
|
enumerable: false,
|
|
get: function () {
|
|
process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined;
|
|
Object.defineProperty(this, 'type', {
|
|
value: type
|
|
});
|
|
return type;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
return validatedFactory;
|
|
},
|
|
|
|
cloneElement: function (element, props, children) {
|
|
var newElement = ReactElement.cloneElement.apply(this, arguments);
|
|
for (var i = 2; i < arguments.length; i++) {
|
|
validateChildKeys(arguments[i], newElement.type);
|
|
}
|
|
validatePropTypes(newElement);
|
|
return newElement;
|
|
}
|
|
|
|
};
|
|
|
|
module.exports = ReactElementValidator;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 155 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule mapObject
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
|
|
/**
|
|
* Executes the provided `callback` once for each enumerable own property in the
|
|
* object and constructs a new object from the results. The `callback` is
|
|
* invoked with three arguments:
|
|
*
|
|
* - the property value
|
|
* - the property name
|
|
* - the object being traversed
|
|
*
|
|
* Properties that are added after the call to `mapObject` will not be visited
|
|
* by `callback`. If the values of existing properties are changed, the value
|
|
* passed to `callback` will be the value at the time `mapObject` visits them.
|
|
* Properties that are deleted before being visited are not visited.
|
|
*
|
|
* @grep function objectMap()
|
|
* @grep function objMap()
|
|
*
|
|
* @param {?object} object
|
|
* @param {function} callback
|
|
* @param {*} context
|
|
* @return {?object}
|
|
*/
|
|
function mapObject(object, callback, context) {
|
|
if (!object) {
|
|
return null;
|
|
}
|
|
var result = {};
|
|
for (var name in object) {
|
|
if (hasOwnProperty.call(object, name)) {
|
|
result[name] = callback.call(context, object[name], name, object);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
module.exports = mapObject;
|
|
|
|
/***/ }),
|
|
/* 156 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule onlyChild
|
|
*/
|
|
'use strict';
|
|
|
|
var ReactElement = __webpack_require__(42);
|
|
|
|
var invariant = __webpack_require__(13);
|
|
|
|
/**
|
|
* Returns the first child in a collection of children and verifies that there
|
|
* is only one child in the collection. The current implementation of this
|
|
* function assumes that a single child gets passed without a wrapper, but the
|
|
* purpose of this helper function is to abstract away the particular structure
|
|
* of children.
|
|
*
|
|
* @param {?object} children Child collection structure.
|
|
* @return {ReactComponent} The first and only `ReactComponent` contained in the
|
|
* structure.
|
|
*/
|
|
function onlyChild(children) {
|
|
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
|
|
return children;
|
|
}
|
|
|
|
module.exports = onlyChild;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 157 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(process) {/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule deprecated
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var assign = __webpack_require__(39);
|
|
var warning = __webpack_require__(25);
|
|
|
|
/**
|
|
* This will log a single deprecation notice per function and forward the call
|
|
* on to the new API.
|
|
*
|
|
* @param {string} fnName The name of the function
|
|
* @param {string} newModule The module that fn will exist in
|
|
* @param {string} newPackage The module that fn will exist in
|
|
* @param {*} ctx The context this forwarded call should run in
|
|
* @param {function} fn The function to forward on to
|
|
* @return {function} The function that will warn once and then call fn
|
|
*/
|
|
function deprecated(fnName, newModule, newPackage, ctx, fn) {
|
|
var warned = false;
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
var newFn = function () {
|
|
process.env.NODE_ENV !== 'production' ? warning(warned,
|
|
// Require examples in this string must be split to prevent React's
|
|
// build tools from mistaking them for real requires.
|
|
// Otherwise the build tools will attempt to build a '%s' module.
|
|
'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined;
|
|
warned = true;
|
|
return fn.apply(ctx, arguments);
|
|
};
|
|
// We need to make sure all properties of the original fn are copied over.
|
|
// In particular, this is needed to support PropTypes
|
|
return assign(newFn, fn);
|
|
}
|
|
|
|
return fn;
|
|
}
|
|
|
|
module.exports = deprecated;
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
|
|
|
|
/***/ }),
|
|
/* 158 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
module.exports = __webpack_require__(3);
|
|
|
|
|
|
/***/ }),
|
|
/* 159 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/*
|
|
* Copyright Joyent, Inc. and other Node contributors.
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person obtaining a
|
|
* copy of this software and associated documentation files (the
|
|
* "Software"), to deal in the Software without restriction, including
|
|
* without limitation the rights to use, copy, modify, merge, publish,
|
|
* distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
* persons to whom the Software is furnished to do so, subject to the
|
|
* following conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be included
|
|
* in all copies or substantial portions of the Software.
|
|
*
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
|
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
* USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var punycode = __webpack_require__(160);
|
|
|
|
function Url() {
|
|
this.protocol = null;
|
|
this.slashes = null;
|
|
this.auth = null;
|
|
this.host = null;
|
|
this.port = null;
|
|
this.hostname = null;
|
|
this.hash = null;
|
|
this.search = null;
|
|
this.query = null;
|
|
this.pathname = null;
|
|
this.path = null;
|
|
this.href = null;
|
|
}
|
|
|
|
// Reference: RFC 3986, RFC 1808, RFC 2396
|
|
|
|
/*
|
|
* define these here so at least they only have to be
|
|
* compiled once on the first module load.
|
|
*/
|
|
var protocolPattern = /^([a-z0-9.+-]+:)/i,
|
|
portPattern = /:[0-9]*$/,
|
|
|
|
// Special case for a simple path URL
|
|
simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,
|
|
|
|
/*
|
|
* RFC 2396: characters reserved for delimiting URLs.
|
|
* We actually just auto-escape these.
|
|
*/
|
|
delims = [
|
|
'<', '>', '"', '`', ' ', '\r', '\n', '\t'
|
|
],
|
|
|
|
// RFC 2396: characters not allowed for various reasons.
|
|
unwise = [
|
|
'{', '}', '|', '\\', '^', '`'
|
|
].concat(delims),
|
|
|
|
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
|
|
autoEscape = ['\''].concat(unwise),
|
|
/*
|
|
* Characters that are never ever allowed in a hostname.
|
|
* Note that any invalid chars are also handled, but these
|
|
* are the ones that are *expected* to be seen, so we fast-path
|
|
* them.
|
|
*/
|
|
nonHostChars = [
|
|
'%', '/', '?', ';', '#'
|
|
].concat(autoEscape),
|
|
hostEndingChars = [
|
|
'/', '?', '#'
|
|
],
|
|
hostnameMaxLen = 255,
|
|
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
|
|
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
|
|
// protocols that can allow "unsafe" and "unwise" chars.
|
|
unsafeProtocol = {
|
|
javascript: true,
|
|
'javascript:': true
|
|
},
|
|
// protocols that never have a hostname.
|
|
hostlessProtocol = {
|
|
javascript: true,
|
|
'javascript:': true
|
|
},
|
|
// protocols that always contain a // bit.
|
|
slashedProtocol = {
|
|
http: true,
|
|
https: true,
|
|
ftp: true,
|
|
gopher: true,
|
|
file: true,
|
|
'http:': true,
|
|
'https:': true,
|
|
'ftp:': true,
|
|
'gopher:': true,
|
|
'file:': true
|
|
},
|
|
querystring = __webpack_require__(162);
|
|
|
|
function urlParse(url, parseQueryString, slashesDenoteHost) {
|
|
if (url && typeof url === 'object' && url instanceof Url) { return url; }
|
|
|
|
var u = new Url();
|
|
u.parse(url, parseQueryString, slashesDenoteHost);
|
|
return u;
|
|
}
|
|
|
|
Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
|
|
if (typeof url !== 'string') {
|
|
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
|
|
}
|
|
|
|
/*
|
|
* Copy chrome, IE, opera backslash-handling behavior.
|
|
* Back slashes before the query string get converted to forward slashes
|
|
* See: https://code.google.com/p/chromium/issues/detail?id=25916
|
|
*/
|
|
var queryIndex = url.indexOf('?'),
|
|
splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#',
|
|
uSplit = url.split(splitter),
|
|
slashRegex = /\\/g;
|
|
uSplit[0] = uSplit[0].replace(slashRegex, '/');
|
|
url = uSplit.join(splitter);
|
|
|
|
var rest = url;
|
|
|
|
/*
|
|
* trim before proceeding.
|
|
* This is to support parse stuff like " http://foo.com \n"
|
|
*/
|
|
rest = rest.trim();
|
|
|
|
if (!slashesDenoteHost && url.split('#').length === 1) {
|
|
// Try fast path regexp
|
|
var simplePath = simplePathPattern.exec(rest);
|
|
if (simplePath) {
|
|
this.path = rest;
|
|
this.href = rest;
|
|
this.pathname = simplePath[1];
|
|
if (simplePath[2]) {
|
|
this.search = simplePath[2];
|
|
if (parseQueryString) {
|
|
this.query = querystring.parse(this.search.substr(1));
|
|
} else {
|
|
this.query = this.search.substr(1);
|
|
}
|
|
} else if (parseQueryString) {
|
|
this.search = '';
|
|
this.query = {};
|
|
}
|
|
return this;
|
|
}
|
|
}
|
|
|
|
var proto = protocolPattern.exec(rest);
|
|
if (proto) {
|
|
proto = proto[0];
|
|
var lowerProto = proto.toLowerCase();
|
|
this.protocol = lowerProto;
|
|
rest = rest.substr(proto.length);
|
|
}
|
|
|
|
/*
|
|
* figure out if it's got a host
|
|
* user@server is *always* interpreted as a hostname, and url
|
|
* resolution will treat //foo/bar as host=foo,path=bar because that's
|
|
* how the browser resolves relative URLs.
|
|
*/
|
|
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) {
|
|
var slashes = rest.substr(0, 2) === '//';
|
|
if (slashes && !(proto && hostlessProtocol[proto])) {
|
|
rest = rest.substr(2);
|
|
this.slashes = true;
|
|
}
|
|
}
|
|
|
|
if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) {
|
|
|
|
/*
|
|
* there's a hostname.
|
|
* the first instance of /, ?, ;, or # ends the host.
|
|
*
|
|
* If there is an @ in the hostname, then non-host chars *are* allowed
|
|
* to the left of the last @ sign, unless some host-ending character
|
|
* comes *before* the @-sign.
|
|
* URLs are obnoxious.
|
|
*
|
|
* ex:
|
|
* http://a@b@c/ => user:a@b host:c
|
|
* http://a@b?@c => user:a host:c path:/?@c
|
|
*/
|
|
|
|
/*
|
|
* v0.12 TODO(isaacs): This is not quite how Chrome does things.
|
|
* Review our test case against browsers more comprehensively.
|
|
*/
|
|
|
|
// find the first instance of any hostEndingChars
|
|
var hostEnd = -1;
|
|
for (var i = 0; i < hostEndingChars.length; i++) {
|
|
var hec = rest.indexOf(hostEndingChars[i]);
|
|
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }
|
|
}
|
|
|
|
/*
|
|
* at this point, either we have an explicit point where the
|
|
* auth portion cannot go past, or the last @ char is the decider.
|
|
*/
|
|
var auth, atSign;
|
|
if (hostEnd === -1) {
|
|
// atSign can be anywhere.
|
|
atSign = rest.lastIndexOf('@');
|
|
} else {
|
|
/*
|
|
* atSign must be in auth portion.
|
|
* http://a@b/c@d => host:b auth:a path:/c@d
|
|
*/
|
|
atSign = rest.lastIndexOf('@', hostEnd);
|
|
}
|
|
|
|
/*
|
|
* Now we have a portion which is definitely the auth.
|
|
* Pull that off.
|
|
*/
|
|
if (atSign !== -1) {
|
|
auth = rest.slice(0, atSign);
|
|
rest = rest.slice(atSign + 1);
|
|
this.auth = decodeURIComponent(auth);
|
|
}
|
|
|
|
// the host is the remaining to the left of the first non-host char
|
|
hostEnd = -1;
|
|
for (var i = 0; i < nonHostChars.length; i++) {
|
|
var hec = rest.indexOf(nonHostChars[i]);
|
|
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }
|
|
}
|
|
// if we still have not hit it, then the entire thing is a host.
|
|
if (hostEnd === -1) { hostEnd = rest.length; }
|
|
|
|
this.host = rest.slice(0, hostEnd);
|
|
rest = rest.slice(hostEnd);
|
|
|
|
// pull out port.
|
|
this.parseHost();
|
|
|
|
/*
|
|
* we've indicated that there is a hostname,
|
|
* so even if it's empty, it has to be present.
|
|
*/
|
|
this.hostname = this.hostname || '';
|
|
|
|
/*
|
|
* if hostname begins with [ and ends with ]
|
|
* assume that it's an IPv6 address.
|
|
*/
|
|
var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';
|
|
|
|
// validate a little.
|
|
if (!ipv6Hostname) {
|
|
var hostparts = this.hostname.split(/\./);
|
|
for (var i = 0, l = hostparts.length; i < l; i++) {
|
|
var part = hostparts[i];
|
|
if (!part) { continue; }
|
|
if (!part.match(hostnamePartPattern)) {
|
|
var newpart = '';
|
|
for (var j = 0, k = part.length; j < k; j++) {
|
|
if (part.charCodeAt(j) > 127) {
|
|
/*
|
|
* we replace non-ASCII char with a temporary placeholder
|
|
* we need this to make sure size of hostname is not
|
|
* broken by replacing non-ASCII by nothing
|
|
*/
|
|
newpart += 'x';
|
|
} else {
|
|
newpart += part[j];
|
|
}
|
|
}
|
|
// we test again with ASCII char only
|
|
if (!newpart.match(hostnamePartPattern)) {
|
|
var validParts = hostparts.slice(0, i);
|
|
var notHost = hostparts.slice(i + 1);
|
|
var bit = part.match(hostnamePartStart);
|
|
if (bit) {
|
|
validParts.push(bit[1]);
|
|
notHost.unshift(bit[2]);
|
|
}
|
|
if (notHost.length) {
|
|
rest = '/' + notHost.join('.') + rest;
|
|
}
|
|
this.hostname = validParts.join('.');
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (this.hostname.length > hostnameMaxLen) {
|
|
this.hostname = '';
|
|
} else {
|
|
// hostnames are always lower case.
|
|
this.hostname = this.hostname.toLowerCase();
|
|
}
|
|
|
|
if (!ipv6Hostname) {
|
|
/*
|
|
* IDNA Support: Returns a punycoded representation of "domain".
|
|
* It only converts parts of the domain name that
|
|
* have non-ASCII characters, i.e. it doesn't matter if
|
|
* you call it with a domain that already is ASCII-only.
|
|
*/
|
|
this.hostname = punycode.toASCII(this.hostname);
|
|
}
|
|
|
|
var p = this.port ? ':' + this.port : '';
|
|
var h = this.hostname || '';
|
|
this.host = h + p;
|
|
this.href += this.host;
|
|
|
|
/*
|
|
* strip [ and ] from the hostname
|
|
* the host field still retains them, though
|
|
*/
|
|
if (ipv6Hostname) {
|
|
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
|
|
if (rest[0] !== '/') {
|
|
rest = '/' + rest;
|
|
}
|
|
}
|
|
}
|
|
|
|
/*
|
|
* now rest is set to the post-host stuff.
|
|
* chop off any delim chars.
|
|
*/
|
|
if (!unsafeProtocol[lowerProto]) {
|
|
|
|
/*
|
|
* First, make 100% sure that any "autoEscape" chars get
|
|
* escaped, even if encodeURIComponent doesn't think they
|
|
* need to be.
|
|
*/
|
|
for (var i = 0, l = autoEscape.length; i < l; i++) {
|
|
var ae = autoEscape[i];
|
|
if (rest.indexOf(ae) === -1) { continue; }
|
|
var esc = encodeURIComponent(ae);
|
|
if (esc === ae) {
|
|
esc = escape(ae);
|
|
}
|
|
rest = rest.split(ae).join(esc);
|
|
}
|
|
}
|
|
|
|
// chop off from the tail first.
|
|
var hash = rest.indexOf('#');
|
|
if (hash !== -1) {
|
|
// got a fragment string.
|
|
this.hash = rest.substr(hash);
|
|
rest = rest.slice(0, hash);
|
|
}
|
|
var qm = rest.indexOf('?');
|
|
if (qm !== -1) {
|
|
this.search = rest.substr(qm);
|
|
this.query = rest.substr(qm + 1);
|
|
if (parseQueryString) {
|
|
this.query = querystring.parse(this.query);
|
|
}
|
|
rest = rest.slice(0, qm);
|
|
} else if (parseQueryString) {
|
|
// no query string, but parseQueryString still requested
|
|
this.search = '';
|
|
this.query = {};
|
|
}
|
|
if (rest) { this.pathname = rest; }
|
|
if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
|
|
this.pathname = '/';
|
|
}
|
|
|
|
// to support http.request
|
|
if (this.pathname || this.search) {
|
|
var p = this.pathname || '';
|
|
var s = this.search || '';
|
|
this.path = p + s;
|
|
}
|
|
|
|
// finally, reconstruct the href based on what has been validated.
|
|
this.href = this.format();
|
|
return this;
|
|
};
|
|
|
|
// format a parsed object into a url string
|
|
function urlFormat(obj) {
|
|
/*
|
|
* ensure it's an object, and not a string url.
|
|
* If it's an obj, this is a no-op.
|
|
* this way, you can call url_format() on strings
|
|
* to clean up potentially wonky urls.
|
|
*/
|
|
if (typeof obj === 'string') { obj = urlParse(obj); }
|
|
if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }
|
|
return obj.format();
|
|
}
|
|
|
|
Url.prototype.format = function () {
|
|
var auth = this.auth || '';
|
|
if (auth) {
|
|
auth = encodeURIComponent(auth);
|
|
auth = auth.replace(/%3A/i, ':');
|
|
auth += '@';
|
|
}
|
|
|
|
var protocol = this.protocol || '',
|
|
pathname = this.pathname || '',
|
|
hash = this.hash || '',
|
|
host = false,
|
|
query = '';
|
|
|
|
if (this.host) {
|
|
host = auth + this.host;
|
|
} else if (this.hostname) {
|
|
host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']');
|
|
if (this.port) {
|
|
host += ':' + this.port;
|
|
}
|
|
}
|
|
|
|
if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) {
|
|
query = querystring.stringify(this.query, {
|
|
arrayFormat: 'repeat',
|
|
addQueryPrefix: false
|
|
});
|
|
}
|
|
|
|
var search = this.search || (query && ('?' + query)) || '';
|
|
|
|
if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }
|
|
|
|
/*
|
|
* only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
|
|
* unless they had them to begin with.
|
|
*/
|
|
if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {
|
|
host = '//' + (host || '');
|
|
if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }
|
|
} else if (!host) {
|
|
host = '';
|
|
}
|
|
|
|
if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }
|
|
if (search && search.charAt(0) !== '?') { search = '?' + search; }
|
|
|
|
pathname = pathname.replace(/[?#]/g, function (match) {
|
|
return encodeURIComponent(match);
|
|
});
|
|
search = search.replace('#', '%23');
|
|
|
|
return protocol + host + pathname + search + hash;
|
|
};
|
|
|
|
function urlResolve(source, relative) {
|
|
return urlParse(source, false, true).resolve(relative);
|
|
}
|
|
|
|
Url.prototype.resolve = function (relative) {
|
|
return this.resolveObject(urlParse(relative, false, true)).format();
|
|
};
|
|
|
|
function urlResolveObject(source, relative) {
|
|
if (!source) { return relative; }
|
|
return urlParse(source, false, true).resolveObject(relative);
|
|
}
|
|
|
|
Url.prototype.resolveObject = function (relative) {
|
|
if (typeof relative === 'string') {
|
|
var rel = new Url();
|
|
rel.parse(relative, false, true);
|
|
relative = rel;
|
|
}
|
|
|
|
var result = new Url();
|
|
var tkeys = Object.keys(this);
|
|
for (var tk = 0; tk < tkeys.length; tk++) {
|
|
var tkey = tkeys[tk];
|
|
result[tkey] = this[tkey];
|
|
}
|
|
|
|
/*
|
|
* hash is always overridden, no matter what.
|
|
* even href="" will remove it.
|
|
*/
|
|
result.hash = relative.hash;
|
|
|
|
// if the relative url is empty, then there's nothing left to do here.
|
|
if (relative.href === '') {
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
// hrefs like //foo/bar always cut to the protocol.
|
|
if (relative.slashes && !relative.protocol) {
|
|
// take everything except the protocol from relative
|
|
var rkeys = Object.keys(relative);
|
|
for (var rk = 0; rk < rkeys.length; rk++) {
|
|
var rkey = rkeys[rk];
|
|
if (rkey !== 'protocol') { result[rkey] = relative[rkey]; }
|
|
}
|
|
|
|
// urlParse appends trailing / to urls like http://www.example.com
|
|
if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) {
|
|
result.pathname = '/';
|
|
result.path = result.pathname;
|
|
}
|
|
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
if (relative.protocol && relative.protocol !== result.protocol) {
|
|
/*
|
|
* if it's a known url protocol, then changing
|
|
* the protocol does weird things
|
|
* first, if it's not file:, then we MUST have a host,
|
|
* and if there was a path
|
|
* to begin with, then we MUST have a path.
|
|
* if it is file:, then the host is dropped,
|
|
* because that's known to be hostless.
|
|
* anything else is assumed to be absolute.
|
|
*/
|
|
if (!slashedProtocol[relative.protocol]) {
|
|
var keys = Object.keys(relative);
|
|
for (var v = 0; v < keys.length; v++) {
|
|
var k = keys[v];
|
|
result[k] = relative[k];
|
|
}
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
result.protocol = relative.protocol;
|
|
if (!relative.host && !hostlessProtocol[relative.protocol]) {
|
|
var relPath = (relative.pathname || '').split('/');
|
|
while (relPath.length && !(relative.host = relPath.shift())) { }
|
|
if (!relative.host) { relative.host = ''; }
|
|
if (!relative.hostname) { relative.hostname = ''; }
|
|
if (relPath[0] !== '') { relPath.unshift(''); }
|
|
if (relPath.length < 2) { relPath.unshift(''); }
|
|
result.pathname = relPath.join('/');
|
|
} else {
|
|
result.pathname = relative.pathname;
|
|
}
|
|
result.search = relative.search;
|
|
result.query = relative.query;
|
|
result.host = relative.host || '';
|
|
result.auth = relative.auth;
|
|
result.hostname = relative.hostname || relative.host;
|
|
result.port = relative.port;
|
|
// to support http.request
|
|
if (result.pathname || result.search) {
|
|
var p = result.pathname || '';
|
|
var s = result.search || '';
|
|
result.path = p + s;
|
|
}
|
|
result.slashes = result.slashes || relative.slashes;
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/',
|
|
isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/',
|
|
mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname),
|
|
removeAllDots = mustEndAbs,
|
|
srcPath = result.pathname && result.pathname.split('/') || [],
|
|
relPath = relative.pathname && relative.pathname.split('/') || [],
|
|
psychotic = result.protocol && !slashedProtocol[result.protocol];
|
|
|
|
/*
|
|
* if the url is a non-slashed url, then relative
|
|
* links like ../.. should be able
|
|
* to crawl up to the hostname, as well. This is strange.
|
|
* result.protocol has already been set by now.
|
|
* Later on, put the first path part into the host field.
|
|
*/
|
|
if (psychotic) {
|
|
result.hostname = '';
|
|
result.port = null;
|
|
if (result.host) {
|
|
if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); }
|
|
}
|
|
result.host = '';
|
|
if (relative.protocol) {
|
|
relative.hostname = null;
|
|
relative.port = null;
|
|
if (relative.host) {
|
|
if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); }
|
|
}
|
|
relative.host = null;
|
|
}
|
|
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
|
|
}
|
|
|
|
if (isRelAbs) {
|
|
// it's absolute.
|
|
result.host = relative.host || relative.host === '' ? relative.host : result.host;
|
|
result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname;
|
|
result.search = relative.search;
|
|
result.query = relative.query;
|
|
srcPath = relPath;
|
|
// fall through to the dot-handling below.
|
|
} else if (relPath.length) {
|
|
/*
|
|
* it's relative
|
|
* throw away the existing file, and take the new path instead.
|
|
*/
|
|
if (!srcPath) { srcPath = []; }
|
|
srcPath.pop();
|
|
srcPath = srcPath.concat(relPath);
|
|
result.search = relative.search;
|
|
result.query = relative.query;
|
|
} else if (relative.search != null) {
|
|
/*
|
|
* just pull out the search.
|
|
* like href='?foo'.
|
|
* Put this after the other two cases because it simplifies the booleans
|
|
*/
|
|
if (psychotic) {
|
|
result.host = srcPath.shift();
|
|
result.hostname = result.host;
|
|
/*
|
|
* occationaly the auth can get stuck only in host
|
|
* this especially happens in cases like
|
|
* url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
|
*/
|
|
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
|
|
if (authInHost) {
|
|
result.auth = authInHost.shift();
|
|
result.hostname = authInHost.shift();
|
|
result.host = result.hostname;
|
|
}
|
|
}
|
|
result.search = relative.search;
|
|
result.query = relative.query;
|
|
// to support http.request
|
|
if (result.pathname !== null || result.search !== null) {
|
|
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
|
|
}
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
if (!srcPath.length) {
|
|
/*
|
|
* no path at all. easy.
|
|
* we've already handled the other stuff above.
|
|
*/
|
|
result.pathname = null;
|
|
// to support http.request
|
|
if (result.search) {
|
|
result.path = '/' + result.search;
|
|
} else {
|
|
result.path = null;
|
|
}
|
|
result.href = result.format();
|
|
return result;
|
|
}
|
|
|
|
/*
|
|
* if a url ENDs in . or .., then it must get a trailing slash.
|
|
* however, if it ends in anything else non-slashy,
|
|
* then it must NOT get a trailing slash.
|
|
*/
|
|
var last = srcPath.slice(-1)[0];
|
|
var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === '';
|
|
|
|
/*
|
|
* strip single dots, resolve double dots to parent dir
|
|
* if the path tries to go above the root, `up` ends up > 0
|
|
*/
|
|
var up = 0;
|
|
for (var i = srcPath.length; i >= 0; i--) {
|
|
last = srcPath[i];
|
|
if (last === '.') {
|
|
srcPath.splice(i, 1);
|
|
} else if (last === '..') {
|
|
srcPath.splice(i, 1);
|
|
up++;
|
|
} else if (up) {
|
|
srcPath.splice(i, 1);
|
|
up--;
|
|
}
|
|
}
|
|
|
|
// if the path is allowed to go above the root, restore leading ..s
|
|
if (!mustEndAbs && !removeAllDots) {
|
|
for (; up--; up) {
|
|
srcPath.unshift('..');
|
|
}
|
|
}
|
|
|
|
if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
|
|
srcPath.unshift('');
|
|
}
|
|
|
|
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
|
|
srcPath.push('');
|
|
}
|
|
|
|
var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/');
|
|
|
|
// put the host back
|
|
if (psychotic) {
|
|
result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';
|
|
result.host = result.hostname;
|
|
/*
|
|
* occationaly the auth can get stuck only in host
|
|
* this especially happens in cases like
|
|
* url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
|
*/
|
|
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
|
|
if (authInHost) {
|
|
result.auth = authInHost.shift();
|
|
result.hostname = authInHost.shift();
|
|
result.host = result.hostname;
|
|
}
|
|
}
|
|
|
|
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
|
|
|
|
if (mustEndAbs && !isAbsolute) {
|
|
srcPath.unshift('');
|
|
}
|
|
|
|
if (srcPath.length > 0) {
|
|
result.pathname = srcPath.join('/');
|
|
} else {
|
|
result.pathname = null;
|
|
result.path = null;
|
|
}
|
|
|
|
// to support request.http
|
|
if (result.pathname !== null || result.search !== null) {
|
|
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
|
|
}
|
|
result.auth = relative.auth || result.auth;
|
|
result.slashes = result.slashes || relative.slashes;
|
|
result.href = result.format();
|
|
return result;
|
|
};
|
|
|
|
Url.prototype.parseHost = function () {
|
|
var host = this.host;
|
|
var port = portPattern.exec(host);
|
|
if (port) {
|
|
port = port[0];
|
|
if (port !== ':') {
|
|
this.port = port.substr(1);
|
|
}
|
|
host = host.substr(0, host.length - port.length);
|
|
}
|
|
if (host) { this.hostname = host; }
|
|
};
|
|
|
|
exports.parse = urlParse;
|
|
exports.resolve = urlResolve;
|
|
exports.resolveObject = urlResolveObject;
|
|
exports.format = urlFormat;
|
|
|
|
exports.Url = Url;
|
|
|
|
|
|
/***/ }),
|
|
/* 160 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/punycode v1.4.1 by @mathias */
|
|
;(function(root) {
|
|
|
|
/** Detect free variables */
|
|
var freeExports = typeof exports == 'object' && exports &&
|
|
!exports.nodeType && exports;
|
|
var freeModule = typeof module == 'object' && module &&
|
|
!module.nodeType && module;
|
|
var freeGlobal = typeof global == 'object' && global;
|
|
if (
|
|
freeGlobal.global === freeGlobal ||
|
|
freeGlobal.window === freeGlobal ||
|
|
freeGlobal.self === freeGlobal
|
|
) {
|
|
root = freeGlobal;
|
|
}
|
|
|
|
/**
|
|
* The `punycode` object.
|
|
* @name punycode
|
|
* @type Object
|
|
*/
|
|
var punycode,
|
|
|
|
/** Highest positive signed 32-bit float value */
|
|
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
|
|
|
|
/** Bootstring parameters */
|
|
base = 36,
|
|
tMin = 1,
|
|
tMax = 26,
|
|
skew = 38,
|
|
damp = 700,
|
|
initialBias = 72,
|
|
initialN = 128, // 0x80
|
|
delimiter = '-', // '\x2D'
|
|
|
|
/** Regular expressions */
|
|
regexPunycode = /^xn--/,
|
|
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
|
|
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
|
|
|
|
/** Error messages */
|
|
errors = {
|
|
'overflow': 'Overflow: input needs wider integers to process',
|
|
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
|
|
'invalid-input': 'Invalid input'
|
|
},
|
|
|
|
/** Convenience shortcuts */
|
|
baseMinusTMin = base - tMin,
|
|
floor = Math.floor,
|
|
stringFromCharCode = String.fromCharCode,
|
|
|
|
/** Temporary variable */
|
|
key;
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
/**
|
|
* A generic error utility function.
|
|
* @private
|
|
* @param {String} type The error type.
|
|
* @returns {Error} Throws a `RangeError` with the applicable error message.
|
|
*/
|
|
function error(type) {
|
|
throw new RangeError(errors[type]);
|
|
}
|
|
|
|
/**
|
|
* A generic `Array#map` utility function.
|
|
* @private
|
|
* @param {Array} array The array to iterate over.
|
|
* @param {Function} callback The function that gets called for every array
|
|
* item.
|
|
* @returns {Array} A new array of values returned by the callback function.
|
|
*/
|
|
function map(array, fn) {
|
|
var length = array.length;
|
|
var result = [];
|
|
while (length--) {
|
|
result[length] = fn(array[length]);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* A simple `Array#map`-like wrapper to work with domain name strings or email
|
|
* addresses.
|
|
* @private
|
|
* @param {String} domain The domain name or email address.
|
|
* @param {Function} callback The function that gets called for every
|
|
* character.
|
|
* @returns {Array} A new string of characters returned by the callback
|
|
* function.
|
|
*/
|
|
function mapDomain(string, fn) {
|
|
var parts = string.split('@');
|
|
var result = '';
|
|
if (parts.length > 1) {
|
|
// In email addresses, only the domain name should be punycoded. Leave
|
|
// the local part (i.e. everything up to `@`) intact.
|
|
result = parts[0] + '@';
|
|
string = parts[1];
|
|
}
|
|
// Avoid `split(regex)` for IE8 compatibility. See #17.
|
|
string = string.replace(regexSeparators, '\x2E');
|
|
var labels = string.split('.');
|
|
var encoded = map(labels, fn).join('.');
|
|
return result + encoded;
|
|
}
|
|
|
|
/**
|
|
* Creates an array containing the numeric code points of each Unicode
|
|
* character in the string. While JavaScript uses UCS-2 internally,
|
|
* this function will convert a pair of surrogate halves (each of which
|
|
* UCS-2 exposes as separate characters) into a single code point,
|
|
* matching UTF-16.
|
|
* @see `punycode.ucs2.encode`
|
|
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
|
* @memberOf punycode.ucs2
|
|
* @name decode
|
|
* @param {String} string The Unicode input string (UCS-2).
|
|
* @returns {Array} The new array of code points.
|
|
*/
|
|
function ucs2decode(string) {
|
|
var output = [],
|
|
counter = 0,
|
|
length = string.length,
|
|
value,
|
|
extra;
|
|
while (counter < length) {
|
|
value = string.charCodeAt(counter++);
|
|
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
|
|
// high surrogate, and there is a next character
|
|
extra = string.charCodeAt(counter++);
|
|
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
|
|
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
|
|
} else {
|
|
// unmatched surrogate; only append this code unit, in case the next
|
|
// code unit is the high surrogate of a surrogate pair
|
|
output.push(value);
|
|
counter--;
|
|
}
|
|
} else {
|
|
output.push(value);
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
|
|
/**
|
|
* Creates a string based on an array of numeric code points.
|
|
* @see `punycode.ucs2.decode`
|
|
* @memberOf punycode.ucs2
|
|
* @name encode
|
|
* @param {Array} codePoints The array of numeric code points.
|
|
* @returns {String} The new Unicode string (UCS-2).
|
|
*/
|
|
function ucs2encode(array) {
|
|
return map(array, function(value) {
|
|
var output = '';
|
|
if (value > 0xFFFF) {
|
|
value -= 0x10000;
|
|
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
|
|
value = 0xDC00 | value & 0x3FF;
|
|
}
|
|
output += stringFromCharCode(value);
|
|
return output;
|
|
}).join('');
|
|
}
|
|
|
|
/**
|
|
* Converts a basic code point into a digit/integer.
|
|
* @see `digitToBasic()`
|
|
* @private
|
|
* @param {Number} codePoint The basic numeric code point value.
|
|
* @returns {Number} The numeric value of a basic code point (for use in
|
|
* representing integers) in the range `0` to `base - 1`, or `base` if
|
|
* the code point does not represent a value.
|
|
*/
|
|
function basicToDigit(codePoint) {
|
|
if (codePoint - 48 < 10) {
|
|
return codePoint - 22;
|
|
}
|
|
if (codePoint - 65 < 26) {
|
|
return codePoint - 65;
|
|
}
|
|
if (codePoint - 97 < 26) {
|
|
return codePoint - 97;
|
|
}
|
|
return base;
|
|
}
|
|
|
|
/**
|
|
* Converts a digit/integer into a basic code point.
|
|
* @see `basicToDigit()`
|
|
* @private
|
|
* @param {Number} digit The numeric value of a basic code point.
|
|
* @returns {Number} The basic code point whose value (when used for
|
|
* representing integers) is `digit`, which needs to be in the range
|
|
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
|
|
* used; else, the lowercase form is used. The behavior is undefined
|
|
* if `flag` is non-zero and `digit` has no uppercase form.
|
|
*/
|
|
function digitToBasic(digit, flag) {
|
|
// 0..25 map to ASCII a..z or A..Z
|
|
// 26..35 map to ASCII 0..9
|
|
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
|
|
}
|
|
|
|
/**
|
|
* Bias adaptation function as per section 3.4 of RFC 3492.
|
|
* https://tools.ietf.org/html/rfc3492#section-3.4
|
|
* @private
|
|
*/
|
|
function adapt(delta, numPoints, firstTime) {
|
|
var k = 0;
|
|
delta = firstTime ? floor(delta / damp) : delta >> 1;
|
|
delta += floor(delta / numPoints);
|
|
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
|
|
delta = floor(delta / baseMinusTMin);
|
|
}
|
|
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
|
|
}
|
|
|
|
/**
|
|
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
|
|
* symbols.
|
|
* @memberOf punycode
|
|
* @param {String} input The Punycode string of ASCII-only symbols.
|
|
* @returns {String} The resulting string of Unicode symbols.
|
|
*/
|
|
function decode(input) {
|
|
// Don't use UCS-2
|
|
var output = [],
|
|
inputLength = input.length,
|
|
out,
|
|
i = 0,
|
|
n = initialN,
|
|
bias = initialBias,
|
|
basic,
|
|
j,
|
|
index,
|
|
oldi,
|
|
w,
|
|
k,
|
|
digit,
|
|
t,
|
|
/** Cached calculation results */
|
|
baseMinusT;
|
|
|
|
// Handle the basic code points: let `basic` be the number of input code
|
|
// points before the last delimiter, or `0` if there is none, then copy
|
|
// the first basic code points to the output.
|
|
|
|
basic = input.lastIndexOf(delimiter);
|
|
if (basic < 0) {
|
|
basic = 0;
|
|
}
|
|
|
|
for (j = 0; j < basic; ++j) {
|
|
// if it's not a basic code point
|
|
if (input.charCodeAt(j) >= 0x80) {
|
|
error('not-basic');
|
|
}
|
|
output.push(input.charCodeAt(j));
|
|
}
|
|
|
|
// Main decoding loop: start just after the last delimiter if any basic code
|
|
// points were copied; start at the beginning otherwise.
|
|
|
|
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
|
|
|
|
// `index` is the index of the next character to be consumed.
|
|
// Decode a generalized variable-length integer into `delta`,
|
|
// which gets added to `i`. The overflow checking is easier
|
|
// if we increase `i` as we go, then subtract off its starting
|
|
// value at the end to obtain `delta`.
|
|
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
|
|
|
|
if (index >= inputLength) {
|
|
error('invalid-input');
|
|
}
|
|
|
|
digit = basicToDigit(input.charCodeAt(index++));
|
|
|
|
if (digit >= base || digit > floor((maxInt - i) / w)) {
|
|
error('overflow');
|
|
}
|
|
|
|
i += digit * w;
|
|
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
|
|
|
if (digit < t) {
|
|
break;
|
|
}
|
|
|
|
baseMinusT = base - t;
|
|
if (w > floor(maxInt / baseMinusT)) {
|
|
error('overflow');
|
|
}
|
|
|
|
w *= baseMinusT;
|
|
|
|
}
|
|
|
|
out = output.length + 1;
|
|
bias = adapt(i - oldi, out, oldi == 0);
|
|
|
|
// `i` was supposed to wrap around from `out` to `0`,
|
|
// incrementing `n` each time, so we'll fix that now:
|
|
if (floor(i / out) > maxInt - n) {
|
|
error('overflow');
|
|
}
|
|
|
|
n += floor(i / out);
|
|
i %= out;
|
|
|
|
// Insert `n` at position `i` of the output
|
|
output.splice(i++, 0, n);
|
|
|
|
}
|
|
|
|
return ucs2encode(output);
|
|
}
|
|
|
|
/**
|
|
* Converts a string of Unicode symbols (e.g. a domain name label) to a
|
|
* Punycode string of ASCII-only symbols.
|
|
* @memberOf punycode
|
|
* @param {String} input The string of Unicode symbols.
|
|
* @returns {String} The resulting Punycode string of ASCII-only symbols.
|
|
*/
|
|
function encode(input) {
|
|
var n,
|
|
delta,
|
|
handledCPCount,
|
|
basicLength,
|
|
bias,
|
|
j,
|
|
m,
|
|
q,
|
|
k,
|
|
t,
|
|
currentValue,
|
|
output = [],
|
|
/** `inputLength` will hold the number of code points in `input`. */
|
|
inputLength,
|
|
/** Cached calculation results */
|
|
handledCPCountPlusOne,
|
|
baseMinusT,
|
|
qMinusT;
|
|
|
|
// Convert the input in UCS-2 to Unicode
|
|
input = ucs2decode(input);
|
|
|
|
// Cache the length
|
|
inputLength = input.length;
|
|
|
|
// Initialize the state
|
|
n = initialN;
|
|
delta = 0;
|
|
bias = initialBias;
|
|
|
|
// Handle the basic code points
|
|
for (j = 0; j < inputLength; ++j) {
|
|
currentValue = input[j];
|
|
if (currentValue < 0x80) {
|
|
output.push(stringFromCharCode(currentValue));
|
|
}
|
|
}
|
|
|
|
handledCPCount = basicLength = output.length;
|
|
|
|
// `handledCPCount` is the number of code points that have been handled;
|
|
// `basicLength` is the number of basic code points.
|
|
|
|
// Finish the basic string - if it is not empty - with a delimiter
|
|
if (basicLength) {
|
|
output.push(delimiter);
|
|
}
|
|
|
|
// Main encoding loop:
|
|
while (handledCPCount < inputLength) {
|
|
|
|
// All non-basic code points < n have been handled already. Find the next
|
|
// larger one:
|
|
for (m = maxInt, j = 0; j < inputLength; ++j) {
|
|
currentValue = input[j];
|
|
if (currentValue >= n && currentValue < m) {
|
|
m = currentValue;
|
|
}
|
|
}
|
|
|
|
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
|
|
// but guard against overflow
|
|
handledCPCountPlusOne = handledCPCount + 1;
|
|
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
|
|
error('overflow');
|
|
}
|
|
|
|
delta += (m - n) * handledCPCountPlusOne;
|
|
n = m;
|
|
|
|
for (j = 0; j < inputLength; ++j) {
|
|
currentValue = input[j];
|
|
|
|
if (currentValue < n && ++delta > maxInt) {
|
|
error('overflow');
|
|
}
|
|
|
|
if (currentValue == n) {
|
|
// Represent delta as a generalized variable-length integer
|
|
for (q = delta, k = base; /* no condition */; k += base) {
|
|
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
|
if (q < t) {
|
|
break;
|
|
}
|
|
qMinusT = q - t;
|
|
baseMinusT = base - t;
|
|
output.push(
|
|
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
|
|
);
|
|
q = floor(qMinusT / baseMinusT);
|
|
}
|
|
|
|
output.push(stringFromCharCode(digitToBasic(q, 0)));
|
|
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
|
|
delta = 0;
|
|
++handledCPCount;
|
|
}
|
|
}
|
|
|
|
++delta;
|
|
++n;
|
|
|
|
}
|
|
return output.join('');
|
|
}
|
|
|
|
/**
|
|
* Converts a Punycode string representing a domain name or an email address
|
|
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
|
|
* it doesn't matter if you call it on a string that has already been
|
|
* converted to Unicode.
|
|
* @memberOf punycode
|
|
* @param {String} input The Punycoded domain name or email address to
|
|
* convert to Unicode.
|
|
* @returns {String} The Unicode representation of the given Punycode
|
|
* string.
|
|
*/
|
|
function toUnicode(input) {
|
|
return mapDomain(input, function(string) {
|
|
return regexPunycode.test(string)
|
|
? decode(string.slice(4).toLowerCase())
|
|
: string;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Converts a Unicode string representing a domain name or an email address to
|
|
* Punycode. Only the non-ASCII parts of the domain name will be converted,
|
|
* i.e. it doesn't matter if you call it with a domain that's already in
|
|
* ASCII.
|
|
* @memberOf punycode
|
|
* @param {String} input The domain name or email address to convert, as a
|
|
* Unicode string.
|
|
* @returns {String} The Punycode representation of the given domain name or
|
|
* email address.
|
|
*/
|
|
function toASCII(input) {
|
|
return mapDomain(input, function(string) {
|
|
return regexNonASCII.test(string)
|
|
? 'xn--' + encode(string)
|
|
: string;
|
|
});
|
|
}
|
|
|
|
/*--------------------------------------------------------------------------*/
|
|
|
|
/** Define the public API */
|
|
punycode = {
|
|
/**
|
|
* A string representing the current Punycode.js version number.
|
|
* @memberOf punycode
|
|
* @type String
|
|
*/
|
|
'version': '1.4.1',
|
|
/**
|
|
* An object of methods to convert from JavaScript's internal character
|
|
* representation (UCS-2) to Unicode code points, and back.
|
|
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
|
* @memberOf punycode
|
|
* @type Object
|
|
*/
|
|
'ucs2': {
|
|
'decode': ucs2decode,
|
|
'encode': ucs2encode
|
|
},
|
|
'decode': decode,
|
|
'encode': encode,
|
|
'toASCII': toASCII,
|
|
'toUnicode': toUnicode
|
|
};
|
|
|
|
/** Expose `punycode` */
|
|
// Some AMD build optimizers, like r.js, check for specific condition patterns
|
|
// like the following:
|
|
if (
|
|
true
|
|
) {
|
|
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
|
|
return punycode;
|
|
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
|
|
} else if (freeExports && freeModule) {
|
|
if (module.exports == freeExports) {
|
|
// in Node.js, io.js, or RingoJS v0.8.0+
|
|
freeModule.exports = punycode;
|
|
} else {
|
|
// in Narwhal or RingoJS v0.7.0-
|
|
for (key in punycode) {
|
|
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
|
|
}
|
|
}
|
|
} else {
|
|
// in Rhino or a web browser
|
|
root.punycode = punycode;
|
|
}
|
|
|
|
}(this));
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(161)(module), (function() { return this; }())))
|
|
|
|
/***/ }),
|
|
/* 161 */
|
|
/***/ (function(module, exports) {
|
|
|
|
module.exports = function(module) {
|
|
if(!module.webpackPolyfill) {
|
|
module.deprecate = function() {};
|
|
module.paths = [];
|
|
// module.parent = undefined by default
|
|
module.children = [];
|
|
module.webpackPolyfill = 1;
|
|
}
|
|
return module;
|
|
}
|
|
|
|
|
|
/***/ }),
|
|
/* 162 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var stringify = __webpack_require__(163);
|
|
var parse = __webpack_require__(190);
|
|
var formats = __webpack_require__(189);
|
|
|
|
module.exports = {
|
|
formats: formats,
|
|
parse: parse,
|
|
stringify: stringify
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 163 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var getSideChannel = __webpack_require__(164);
|
|
var utils = __webpack_require__(188);
|
|
var formats = __webpack_require__(189);
|
|
var has = Object.prototype.hasOwnProperty;
|
|
|
|
var arrayPrefixGenerators = {
|
|
brackets: function brackets(prefix) {
|
|
return prefix + '[]';
|
|
},
|
|
comma: 'comma',
|
|
indices: function indices(prefix, key) {
|
|
return prefix + '[' + key + ']';
|
|
},
|
|
repeat: function repeat(prefix) {
|
|
return prefix;
|
|
}
|
|
};
|
|
|
|
var isArray = Array.isArray;
|
|
var push = Array.prototype.push;
|
|
var pushToArray = function (arr, valueOrArray) {
|
|
push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
|
|
};
|
|
|
|
var toISO = Date.prototype.toISOString;
|
|
|
|
var defaultFormat = formats['default'];
|
|
var defaults = {
|
|
addQueryPrefix: false,
|
|
allowDots: false,
|
|
allowEmptyArrays: false,
|
|
arrayFormat: 'indices',
|
|
charset: 'utf-8',
|
|
charsetSentinel: false,
|
|
delimiter: '&',
|
|
encode: true,
|
|
encodeDotInKeys: false,
|
|
encoder: utils.encode,
|
|
encodeValuesOnly: false,
|
|
format: defaultFormat,
|
|
formatter: formats.formatters[defaultFormat],
|
|
// deprecated
|
|
indices: false,
|
|
serializeDate: function serializeDate(date) {
|
|
return toISO.call(date);
|
|
},
|
|
skipNulls: false,
|
|
strictNullHandling: false
|
|
};
|
|
|
|
var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
|
|
return typeof v === 'string'
|
|
|| typeof v === 'number'
|
|
|| typeof v === 'boolean'
|
|
|| typeof v === 'symbol'
|
|
|| typeof v === 'bigint';
|
|
};
|
|
|
|
var sentinel = {};
|
|
|
|
var stringify = function stringify(
|
|
object,
|
|
prefix,
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
allowEmptyArrays,
|
|
strictNullHandling,
|
|
skipNulls,
|
|
encodeDotInKeys,
|
|
encoder,
|
|
filter,
|
|
sort,
|
|
allowDots,
|
|
serializeDate,
|
|
format,
|
|
formatter,
|
|
encodeValuesOnly,
|
|
charset,
|
|
sideChannel
|
|
) {
|
|
var obj = object;
|
|
|
|
var tmpSc = sideChannel;
|
|
var step = 0;
|
|
var findFlag = false;
|
|
while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
|
|
// Where object last appeared in the ref tree
|
|
var pos = tmpSc.get(object);
|
|
step += 1;
|
|
if (typeof pos !== 'undefined') {
|
|
if (pos === step) {
|
|
throw new RangeError('Cyclic object value');
|
|
} else {
|
|
findFlag = true; // Break while
|
|
}
|
|
}
|
|
if (typeof tmpSc.get(sentinel) === 'undefined') {
|
|
step = 0;
|
|
}
|
|
}
|
|
|
|
if (typeof filter === 'function') {
|
|
obj = filter(prefix, obj);
|
|
} else if (obj instanceof Date) {
|
|
obj = serializeDate(obj);
|
|
} else if (generateArrayPrefix === 'comma' && isArray(obj)) {
|
|
obj = utils.maybeMap(obj, function (value) {
|
|
if (value instanceof Date) {
|
|
return serializeDate(value);
|
|
}
|
|
return value;
|
|
});
|
|
}
|
|
|
|
if (obj === null) {
|
|
if (strictNullHandling) {
|
|
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
|
|
}
|
|
|
|
obj = '';
|
|
}
|
|
|
|
if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
|
|
if (encoder) {
|
|
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
|
|
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
|
|
}
|
|
return [formatter(prefix) + '=' + formatter(String(obj))];
|
|
}
|
|
|
|
var values = [];
|
|
|
|
if (typeof obj === 'undefined') {
|
|
return values;
|
|
}
|
|
|
|
var objKeys;
|
|
if (generateArrayPrefix === 'comma' && isArray(obj)) {
|
|
// we need to join elements in
|
|
if (encodeValuesOnly && encoder) {
|
|
obj = utils.maybeMap(obj, encoder);
|
|
}
|
|
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
|
|
} else if (isArray(filter)) {
|
|
objKeys = filter;
|
|
} else {
|
|
var keys = Object.keys(obj);
|
|
objKeys = sort ? keys.sort(sort) : keys;
|
|
}
|
|
|
|
var encodedPrefix = encodeDotInKeys ? prefix.replace(/\./g, '%2E') : prefix;
|
|
|
|
var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix;
|
|
|
|
if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
|
|
return adjustedPrefix + '[]';
|
|
}
|
|
|
|
for (var j = 0; j < objKeys.length; ++j) {
|
|
var key = objKeys[j];
|
|
var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];
|
|
|
|
if (skipNulls && value === null) {
|
|
continue;
|
|
}
|
|
|
|
var encodedKey = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key;
|
|
var keyPrefix = isArray(obj)
|
|
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix
|
|
: adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']');
|
|
|
|
sideChannel.set(object, step);
|
|
var valueSideChannel = getSideChannel();
|
|
valueSideChannel.set(sentinel, sideChannel);
|
|
pushToArray(values, stringify(
|
|
value,
|
|
keyPrefix,
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
allowEmptyArrays,
|
|
strictNullHandling,
|
|
skipNulls,
|
|
encodeDotInKeys,
|
|
generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
|
|
filter,
|
|
sort,
|
|
allowDots,
|
|
serializeDate,
|
|
format,
|
|
formatter,
|
|
encodeValuesOnly,
|
|
charset,
|
|
valueSideChannel
|
|
));
|
|
}
|
|
|
|
return values;
|
|
};
|
|
|
|
var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
|
|
if (!opts) {
|
|
return defaults;
|
|
}
|
|
|
|
if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
|
|
throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
|
|
}
|
|
|
|
if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {
|
|
throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');
|
|
}
|
|
|
|
if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
|
|
throw new TypeError('Encoder has to be a function.');
|
|
}
|
|
|
|
var charset = opts.charset || defaults.charset;
|
|
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
|
|
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
|
|
}
|
|
|
|
var format = formats['default'];
|
|
if (typeof opts.format !== 'undefined') {
|
|
if (!has.call(formats.formatters, opts.format)) {
|
|
throw new TypeError('Unknown format option provided.');
|
|
}
|
|
format = opts.format;
|
|
}
|
|
var formatter = formats.formatters[format];
|
|
|
|
var filter = defaults.filter;
|
|
if (typeof opts.filter === 'function' || isArray(opts.filter)) {
|
|
filter = opts.filter;
|
|
}
|
|
|
|
var arrayFormat;
|
|
if (opts.arrayFormat in arrayPrefixGenerators) {
|
|
arrayFormat = opts.arrayFormat;
|
|
} else if ('indices' in opts) {
|
|
arrayFormat = opts.indices ? 'indices' : 'repeat';
|
|
} else {
|
|
arrayFormat = defaults.arrayFormat;
|
|
}
|
|
|
|
if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
|
|
throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
|
|
}
|
|
|
|
var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
|
|
|
|
return {
|
|
addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
|
|
allowDots: allowDots,
|
|
allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
|
|
arrayFormat: arrayFormat,
|
|
charset: charset,
|
|
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
|
|
commaRoundTrip: opts.commaRoundTrip,
|
|
delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
|
|
encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
|
|
encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
|
|
encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
|
|
encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
|
|
filter: filter,
|
|
format: format,
|
|
formatter: formatter,
|
|
serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
|
|
skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
|
|
sort: typeof opts.sort === 'function' ? opts.sort : null,
|
|
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
|
|
};
|
|
};
|
|
|
|
module.exports = function (object, opts) {
|
|
var obj = object;
|
|
var options = normalizeStringifyOptions(opts);
|
|
|
|
var objKeys;
|
|
var filter;
|
|
|
|
if (typeof options.filter === 'function') {
|
|
filter = options.filter;
|
|
obj = filter('', obj);
|
|
} else if (isArray(options.filter)) {
|
|
filter = options.filter;
|
|
objKeys = filter;
|
|
}
|
|
|
|
var keys = [];
|
|
|
|
if (typeof obj !== 'object' || obj === null) {
|
|
return '';
|
|
}
|
|
|
|
var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
|
|
var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;
|
|
|
|
if (!objKeys) {
|
|
objKeys = Object.keys(obj);
|
|
}
|
|
|
|
if (options.sort) {
|
|
objKeys.sort(options.sort);
|
|
}
|
|
|
|
var sideChannel = getSideChannel();
|
|
for (var i = 0; i < objKeys.length; ++i) {
|
|
var key = objKeys[i];
|
|
|
|
if (options.skipNulls && obj[key] === null) {
|
|
continue;
|
|
}
|
|
pushToArray(keys, stringify(
|
|
obj[key],
|
|
key,
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
options.allowEmptyArrays,
|
|
options.strictNullHandling,
|
|
options.skipNulls,
|
|
options.encodeDotInKeys,
|
|
options.encode ? options.encoder : null,
|
|
options.filter,
|
|
options.sort,
|
|
options.allowDots,
|
|
options.serializeDate,
|
|
options.format,
|
|
options.formatter,
|
|
options.encodeValuesOnly,
|
|
options.charset,
|
|
sideChannel
|
|
));
|
|
}
|
|
|
|
var joined = keys.join(options.delimiter);
|
|
var prefix = options.addQueryPrefix === true ? '?' : '';
|
|
|
|
if (options.charsetSentinel) {
|
|
if (options.charset === 'iso-8859-1') {
|
|
// encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
|
|
prefix += 'utf8=%26%2310003%3B&';
|
|
} else {
|
|
// encodeURIComponent('✓')
|
|
prefix += 'utf8=%E2%9C%93&';
|
|
}
|
|
}
|
|
|
|
return joined.length > 0 ? prefix + joined : '';
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 164 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
var callBound = __webpack_require__(179);
|
|
var inspect = __webpack_require__(186);
|
|
|
|
var $TypeError = __webpack_require__(171);
|
|
var $WeakMap = GetIntrinsic('%WeakMap%', true);
|
|
var $Map = GetIntrinsic('%Map%', true);
|
|
|
|
var $weakMapGet = callBound('WeakMap.prototype.get', true);
|
|
var $weakMapSet = callBound('WeakMap.prototype.set', true);
|
|
var $weakMapHas = callBound('WeakMap.prototype.has', true);
|
|
var $mapGet = callBound('Map.prototype.get', true);
|
|
var $mapSet = callBound('Map.prototype.set', true);
|
|
var $mapHas = callBound('Map.prototype.has', true);
|
|
|
|
/*
|
|
* This function traverses the list returning the node corresponding to the given key.
|
|
*
|
|
* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly.
|
|
*/
|
|
/** @type {import('.').listGetNode} */
|
|
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
|
|
/** @type {typeof list | NonNullable<(typeof list)['next']>} */
|
|
var prev = list;
|
|
/** @type {(typeof list)['next']} */
|
|
var curr;
|
|
for (; (curr = prev.next) !== null; prev = curr) {
|
|
if (curr.key === key) {
|
|
prev.next = curr.next;
|
|
// eslint-disable-next-line no-extra-parens
|
|
curr.next = /** @type {NonNullable<typeof list.next>} */ (list.next);
|
|
list.next = curr; // eslint-disable-line no-param-reassign
|
|
return curr;
|
|
}
|
|
}
|
|
};
|
|
|
|
/** @type {import('.').listGet} */
|
|
var listGet = function (objects, key) {
|
|
var node = listGetNode(objects, key);
|
|
return node && node.value;
|
|
};
|
|
/** @type {import('.').listSet} */
|
|
var listSet = function (objects, key, value) {
|
|
var node = listGetNode(objects, key);
|
|
if (node) {
|
|
node.value = value;
|
|
} else {
|
|
// Prepend the new node to the beginning of the list
|
|
objects.next = /** @type {import('.').ListNode<typeof value>} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens
|
|
key: key,
|
|
next: objects.next,
|
|
value: value
|
|
});
|
|
}
|
|
};
|
|
/** @type {import('.').listHas} */
|
|
var listHas = function (objects, key) {
|
|
return !!listGetNode(objects, key);
|
|
};
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = function getSideChannel() {
|
|
/** @type {WeakMap<object, unknown>} */ var $wm;
|
|
/** @type {Map<object, unknown>} */ var $m;
|
|
/** @type {import('.').RootNode<unknown>} */ var $o;
|
|
|
|
/** @type {import('.').Channel} */
|
|
var channel = {
|
|
assert: function (key) {
|
|
if (!channel.has(key)) {
|
|
throw new $TypeError('Side channel does not contain ' + inspect(key));
|
|
}
|
|
},
|
|
get: function (key) { // eslint-disable-line consistent-return
|
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
|
if ($wm) {
|
|
return $weakMapGet($wm, key);
|
|
}
|
|
} else if ($Map) {
|
|
if ($m) {
|
|
return $mapGet($m, key);
|
|
}
|
|
} else {
|
|
if ($o) { // eslint-disable-line no-lonely-if
|
|
return listGet($o, key);
|
|
}
|
|
}
|
|
},
|
|
has: function (key) {
|
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
|
if ($wm) {
|
|
return $weakMapHas($wm, key);
|
|
}
|
|
} else if ($Map) {
|
|
if ($m) {
|
|
return $mapHas($m, key);
|
|
}
|
|
} else {
|
|
if ($o) { // eslint-disable-line no-lonely-if
|
|
return listHas($o, key);
|
|
}
|
|
}
|
|
return false;
|
|
},
|
|
set: function (key, value) {
|
|
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
|
|
if (!$wm) {
|
|
$wm = new $WeakMap();
|
|
}
|
|
$weakMapSet($wm, key, value);
|
|
} else if ($Map) {
|
|
if (!$m) {
|
|
$m = new $Map();
|
|
}
|
|
$mapSet($m, key, value);
|
|
} else {
|
|
if (!$o) {
|
|
// Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head
|
|
$o = { key: {}, next: null };
|
|
}
|
|
listSet($o, key, value);
|
|
}
|
|
}
|
|
};
|
|
return channel;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 165 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var undefined;
|
|
|
|
var $Error = __webpack_require__(166);
|
|
var $EvalError = __webpack_require__(167);
|
|
var $RangeError = __webpack_require__(168);
|
|
var $ReferenceError = __webpack_require__(169);
|
|
var $SyntaxError = __webpack_require__(170);
|
|
var $TypeError = __webpack_require__(171);
|
|
var $URIError = __webpack_require__(172);
|
|
|
|
var $Function = Function;
|
|
|
|
// eslint-disable-next-line consistent-return
|
|
var getEvalledConstructor = function (expressionSyntax) {
|
|
try {
|
|
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
|
|
} catch (e) {}
|
|
};
|
|
|
|
var $gOPD = Object.getOwnPropertyDescriptor;
|
|
if ($gOPD) {
|
|
try {
|
|
$gOPD({}, '');
|
|
} catch (e) {
|
|
$gOPD = null; // this is IE 8, which has a broken gOPD
|
|
}
|
|
}
|
|
|
|
var throwTypeError = function () {
|
|
throw new $TypeError();
|
|
};
|
|
var ThrowTypeError = $gOPD
|
|
? (function () {
|
|
try {
|
|
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
|
|
arguments.callee; // IE 8 does not throw here
|
|
return throwTypeError;
|
|
} catch (calleeThrows) {
|
|
try {
|
|
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
|
|
return $gOPD(arguments, 'callee').get;
|
|
} catch (gOPDthrows) {
|
|
return throwTypeError;
|
|
}
|
|
}
|
|
}())
|
|
: throwTypeError;
|
|
|
|
var hasSymbols = __webpack_require__(173)();
|
|
var hasProto = __webpack_require__(175)();
|
|
|
|
var getProto = Object.getPrototypeOf || (
|
|
hasProto
|
|
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
|
|
: null
|
|
);
|
|
|
|
var needsEval = {};
|
|
|
|
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
|
|
|
|
var INTRINSICS = {
|
|
__proto__: null,
|
|
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
|
|
'%Array%': Array,
|
|
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
|
|
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
|
|
'%AsyncFromSyncIteratorPrototype%': undefined,
|
|
'%AsyncFunction%': needsEval,
|
|
'%AsyncGenerator%': needsEval,
|
|
'%AsyncGeneratorFunction%': needsEval,
|
|
'%AsyncIteratorPrototype%': needsEval,
|
|
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
|
|
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
|
|
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
|
|
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
|
|
'%Boolean%': Boolean,
|
|
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
|
|
'%Date%': Date,
|
|
'%decodeURI%': decodeURI,
|
|
'%decodeURIComponent%': decodeURIComponent,
|
|
'%encodeURI%': encodeURI,
|
|
'%encodeURIComponent%': encodeURIComponent,
|
|
'%Error%': $Error,
|
|
'%eval%': eval, // eslint-disable-line no-eval
|
|
'%EvalError%': $EvalError,
|
|
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
|
|
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
|
|
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
|
|
'%Function%': $Function,
|
|
'%GeneratorFunction%': needsEval,
|
|
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
|
|
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
|
|
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
|
|
'%isFinite%': isFinite,
|
|
'%isNaN%': isNaN,
|
|
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
|
|
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
|
|
'%Map%': typeof Map === 'undefined' ? undefined : Map,
|
|
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
|
|
'%Math%': Math,
|
|
'%Number%': Number,
|
|
'%Object%': Object,
|
|
'%parseFloat%': parseFloat,
|
|
'%parseInt%': parseInt,
|
|
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
|
|
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
|
|
'%RangeError%': $RangeError,
|
|
'%ReferenceError%': $ReferenceError,
|
|
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
|
|
'%RegExp%': RegExp,
|
|
'%Set%': typeof Set === 'undefined' ? undefined : Set,
|
|
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
|
|
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
|
|
'%String%': String,
|
|
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
|
|
'%Symbol%': hasSymbols ? Symbol : undefined,
|
|
'%SyntaxError%': $SyntaxError,
|
|
'%ThrowTypeError%': ThrowTypeError,
|
|
'%TypedArray%': TypedArray,
|
|
'%TypeError%': $TypeError,
|
|
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
|
|
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
|
|
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
|
|
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
|
|
'%URIError%': $URIError,
|
|
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
|
|
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
|
|
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
|
|
};
|
|
|
|
if (getProto) {
|
|
try {
|
|
null.error; // eslint-disable-line no-unused-expressions
|
|
} catch (e) {
|
|
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
|
|
var errorProto = getProto(getProto(e));
|
|
INTRINSICS['%Error.prototype%'] = errorProto;
|
|
}
|
|
}
|
|
|
|
var doEval = function doEval(name) {
|
|
var value;
|
|
if (name === '%AsyncFunction%') {
|
|
value = getEvalledConstructor('async function () {}');
|
|
} else if (name === '%GeneratorFunction%') {
|
|
value = getEvalledConstructor('function* () {}');
|
|
} else if (name === '%AsyncGeneratorFunction%') {
|
|
value = getEvalledConstructor('async function* () {}');
|
|
} else if (name === '%AsyncGenerator%') {
|
|
var fn = doEval('%AsyncGeneratorFunction%');
|
|
if (fn) {
|
|
value = fn.prototype;
|
|
}
|
|
} else if (name === '%AsyncIteratorPrototype%') {
|
|
var gen = doEval('%AsyncGenerator%');
|
|
if (gen && getProto) {
|
|
value = getProto(gen.prototype);
|
|
}
|
|
}
|
|
|
|
INTRINSICS[name] = value;
|
|
|
|
return value;
|
|
};
|
|
|
|
var LEGACY_ALIASES = {
|
|
__proto__: null,
|
|
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
|
|
'%ArrayPrototype%': ['Array', 'prototype'],
|
|
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
|
|
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
|
|
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
|
|
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
|
|
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
|
|
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
|
|
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
|
|
'%BooleanPrototype%': ['Boolean', 'prototype'],
|
|
'%DataViewPrototype%': ['DataView', 'prototype'],
|
|
'%DatePrototype%': ['Date', 'prototype'],
|
|
'%ErrorPrototype%': ['Error', 'prototype'],
|
|
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
|
|
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
|
|
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
|
|
'%FunctionPrototype%': ['Function', 'prototype'],
|
|
'%Generator%': ['GeneratorFunction', 'prototype'],
|
|
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
|
|
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
|
|
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
|
|
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
|
|
'%JSONParse%': ['JSON', 'parse'],
|
|
'%JSONStringify%': ['JSON', 'stringify'],
|
|
'%MapPrototype%': ['Map', 'prototype'],
|
|
'%NumberPrototype%': ['Number', 'prototype'],
|
|
'%ObjectPrototype%': ['Object', 'prototype'],
|
|
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
|
|
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
|
|
'%PromisePrototype%': ['Promise', 'prototype'],
|
|
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
|
|
'%Promise_all%': ['Promise', 'all'],
|
|
'%Promise_reject%': ['Promise', 'reject'],
|
|
'%Promise_resolve%': ['Promise', 'resolve'],
|
|
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
|
|
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
|
|
'%RegExpPrototype%': ['RegExp', 'prototype'],
|
|
'%SetPrototype%': ['Set', 'prototype'],
|
|
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
|
|
'%StringPrototype%': ['String', 'prototype'],
|
|
'%SymbolPrototype%': ['Symbol', 'prototype'],
|
|
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
|
|
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
|
|
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
|
|
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
|
|
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
|
|
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
|
|
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
|
|
'%URIErrorPrototype%': ['URIError', 'prototype'],
|
|
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
|
|
'%WeakSetPrototype%': ['WeakSet', 'prototype']
|
|
};
|
|
|
|
var bind = __webpack_require__(176);
|
|
var hasOwn = __webpack_require__(178);
|
|
var $concat = bind.call(Function.call, Array.prototype.concat);
|
|
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
|
|
var $replace = bind.call(Function.call, String.prototype.replace);
|
|
var $strSlice = bind.call(Function.call, String.prototype.slice);
|
|
var $exec = bind.call(Function.call, RegExp.prototype.exec);
|
|
|
|
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
|
|
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
|
|
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
|
|
var stringToPath = function stringToPath(string) {
|
|
var first = $strSlice(string, 0, 1);
|
|
var last = $strSlice(string, -1);
|
|
if (first === '%' && last !== '%') {
|
|
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
|
|
} else if (last === '%' && first !== '%') {
|
|
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
|
|
}
|
|
var result = [];
|
|
$replace(string, rePropName, function (match, number, quote, subString) {
|
|
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
|
|
});
|
|
return result;
|
|
};
|
|
/* end adaptation */
|
|
|
|
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
|
|
var intrinsicName = name;
|
|
var alias;
|
|
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
|
|
alias = LEGACY_ALIASES[intrinsicName];
|
|
intrinsicName = '%' + alias[0] + '%';
|
|
}
|
|
|
|
if (hasOwn(INTRINSICS, intrinsicName)) {
|
|
var value = INTRINSICS[intrinsicName];
|
|
if (value === needsEval) {
|
|
value = doEval(intrinsicName);
|
|
}
|
|
if (typeof value === 'undefined' && !allowMissing) {
|
|
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
|
|
}
|
|
|
|
return {
|
|
alias: alias,
|
|
name: intrinsicName,
|
|
value: value
|
|
};
|
|
}
|
|
|
|
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
|
|
};
|
|
|
|
module.exports = function GetIntrinsic(name, allowMissing) {
|
|
if (typeof name !== 'string' || name.length === 0) {
|
|
throw new $TypeError('intrinsic name must be a non-empty string');
|
|
}
|
|
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
|
|
throw new $TypeError('"allowMissing" argument must be a boolean');
|
|
}
|
|
|
|
if ($exec(/^%?[^%]*%?$/, name) === null) {
|
|
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
|
|
}
|
|
var parts = stringToPath(name);
|
|
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
|
|
|
|
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
|
|
var intrinsicRealName = intrinsic.name;
|
|
var value = intrinsic.value;
|
|
var skipFurtherCaching = false;
|
|
|
|
var alias = intrinsic.alias;
|
|
if (alias) {
|
|
intrinsicBaseName = alias[0];
|
|
$spliceApply(parts, $concat([0, 1], alias));
|
|
}
|
|
|
|
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
|
|
var part = parts[i];
|
|
var first = $strSlice(part, 0, 1);
|
|
var last = $strSlice(part, -1);
|
|
if (
|
|
(
|
|
(first === '"' || first === "'" || first === '`')
|
|
|| (last === '"' || last === "'" || last === '`')
|
|
)
|
|
&& first !== last
|
|
) {
|
|
throw new $SyntaxError('property names with quotes must have matching quotes');
|
|
}
|
|
if (part === 'constructor' || !isOwn) {
|
|
skipFurtherCaching = true;
|
|
}
|
|
|
|
intrinsicBaseName += '.' + part;
|
|
intrinsicRealName = '%' + intrinsicBaseName + '%';
|
|
|
|
if (hasOwn(INTRINSICS, intrinsicRealName)) {
|
|
value = INTRINSICS[intrinsicRealName];
|
|
} else if (value != null) {
|
|
if (!(part in value)) {
|
|
if (!allowMissing) {
|
|
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
|
|
}
|
|
return void undefined;
|
|
}
|
|
if ($gOPD && (i + 1) >= parts.length) {
|
|
var desc = $gOPD(value, part);
|
|
isOwn = !!desc;
|
|
|
|
// By convention, when a data property is converted to an accessor
|
|
// property to emulate a data property that does not suffer from
|
|
// the override mistake, that accessor's getter is marked with
|
|
// an `originalValue` property. Here, when we detect this, we
|
|
// uphold the illusion by pretending to see that original data
|
|
// property, i.e., returning the value rather than the getter
|
|
// itself.
|
|
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
|
|
value = desc.get;
|
|
} else {
|
|
value = value[part];
|
|
}
|
|
} else {
|
|
isOwn = hasOwn(value, part);
|
|
value = value[part];
|
|
}
|
|
|
|
if (isOwn && !skipFurtherCaching) {
|
|
INTRINSICS[intrinsicRealName] = value;
|
|
}
|
|
}
|
|
}
|
|
return value;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 166 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = Error;
|
|
|
|
|
|
/***/ }),
|
|
/* 167 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./eval')} */
|
|
module.exports = EvalError;
|
|
|
|
|
|
/***/ }),
|
|
/* 168 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./range')} */
|
|
module.exports = RangeError;
|
|
|
|
|
|
/***/ }),
|
|
/* 169 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./ref')} */
|
|
module.exports = ReferenceError;
|
|
|
|
|
|
/***/ }),
|
|
/* 170 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./syntax')} */
|
|
module.exports = SyntaxError;
|
|
|
|
|
|
/***/ }),
|
|
/* 171 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./type')} */
|
|
module.exports = TypeError;
|
|
|
|
|
|
/***/ }),
|
|
/* 172 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/** @type {import('./uri')} */
|
|
module.exports = URIError;
|
|
|
|
|
|
/***/ }),
|
|
/* 173 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
|
|
var hasSymbolSham = __webpack_require__(174);
|
|
|
|
module.exports = function hasNativeSymbols() {
|
|
if (typeof origSymbol !== 'function') { return false; }
|
|
if (typeof Symbol !== 'function') { return false; }
|
|
if (typeof origSymbol('foo') !== 'symbol') { return false; }
|
|
if (typeof Symbol('bar') !== 'symbol') { return false; }
|
|
|
|
return hasSymbolSham();
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 174 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/* eslint complexity: [2, 18], max-statements: [2, 33] */
|
|
module.exports = function hasSymbols() {
|
|
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
|
|
if (typeof Symbol.iterator === 'symbol') { return true; }
|
|
|
|
var obj = {};
|
|
var sym = Symbol('test');
|
|
var symObj = Object(sym);
|
|
if (typeof sym === 'string') { return false; }
|
|
|
|
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
|
|
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
|
|
|
|
// temp disabled per https://github.com/ljharb/object.assign/issues/17
|
|
// if (sym instanceof Symbol) { return false; }
|
|
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
|
|
// if (!(symObj instanceof Symbol)) { return false; }
|
|
|
|
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
|
|
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
|
|
|
|
var symVal = 42;
|
|
obj[sym] = symVal;
|
|
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
|
|
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
|
|
|
|
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
|
|
|
|
var syms = Object.getOwnPropertySymbols(obj);
|
|
if (syms.length !== 1 || syms[0] !== sym) { return false; }
|
|
|
|
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
|
|
|
|
if (typeof Object.getOwnPropertyDescriptor === 'function') {
|
|
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
|
|
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 175 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
var test = {
|
|
__proto__: null,
|
|
foo: {}
|
|
};
|
|
|
|
var $Object = Object;
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = function hasProto() {
|
|
// @ts-expect-error: TS errors on an inherited property for some reason
|
|
return { __proto__: test }.foo === test.foo
|
|
&& !(test instanceof $Object);
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 176 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var implementation = __webpack_require__(177);
|
|
|
|
module.exports = Function.prototype.bind || implementation;
|
|
|
|
|
|
/***/ }),
|
|
/* 177 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
/* eslint no-invalid-this: 1 */
|
|
|
|
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
|
|
var toStr = Object.prototype.toString;
|
|
var max = Math.max;
|
|
var funcType = '[object Function]';
|
|
|
|
var concatty = function concatty(a, b) {
|
|
var arr = [];
|
|
|
|
for (var i = 0; i < a.length; i += 1) {
|
|
arr[i] = a[i];
|
|
}
|
|
for (var j = 0; j < b.length; j += 1) {
|
|
arr[j + a.length] = b[j];
|
|
}
|
|
|
|
return arr;
|
|
};
|
|
|
|
var slicy = function slicy(arrLike, offset) {
|
|
var arr = [];
|
|
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
|
|
arr[j] = arrLike[i];
|
|
}
|
|
return arr;
|
|
};
|
|
|
|
var joiny = function (arr, joiner) {
|
|
var str = '';
|
|
for (var i = 0; i < arr.length; i += 1) {
|
|
str += arr[i];
|
|
if (i + 1 < arr.length) {
|
|
str += joiner;
|
|
}
|
|
}
|
|
return str;
|
|
};
|
|
|
|
module.exports = function bind(that) {
|
|
var target = this;
|
|
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
|
|
throw new TypeError(ERROR_MESSAGE + target);
|
|
}
|
|
var args = slicy(arguments, 1);
|
|
|
|
var bound;
|
|
var binder = function () {
|
|
if (this instanceof bound) {
|
|
var result = target.apply(
|
|
this,
|
|
concatty(args, arguments)
|
|
);
|
|
if (Object(result) === result) {
|
|
return result;
|
|
}
|
|
return this;
|
|
}
|
|
return target.apply(
|
|
that,
|
|
concatty(args, arguments)
|
|
);
|
|
|
|
};
|
|
|
|
var boundLength = max(0, target.length - args.length);
|
|
var boundArgs = [];
|
|
for (var i = 0; i < boundLength; i++) {
|
|
boundArgs[i] = '$' + i;
|
|
}
|
|
|
|
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
|
|
|
|
if (target.prototype) {
|
|
var Empty = function Empty() {};
|
|
Empty.prototype = target.prototype;
|
|
bound.prototype = new Empty();
|
|
Empty.prototype = null;
|
|
}
|
|
|
|
return bound;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 178 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var call = Function.prototype.call;
|
|
var $hasOwn = Object.prototype.hasOwnProperty;
|
|
var bind = __webpack_require__(176);
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = bind.call(call, $hasOwn);
|
|
|
|
|
|
/***/ }),
|
|
/* 179 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
|
|
var callBind = __webpack_require__(180);
|
|
|
|
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
|
|
|
|
module.exports = function callBoundIntrinsic(name, allowMissing) {
|
|
var intrinsic = GetIntrinsic(name, !!allowMissing);
|
|
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
|
|
return callBind(intrinsic);
|
|
}
|
|
return intrinsic;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 180 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var bind = __webpack_require__(176);
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
var setFunctionLength = __webpack_require__(181);
|
|
|
|
var $TypeError = __webpack_require__(171);
|
|
var $apply = GetIntrinsic('%Function.prototype.apply%');
|
|
var $call = GetIntrinsic('%Function.prototype.call%');
|
|
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
|
|
|
|
var $defineProperty = __webpack_require__(183);
|
|
var $max = GetIntrinsic('%Math.max%');
|
|
|
|
module.exports = function callBind(originalFunction) {
|
|
if (typeof originalFunction !== 'function') {
|
|
throw new $TypeError('a function is required');
|
|
}
|
|
var func = $reflectApply(bind, $call, arguments);
|
|
return setFunctionLength(
|
|
func,
|
|
1 + $max(0, originalFunction.length - (arguments.length - 1)),
|
|
true
|
|
);
|
|
};
|
|
|
|
var applyBind = function applyBind() {
|
|
return $reflectApply(bind, $apply, arguments);
|
|
};
|
|
|
|
if ($defineProperty) {
|
|
$defineProperty(module.exports, 'apply', { value: applyBind });
|
|
} else {
|
|
module.exports.apply = applyBind;
|
|
}
|
|
|
|
|
|
/***/ }),
|
|
/* 181 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
var define = __webpack_require__(182);
|
|
var hasDescriptors = __webpack_require__(185)();
|
|
var gOPD = __webpack_require__(184);
|
|
|
|
var $TypeError = __webpack_require__(171);
|
|
var $floor = GetIntrinsic('%Math.floor%');
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = function setFunctionLength(fn, length) {
|
|
if (typeof fn !== 'function') {
|
|
throw new $TypeError('`fn` is not a function');
|
|
}
|
|
if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
|
|
throw new $TypeError('`length` must be a positive 32-bit integer');
|
|
}
|
|
|
|
var loose = arguments.length > 2 && !!arguments[2];
|
|
|
|
var functionLengthIsConfigurable = true;
|
|
var functionLengthIsWritable = true;
|
|
if ('length' in fn && gOPD) {
|
|
var desc = gOPD(fn, 'length');
|
|
if (desc && !desc.configurable) {
|
|
functionLengthIsConfigurable = false;
|
|
}
|
|
if (desc && !desc.writable) {
|
|
functionLengthIsWritable = false;
|
|
}
|
|
}
|
|
|
|
if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
|
|
if (hasDescriptors) {
|
|
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
|
|
} else {
|
|
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
|
|
}
|
|
}
|
|
return fn;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 182 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var $defineProperty = __webpack_require__(183);
|
|
|
|
var $SyntaxError = __webpack_require__(170);
|
|
var $TypeError = __webpack_require__(171);
|
|
|
|
var gopd = __webpack_require__(184);
|
|
|
|
/** @type {import('.')} */
|
|
module.exports = function defineDataProperty(
|
|
obj,
|
|
property,
|
|
value
|
|
) {
|
|
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
|
|
throw new $TypeError('`obj` must be an object or a function`');
|
|
}
|
|
if (typeof property !== 'string' && typeof property !== 'symbol') {
|
|
throw new $TypeError('`property` must be a string or a symbol`');
|
|
}
|
|
if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
|
|
throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
|
|
}
|
|
if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
|
|
throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
|
|
}
|
|
if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
|
|
throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
|
|
}
|
|
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
|
|
throw new $TypeError('`loose`, if provided, must be a boolean');
|
|
}
|
|
|
|
var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
|
|
var nonWritable = arguments.length > 4 ? arguments[4] : null;
|
|
var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
|
|
var loose = arguments.length > 6 ? arguments[6] : false;
|
|
|
|
/* @type {false | TypedPropertyDescriptor<unknown>} */
|
|
var desc = !!gopd && gopd(obj, property);
|
|
|
|
if ($defineProperty) {
|
|
$defineProperty(obj, property, {
|
|
configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
|
|
enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
|
|
value: value,
|
|
writable: nonWritable === null && desc ? desc.writable : !nonWritable
|
|
});
|
|
} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
|
|
// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
|
|
obj[property] = value; // eslint-disable-line no-param-reassign
|
|
} else {
|
|
throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
|
|
}
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 183 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
|
|
/** @type {import('.')} */
|
|
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false;
|
|
if ($defineProperty) {
|
|
try {
|
|
$defineProperty({}, 'a', { value: 1 });
|
|
} catch (e) {
|
|
// IE 8 has a broken defineProperty
|
|
$defineProperty = false;
|
|
}
|
|
}
|
|
|
|
module.exports = $defineProperty;
|
|
|
|
|
|
/***/ }),
|
|
/* 184 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var GetIntrinsic = __webpack_require__(165);
|
|
|
|
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
|
|
|
|
if ($gOPD) {
|
|
try {
|
|
$gOPD([], 'length');
|
|
} catch (e) {
|
|
// IE 8 has a broken gOPD
|
|
$gOPD = null;
|
|
}
|
|
}
|
|
|
|
module.exports = $gOPD;
|
|
|
|
|
|
/***/ }),
|
|
/* 185 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var $defineProperty = __webpack_require__(183);
|
|
|
|
var hasPropertyDescriptors = function hasPropertyDescriptors() {
|
|
return !!$defineProperty;
|
|
};
|
|
|
|
hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
|
|
// node v0.6 has a bug where array lengths can be Set but not Defined
|
|
if (!$defineProperty) {
|
|
return null;
|
|
}
|
|
try {
|
|
return $defineProperty([], 'length', { value: 1 }).length !== 1;
|
|
} catch (e) {
|
|
// In Firefox 4-22, defining length on an array throws an exception.
|
|
return true;
|
|
}
|
|
};
|
|
|
|
module.exports = hasPropertyDescriptors;
|
|
|
|
|
|
/***/ }),
|
|
/* 186 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/* WEBPACK VAR INJECTION */(function(global) {var hasMap = typeof Map === 'function' && Map.prototype;
|
|
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
|
|
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
|
|
var mapForEach = hasMap && Map.prototype.forEach;
|
|
var hasSet = typeof Set === 'function' && Set.prototype;
|
|
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
|
|
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
|
|
var setForEach = hasSet && Set.prototype.forEach;
|
|
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
|
|
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
|
|
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
|
|
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
|
|
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
|
|
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
|
|
var booleanValueOf = Boolean.prototype.valueOf;
|
|
var objectToString = Object.prototype.toString;
|
|
var functionToString = Function.prototype.toString;
|
|
var $match = String.prototype.match;
|
|
var $slice = String.prototype.slice;
|
|
var $replace = String.prototype.replace;
|
|
var $toUpperCase = String.prototype.toUpperCase;
|
|
var $toLowerCase = String.prototype.toLowerCase;
|
|
var $test = RegExp.prototype.test;
|
|
var $concat = Array.prototype.concat;
|
|
var $join = Array.prototype.join;
|
|
var $arrSlice = Array.prototype.slice;
|
|
var $floor = Math.floor;
|
|
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
|
|
var gOPS = Object.getOwnPropertySymbols;
|
|
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
|
|
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
|
|
// ie, `has-tostringtag/shams
|
|
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
|
|
? Symbol.toStringTag
|
|
: null;
|
|
var isEnumerable = Object.prototype.propertyIsEnumerable;
|
|
|
|
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
|
|
[].__proto__ === Array.prototype // eslint-disable-line no-proto
|
|
? function (O) {
|
|
return O.__proto__; // eslint-disable-line no-proto
|
|
}
|
|
: null
|
|
);
|
|
|
|
function addNumericSeparator(num, str) {
|
|
if (
|
|
num === Infinity
|
|
|| num === -Infinity
|
|
|| num !== num
|
|
|| (num && num > -1000 && num < 1000)
|
|
|| $test.call(/e/, str)
|
|
) {
|
|
return str;
|
|
}
|
|
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
|
|
if (typeof num === 'number') {
|
|
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
|
|
if (int !== num) {
|
|
var intStr = String(int);
|
|
var dec = $slice.call(str, intStr.length + 1);
|
|
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
|
|
}
|
|
}
|
|
return $replace.call(str, sepRegex, '$&_');
|
|
}
|
|
|
|
var utilInspect = __webpack_require__(187);
|
|
var inspectCustom = utilInspect.custom;
|
|
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
|
|
|
|
module.exports = function inspect_(obj, options, depth, seen) {
|
|
var opts = options || {};
|
|
|
|
if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
|
|
throw new TypeError('option "quoteStyle" must be "single" or "double"');
|
|
}
|
|
if (
|
|
has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
|
|
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
|
|
: opts.maxStringLength !== null
|
|
)
|
|
) {
|
|
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
|
|
}
|
|
var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
|
|
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
|
|
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
|
|
}
|
|
|
|
if (
|
|
has(opts, 'indent')
|
|
&& opts.indent !== null
|
|
&& opts.indent !== '\t'
|
|
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
|
|
) {
|
|
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
|
|
}
|
|
if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
|
|
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
|
|
}
|
|
var numericSeparator = opts.numericSeparator;
|
|
|
|
if (typeof obj === 'undefined') {
|
|
return 'undefined';
|
|
}
|
|
if (obj === null) {
|
|
return 'null';
|
|
}
|
|
if (typeof obj === 'boolean') {
|
|
return obj ? 'true' : 'false';
|
|
}
|
|
|
|
if (typeof obj === 'string') {
|
|
return inspectString(obj, opts);
|
|
}
|
|
if (typeof obj === 'number') {
|
|
if (obj === 0) {
|
|
return Infinity / obj > 0 ? '0' : '-0';
|
|
}
|
|
var str = String(obj);
|
|
return numericSeparator ? addNumericSeparator(obj, str) : str;
|
|
}
|
|
if (typeof obj === 'bigint') {
|
|
var bigIntStr = String(obj) + 'n';
|
|
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
|
|
}
|
|
|
|
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
|
|
if (typeof depth === 'undefined') { depth = 0; }
|
|
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
|
|
return isArray(obj) ? '[Array]' : '[Object]';
|
|
}
|
|
|
|
var indent = getIndent(opts, depth);
|
|
|
|
if (typeof seen === 'undefined') {
|
|
seen = [];
|
|
} else if (indexOf(seen, obj) >= 0) {
|
|
return '[Circular]';
|
|
}
|
|
|
|
function inspect(value, from, noIndent) {
|
|
if (from) {
|
|
seen = $arrSlice.call(seen);
|
|
seen.push(from);
|
|
}
|
|
if (noIndent) {
|
|
var newOpts = {
|
|
depth: opts.depth
|
|
};
|
|
if (has(opts, 'quoteStyle')) {
|
|
newOpts.quoteStyle = opts.quoteStyle;
|
|
}
|
|
return inspect_(value, newOpts, depth + 1, seen);
|
|
}
|
|
return inspect_(value, opts, depth + 1, seen);
|
|
}
|
|
|
|
if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
|
|
var name = nameOf(obj);
|
|
var keys = arrObjKeys(obj, inspect);
|
|
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
|
|
}
|
|
if (isSymbol(obj)) {
|
|
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
|
|
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
|
|
}
|
|
if (isElement(obj)) {
|
|
var s = '<' + $toLowerCase.call(String(obj.nodeName));
|
|
var attrs = obj.attributes || [];
|
|
for (var i = 0; i < attrs.length; i++) {
|
|
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
|
|
}
|
|
s += '>';
|
|
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
|
|
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
|
|
return s;
|
|
}
|
|
if (isArray(obj)) {
|
|
if (obj.length === 0) { return '[]'; }
|
|
var xs = arrObjKeys(obj, inspect);
|
|
if (indent && !singleLineValues(xs)) {
|
|
return '[' + indentedJoin(xs, indent) + ']';
|
|
}
|
|
return '[ ' + $join.call(xs, ', ') + ' ]';
|
|
}
|
|
if (isError(obj)) {
|
|
var parts = arrObjKeys(obj, inspect);
|
|
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
|
|
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
|
|
}
|
|
if (parts.length === 0) { return '[' + String(obj) + ']'; }
|
|
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
|
|
}
|
|
if (typeof obj === 'object' && customInspect) {
|
|
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
|
|
return utilInspect(obj, { depth: maxDepth - depth });
|
|
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
|
|
return obj.inspect();
|
|
}
|
|
}
|
|
if (isMap(obj)) {
|
|
var mapParts = [];
|
|
if (mapForEach) {
|
|
mapForEach.call(obj, function (value, key) {
|
|
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
|
|
});
|
|
}
|
|
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
|
|
}
|
|
if (isSet(obj)) {
|
|
var setParts = [];
|
|
if (setForEach) {
|
|
setForEach.call(obj, function (value) {
|
|
setParts.push(inspect(value, obj));
|
|
});
|
|
}
|
|
return collectionOf('Set', setSize.call(obj), setParts, indent);
|
|
}
|
|
if (isWeakMap(obj)) {
|
|
return weakCollectionOf('WeakMap');
|
|
}
|
|
if (isWeakSet(obj)) {
|
|
return weakCollectionOf('WeakSet');
|
|
}
|
|
if (isWeakRef(obj)) {
|
|
return weakCollectionOf('WeakRef');
|
|
}
|
|
if (isNumber(obj)) {
|
|
return markBoxed(inspect(Number(obj)));
|
|
}
|
|
if (isBigInt(obj)) {
|
|
return markBoxed(inspect(bigIntValueOf.call(obj)));
|
|
}
|
|
if (isBoolean(obj)) {
|
|
return markBoxed(booleanValueOf.call(obj));
|
|
}
|
|
if (isString(obj)) {
|
|
return markBoxed(inspect(String(obj)));
|
|
}
|
|
// note: in IE 8, sometimes `global !== window` but both are the prototypes of each other
|
|
/* eslint-env browser */
|
|
if (typeof window !== 'undefined' && obj === window) {
|
|
return '{ [object Window] }';
|
|
}
|
|
if (
|
|
(typeof globalThis !== 'undefined' && obj === globalThis)
|
|
|| (typeof global !== 'undefined' && obj === global)
|
|
) {
|
|
return '{ [object globalThis] }';
|
|
}
|
|
if (!isDate(obj) && !isRegExp(obj)) {
|
|
var ys = arrObjKeys(obj, inspect);
|
|
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
|
|
var protoTag = obj instanceof Object ? '' : 'null prototype';
|
|
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
|
|
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
|
|
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
|
|
if (ys.length === 0) { return tag + '{}'; }
|
|
if (indent) {
|
|
return tag + '{' + indentedJoin(ys, indent) + '}';
|
|
}
|
|
return tag + '{ ' + $join.call(ys, ', ') + ' }';
|
|
}
|
|
return String(obj);
|
|
};
|
|
|
|
function wrapQuotes(s, defaultStyle, opts) {
|
|
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
|
|
return quoteChar + s + quoteChar;
|
|
}
|
|
|
|
function quote(s) {
|
|
return $replace.call(String(s), /"/g, '"');
|
|
}
|
|
|
|
function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
|
|
|
|
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
|
|
function isSymbol(obj) {
|
|
if (hasShammedSymbols) {
|
|
return obj && typeof obj === 'object' && obj instanceof Symbol;
|
|
}
|
|
if (typeof obj === 'symbol') {
|
|
return true;
|
|
}
|
|
if (!obj || typeof obj !== 'object' || !symToString) {
|
|
return false;
|
|
}
|
|
try {
|
|
symToString.call(obj);
|
|
return true;
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isBigInt(obj) {
|
|
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
|
|
return false;
|
|
}
|
|
try {
|
|
bigIntValueOf.call(obj);
|
|
return true;
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
|
|
function has(obj, key) {
|
|
return hasOwn.call(obj, key);
|
|
}
|
|
|
|
function toStr(obj) {
|
|
return objectToString.call(obj);
|
|
}
|
|
|
|
function nameOf(f) {
|
|
if (f.name) { return f.name; }
|
|
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
|
|
if (m) { return m[1]; }
|
|
return null;
|
|
}
|
|
|
|
function indexOf(xs, x) {
|
|
if (xs.indexOf) { return xs.indexOf(x); }
|
|
for (var i = 0, l = xs.length; i < l; i++) {
|
|
if (xs[i] === x) { return i; }
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
function isMap(x) {
|
|
if (!mapSize || !x || typeof x !== 'object') {
|
|
return false;
|
|
}
|
|
try {
|
|
mapSize.call(x);
|
|
try {
|
|
setSize.call(x);
|
|
} catch (s) {
|
|
return true;
|
|
}
|
|
return x instanceof Map; // core-js workaround, pre-v2.5.0
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isWeakMap(x) {
|
|
if (!weakMapHas || !x || typeof x !== 'object') {
|
|
return false;
|
|
}
|
|
try {
|
|
weakMapHas.call(x, weakMapHas);
|
|
try {
|
|
weakSetHas.call(x, weakSetHas);
|
|
} catch (s) {
|
|
return true;
|
|
}
|
|
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isWeakRef(x) {
|
|
if (!weakRefDeref || !x || typeof x !== 'object') {
|
|
return false;
|
|
}
|
|
try {
|
|
weakRefDeref.call(x);
|
|
return true;
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isSet(x) {
|
|
if (!setSize || !x || typeof x !== 'object') {
|
|
return false;
|
|
}
|
|
try {
|
|
setSize.call(x);
|
|
try {
|
|
mapSize.call(x);
|
|
} catch (m) {
|
|
return true;
|
|
}
|
|
return x instanceof Set; // core-js workaround, pre-v2.5.0
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isWeakSet(x) {
|
|
if (!weakSetHas || !x || typeof x !== 'object') {
|
|
return false;
|
|
}
|
|
try {
|
|
weakSetHas.call(x, weakSetHas);
|
|
try {
|
|
weakMapHas.call(x, weakMapHas);
|
|
} catch (s) {
|
|
return true;
|
|
}
|
|
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
|
|
} catch (e) {}
|
|
return false;
|
|
}
|
|
|
|
function isElement(x) {
|
|
if (!x || typeof x !== 'object') { return false; }
|
|
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
|
|
return true;
|
|
}
|
|
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
|
|
}
|
|
|
|
function inspectString(str, opts) {
|
|
if (str.length > opts.maxStringLength) {
|
|
var remaining = str.length - opts.maxStringLength;
|
|
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
|
|
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
|
|
}
|
|
// eslint-disable-next-line no-control-regex
|
|
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
|
|
return wrapQuotes(s, 'single', opts);
|
|
}
|
|
|
|
function lowbyte(c) {
|
|
var n = c.charCodeAt(0);
|
|
var x = {
|
|
8: 'b',
|
|
9: 't',
|
|
10: 'n',
|
|
12: 'f',
|
|
13: 'r'
|
|
}[n];
|
|
if (x) { return '\\' + x; }
|
|
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
|
|
}
|
|
|
|
function markBoxed(str) {
|
|
return 'Object(' + str + ')';
|
|
}
|
|
|
|
function weakCollectionOf(type) {
|
|
return type + ' { ? }';
|
|
}
|
|
|
|
function collectionOf(type, size, entries, indent) {
|
|
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
|
|
return type + ' (' + size + ') {' + joinedEntries + '}';
|
|
}
|
|
|
|
function singleLineValues(xs) {
|
|
for (var i = 0; i < xs.length; i++) {
|
|
if (indexOf(xs[i], '\n') >= 0) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function getIndent(opts, depth) {
|
|
var baseIndent;
|
|
if (opts.indent === '\t') {
|
|
baseIndent = '\t';
|
|
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
|
|
baseIndent = $join.call(Array(opts.indent + 1), ' ');
|
|
} else {
|
|
return null;
|
|
}
|
|
return {
|
|
base: baseIndent,
|
|
prev: $join.call(Array(depth + 1), baseIndent)
|
|
};
|
|
}
|
|
|
|
function indentedJoin(xs, indent) {
|
|
if (xs.length === 0) { return ''; }
|
|
var lineJoiner = '\n' + indent.prev + indent.base;
|
|
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
|
|
}
|
|
|
|
function arrObjKeys(obj, inspect) {
|
|
var isArr = isArray(obj);
|
|
var xs = [];
|
|
if (isArr) {
|
|
xs.length = obj.length;
|
|
for (var i = 0; i < obj.length; i++) {
|
|
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
|
|
}
|
|
}
|
|
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
|
|
var symMap;
|
|
if (hasShammedSymbols) {
|
|
symMap = {};
|
|
for (var k = 0; k < syms.length; k++) {
|
|
symMap['$' + syms[k]] = syms[k];
|
|
}
|
|
}
|
|
|
|
for (var key in obj) { // eslint-disable-line no-restricted-syntax
|
|
if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
|
|
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
|
|
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
|
|
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
|
|
continue; // eslint-disable-line no-restricted-syntax, no-continue
|
|
} else if ($test.call(/[^\w$]/, key)) {
|
|
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
|
|
} else {
|
|
xs.push(key + ': ' + inspect(obj[key], obj));
|
|
}
|
|
}
|
|
if (typeof gOPS === 'function') {
|
|
for (var j = 0; j < syms.length; j++) {
|
|
if (isEnumerable.call(obj, syms[j])) {
|
|
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
|
|
}
|
|
}
|
|
}
|
|
return xs;
|
|
}
|
|
|
|
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
|
|
|
|
/***/ }),
|
|
/* 187 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/* (ignored) */
|
|
|
|
/***/ }),
|
|
/* 188 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var formats = __webpack_require__(189);
|
|
|
|
var has = Object.prototype.hasOwnProperty;
|
|
var isArray = Array.isArray;
|
|
|
|
var hexTable = (function () {
|
|
var array = [];
|
|
for (var i = 0; i < 256; ++i) {
|
|
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
|
|
}
|
|
|
|
return array;
|
|
}());
|
|
|
|
var compactQueue = function compactQueue(queue) {
|
|
while (queue.length > 1) {
|
|
var item = queue.pop();
|
|
var obj = item.obj[item.prop];
|
|
|
|
if (isArray(obj)) {
|
|
var compacted = [];
|
|
|
|
for (var j = 0; j < obj.length; ++j) {
|
|
if (typeof obj[j] !== 'undefined') {
|
|
compacted.push(obj[j]);
|
|
}
|
|
}
|
|
|
|
item.obj[item.prop] = compacted;
|
|
}
|
|
}
|
|
};
|
|
|
|
var arrayToObject = function arrayToObject(source, options) {
|
|
var obj = options && options.plainObjects ? Object.create(null) : {};
|
|
for (var i = 0; i < source.length; ++i) {
|
|
if (typeof source[i] !== 'undefined') {
|
|
obj[i] = source[i];
|
|
}
|
|
}
|
|
|
|
return obj;
|
|
};
|
|
|
|
var merge = function merge(target, source, options) {
|
|
/* eslint no-param-reassign: 0 */
|
|
if (!source) {
|
|
return target;
|
|
}
|
|
|
|
if (typeof source !== 'object') {
|
|
if (isArray(target)) {
|
|
target.push(source);
|
|
} else if (target && typeof target === 'object') {
|
|
if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
|
|
target[source] = true;
|
|
}
|
|
} else {
|
|
return [target, source];
|
|
}
|
|
|
|
return target;
|
|
}
|
|
|
|
if (!target || typeof target !== 'object') {
|
|
return [target].concat(source);
|
|
}
|
|
|
|
var mergeTarget = target;
|
|
if (isArray(target) && !isArray(source)) {
|
|
mergeTarget = arrayToObject(target, options);
|
|
}
|
|
|
|
if (isArray(target) && isArray(source)) {
|
|
source.forEach(function (item, i) {
|
|
if (has.call(target, i)) {
|
|
var targetItem = target[i];
|
|
if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
|
|
target[i] = merge(targetItem, item, options);
|
|
} else {
|
|
target.push(item);
|
|
}
|
|
} else {
|
|
target[i] = item;
|
|
}
|
|
});
|
|
return target;
|
|
}
|
|
|
|
return Object.keys(source).reduce(function (acc, key) {
|
|
var value = source[key];
|
|
|
|
if (has.call(acc, key)) {
|
|
acc[key] = merge(acc[key], value, options);
|
|
} else {
|
|
acc[key] = value;
|
|
}
|
|
return acc;
|
|
}, mergeTarget);
|
|
};
|
|
|
|
var assign = function assignSingleSource(target, source) {
|
|
return Object.keys(source).reduce(function (acc, key) {
|
|
acc[key] = source[key];
|
|
return acc;
|
|
}, target);
|
|
};
|
|
|
|
var decode = function (str, decoder, charset) {
|
|
var strWithoutPlus = str.replace(/\+/g, ' ');
|
|
if (charset === 'iso-8859-1') {
|
|
// unescape never throws, no try...catch needed:
|
|
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
|
|
}
|
|
// utf-8
|
|
try {
|
|
return decodeURIComponent(strWithoutPlus);
|
|
} catch (e) {
|
|
return strWithoutPlus;
|
|
}
|
|
};
|
|
|
|
var limit = 1024;
|
|
|
|
/* eslint operator-linebreak: [2, "before"] */
|
|
|
|
var encode = function encode(str, defaultEncoder, charset, kind, format) {
|
|
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
|
|
// It has been adapted here for stricter adherence to RFC 3986
|
|
if (str.length === 0) {
|
|
return str;
|
|
}
|
|
|
|
var string = str;
|
|
if (typeof str === 'symbol') {
|
|
string = Symbol.prototype.toString.call(str);
|
|
} else if (typeof str !== 'string') {
|
|
string = String(str);
|
|
}
|
|
|
|
if (charset === 'iso-8859-1') {
|
|
return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
|
|
return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
|
|
});
|
|
}
|
|
|
|
var out = '';
|
|
for (var j = 0; j < string.length; j += limit) {
|
|
var segment = string.length >= limit ? string.slice(j, j + limit) : string;
|
|
var arr = [];
|
|
|
|
for (var i = 0; i < segment.length; ++i) {
|
|
var c = segment.charCodeAt(i);
|
|
if (
|
|
c === 0x2D // -
|
|
|| c === 0x2E // .
|
|
|| c === 0x5F // _
|
|
|| c === 0x7E // ~
|
|
|| (c >= 0x30 && c <= 0x39) // 0-9
|
|
|| (c >= 0x41 && c <= 0x5A) // a-z
|
|
|| (c >= 0x61 && c <= 0x7A) // A-Z
|
|
|| (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
|
|
) {
|
|
arr[arr.length] = segment.charAt(i);
|
|
continue;
|
|
}
|
|
|
|
if (c < 0x80) {
|
|
arr[arr.length] = hexTable[c];
|
|
continue;
|
|
}
|
|
|
|
if (c < 0x800) {
|
|
arr[arr.length] = hexTable[0xC0 | (c >> 6)]
|
|
+ hexTable[0x80 | (c & 0x3F)];
|
|
continue;
|
|
}
|
|
|
|
if (c < 0xD800 || c >= 0xE000) {
|
|
arr[arr.length] = hexTable[0xE0 | (c >> 12)]
|
|
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
|
|
+ hexTable[0x80 | (c & 0x3F)];
|
|
continue;
|
|
}
|
|
|
|
i += 1;
|
|
c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF));
|
|
|
|
arr[arr.length] = hexTable[0xF0 | (c >> 18)]
|
|
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
|
|
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
|
|
+ hexTable[0x80 | (c & 0x3F)];
|
|
}
|
|
|
|
out += arr.join('');
|
|
}
|
|
|
|
return out;
|
|
};
|
|
|
|
var compact = function compact(value) {
|
|
var queue = [{ obj: { o: value }, prop: 'o' }];
|
|
var refs = [];
|
|
|
|
for (var i = 0; i < queue.length; ++i) {
|
|
var item = queue[i];
|
|
var obj = item.obj[item.prop];
|
|
|
|
var keys = Object.keys(obj);
|
|
for (var j = 0; j < keys.length; ++j) {
|
|
var key = keys[j];
|
|
var val = obj[key];
|
|
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
|
|
queue.push({ obj: obj, prop: key });
|
|
refs.push(val);
|
|
}
|
|
}
|
|
}
|
|
|
|
compactQueue(queue);
|
|
|
|
return value;
|
|
};
|
|
|
|
var isRegExp = function isRegExp(obj) {
|
|
return Object.prototype.toString.call(obj) === '[object RegExp]';
|
|
};
|
|
|
|
var isBuffer = function isBuffer(obj) {
|
|
if (!obj || typeof obj !== 'object') {
|
|
return false;
|
|
}
|
|
|
|
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
|
|
};
|
|
|
|
var combine = function combine(a, b) {
|
|
return [].concat(a, b);
|
|
};
|
|
|
|
var maybeMap = function maybeMap(val, fn) {
|
|
if (isArray(val)) {
|
|
var mapped = [];
|
|
for (var i = 0; i < val.length; i += 1) {
|
|
mapped.push(fn(val[i]));
|
|
}
|
|
return mapped;
|
|
}
|
|
return fn(val);
|
|
};
|
|
|
|
module.exports = {
|
|
arrayToObject: arrayToObject,
|
|
assign: assign,
|
|
combine: combine,
|
|
compact: compact,
|
|
decode: decode,
|
|
encode: encode,
|
|
isBuffer: isBuffer,
|
|
isRegExp: isRegExp,
|
|
maybeMap: maybeMap,
|
|
merge: merge
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 189 */
|
|
/***/ (function(module, exports) {
|
|
|
|
'use strict';
|
|
|
|
var replace = String.prototype.replace;
|
|
var percentTwenties = /%20/g;
|
|
|
|
var Format = {
|
|
RFC1738: 'RFC1738',
|
|
RFC3986: 'RFC3986'
|
|
};
|
|
|
|
module.exports = {
|
|
'default': Format.RFC3986,
|
|
formatters: {
|
|
RFC1738: function (value) {
|
|
return replace.call(value, percentTwenties, '+');
|
|
},
|
|
RFC3986: function (value) {
|
|
return String(value);
|
|
}
|
|
},
|
|
RFC1738: Format.RFC1738,
|
|
RFC3986: Format.RFC3986
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 190 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
'use strict';
|
|
|
|
var utils = __webpack_require__(188);
|
|
|
|
var has = Object.prototype.hasOwnProperty;
|
|
var isArray = Array.isArray;
|
|
|
|
var defaults = {
|
|
allowDots: false,
|
|
allowEmptyArrays: false,
|
|
allowPrototypes: false,
|
|
allowSparse: false,
|
|
arrayLimit: 20,
|
|
charset: 'utf-8',
|
|
charsetSentinel: false,
|
|
comma: false,
|
|
decodeDotInKeys: false,
|
|
decoder: utils.decode,
|
|
delimiter: '&',
|
|
depth: 5,
|
|
duplicates: 'combine',
|
|
ignoreQueryPrefix: false,
|
|
interpretNumericEntities: false,
|
|
parameterLimit: 1000,
|
|
parseArrays: true,
|
|
plainObjects: false,
|
|
strictDepth: false,
|
|
strictNullHandling: false
|
|
};
|
|
|
|
var interpretNumericEntities = function (str) {
|
|
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
|
|
return String.fromCharCode(parseInt(numberStr, 10));
|
|
});
|
|
};
|
|
|
|
var parseArrayValue = function (val, options) {
|
|
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
|
|
return val.split(',');
|
|
}
|
|
|
|
return val;
|
|
};
|
|
|
|
// This is what browsers will submit when the ✓ character occurs in an
|
|
// application/x-www-form-urlencoded body and the encoding of the page containing
|
|
// the form is iso-8859-1, or when the submitted form has an accept-charset
|
|
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
|
|
// the ✓ character, such as us-ascii.
|
|
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
|
|
|
|
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
|
|
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
|
|
|
|
var parseValues = function parseQueryStringValues(str, options) {
|
|
var obj = { __proto__: null };
|
|
|
|
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
|
|
cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']');
|
|
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
|
|
var parts = cleanStr.split(options.delimiter, limit);
|
|
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
|
|
var i;
|
|
|
|
var charset = options.charset;
|
|
if (options.charsetSentinel) {
|
|
for (i = 0; i < parts.length; ++i) {
|
|
if (parts[i].indexOf('utf8=') === 0) {
|
|
if (parts[i] === charsetSentinel) {
|
|
charset = 'utf-8';
|
|
} else if (parts[i] === isoSentinel) {
|
|
charset = 'iso-8859-1';
|
|
}
|
|
skipIndex = i;
|
|
i = parts.length; // The eslint settings do not allow break;
|
|
}
|
|
}
|
|
}
|
|
|
|
for (i = 0; i < parts.length; ++i) {
|
|
if (i === skipIndex) {
|
|
continue;
|
|
}
|
|
var part = parts[i];
|
|
|
|
var bracketEqualsPos = part.indexOf(']=');
|
|
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
|
|
|
|
var key, val;
|
|
if (pos === -1) {
|
|
key = options.decoder(part, defaults.decoder, charset, 'key');
|
|
val = options.strictNullHandling ? null : '';
|
|
} else {
|
|
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
|
|
val = utils.maybeMap(
|
|
parseArrayValue(part.slice(pos + 1), options),
|
|
function (encodedVal) {
|
|
return options.decoder(encodedVal, defaults.decoder, charset, 'value');
|
|
}
|
|
);
|
|
}
|
|
|
|
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
|
|
val = interpretNumericEntities(val);
|
|
}
|
|
|
|
if (part.indexOf('[]=') > -1) {
|
|
val = isArray(val) ? [val] : val;
|
|
}
|
|
|
|
var existing = has.call(obj, key);
|
|
if (existing && options.duplicates === 'combine') {
|
|
obj[key] = utils.combine(obj[key], val);
|
|
} else if (!existing || options.duplicates === 'last') {
|
|
obj[key] = val;
|
|
}
|
|
}
|
|
|
|
return obj;
|
|
};
|
|
|
|
var parseObject = function (chain, val, options, valuesParsed) {
|
|
var leaf = valuesParsed ? val : parseArrayValue(val, options);
|
|
|
|
for (var i = chain.length - 1; i >= 0; --i) {
|
|
var obj;
|
|
var root = chain[i];
|
|
|
|
if (root === '[]' && options.parseArrays) {
|
|
obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null))
|
|
? []
|
|
: [].concat(leaf);
|
|
} else {
|
|
obj = options.plainObjects ? Object.create(null) : {};
|
|
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
|
|
var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot;
|
|
var index = parseInt(decodedRoot, 10);
|
|
if (!options.parseArrays && decodedRoot === '') {
|
|
obj = { 0: leaf };
|
|
} else if (
|
|
!isNaN(index)
|
|
&& root !== decodedRoot
|
|
&& String(index) === decodedRoot
|
|
&& index >= 0
|
|
&& (options.parseArrays && index <= options.arrayLimit)
|
|
) {
|
|
obj = [];
|
|
obj[index] = leaf;
|
|
} else if (decodedRoot !== '__proto__') {
|
|
obj[decodedRoot] = leaf;
|
|
}
|
|
}
|
|
|
|
leaf = obj;
|
|
}
|
|
|
|
return leaf;
|
|
};
|
|
|
|
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
|
|
if (!givenKey) {
|
|
return;
|
|
}
|
|
|
|
// Transform dot notation to bracket notation
|
|
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
|
|
|
|
// The regex chunks
|
|
|
|
var brackets = /(\[[^[\]]*])/;
|
|
var child = /(\[[^[\]]*])/g;
|
|
|
|
// Get the parent
|
|
|
|
var segment = options.depth > 0 && brackets.exec(key);
|
|
var parent = segment ? key.slice(0, segment.index) : key;
|
|
|
|
// Stash the parent if it exists
|
|
|
|
var keys = [];
|
|
if (parent) {
|
|
// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
|
|
if (!options.plainObjects && has.call(Object.prototype, parent)) {
|
|
if (!options.allowPrototypes) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
keys.push(parent);
|
|
}
|
|
|
|
// Loop through children appending to the array until we hit depth
|
|
|
|
var i = 0;
|
|
while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
|
|
i += 1;
|
|
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
|
|
if (!options.allowPrototypes) {
|
|
return;
|
|
}
|
|
}
|
|
keys.push(segment[1]);
|
|
}
|
|
|
|
// If there's a remainder, check strictDepth option for throw, else just add whatever is left
|
|
|
|
if (segment) {
|
|
if (options.strictDepth === true) {
|
|
throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true');
|
|
}
|
|
keys.push('[' + key.slice(segment.index) + ']');
|
|
}
|
|
|
|
return parseObject(keys, val, options, valuesParsed);
|
|
};
|
|
|
|
var normalizeParseOptions = function normalizeParseOptions(opts) {
|
|
if (!opts) {
|
|
return defaults;
|
|
}
|
|
|
|
if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
|
|
throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
|
|
}
|
|
|
|
if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') {
|
|
throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided');
|
|
}
|
|
|
|
if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') {
|
|
throw new TypeError('Decoder has to be a function.');
|
|
}
|
|
|
|
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
|
|
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
|
|
}
|
|
var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
|
|
|
|
var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates;
|
|
|
|
if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') {
|
|
throw new TypeError('The duplicates option must be either combine, first, or last');
|
|
}
|
|
|
|
var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
|
|
|
|
return {
|
|
allowDots: allowDots,
|
|
allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
|
|
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
|
|
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
|
|
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
|
|
charset: charset,
|
|
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
|
|
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
|
|
decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys,
|
|
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
|
|
delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
|
|
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
|
|
depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
|
|
duplicates: duplicates,
|
|
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
|
|
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
|
|
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
|
|
parseArrays: opts.parseArrays !== false,
|
|
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
|
|
strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth,
|
|
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
|
|
};
|
|
};
|
|
|
|
module.exports = function (str, opts) {
|
|
var options = normalizeParseOptions(opts);
|
|
|
|
if (str === '' || str === null || typeof str === 'undefined') {
|
|
return options.plainObjects ? Object.create(null) : {};
|
|
}
|
|
|
|
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
|
|
var obj = options.plainObjects ? Object.create(null) : {};
|
|
|
|
// Iterate over the keys and setup the new object
|
|
|
|
var keys = Object.keys(tempObj);
|
|
for (var i = 0; i < keys.length; ++i) {
|
|
var key = keys[i];
|
|
var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
|
|
obj = utils.merge(obj, newObj, options);
|
|
}
|
|
|
|
if (options.allowSparse === true) {
|
|
return obj;
|
|
}
|
|
|
|
return utils.compact(obj);
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 191 */
|
|
/***/ (function(module, exports) {
|
|
|
|
"use strict";
|
|
exports.P5_VERSION = '1.10.0';
|
|
exports.PREVIEW_WIDTH = 150;
|
|
exports.HEIGHT = 300;
|
|
exports.MAX_RUN_TIME = 1000;
|
|
|
|
|
|
/***/ }),
|
|
/* 192 */
|
|
/***/ (function(module, exports) {
|
|
|
|
"use strict";
|
|
var SessionStorageAutosaver = (function () {
|
|
function SessionStorageAutosaver(id) {
|
|
this.id = id;
|
|
}
|
|
SessionStorageAutosaver.prototype.save = function (value) {
|
|
try {
|
|
window.sessionStorage[this.id] = value;
|
|
}
|
|
catch (e) {
|
|
// It's likely that we ran out of storage space or are in
|
|
// private browsing mode or something. Regardless, autosave is
|
|
// a parachute, so it's regrettable but ultimately not
|
|
// catastrophic for us to fail here.
|
|
console.log("Autosave for " + this.id + " failed", e);
|
|
}
|
|
};
|
|
SessionStorageAutosaver.prototype.restore = function () {
|
|
return window.sessionStorage[this.id];
|
|
};
|
|
return SessionStorageAutosaver;
|
|
}());
|
|
exports.SessionStorageAutosaver = SessionStorageAutosaver;
|
|
|
|
|
|
/***/ }),
|
|
/* 193 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var __extends = (this && this.__extends) || function (d, b) {
|
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
|
function __() { this.constructor = d; }
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
var __assign = (this && this.__assign) || Object.assign || function(t) {
|
|
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
s = arguments[i];
|
|
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
t[p] = s[p];
|
|
}
|
|
return t;
|
|
};
|
|
var React = __webpack_require__(1);
|
|
var pure_component_1 = __webpack_require__(194);
|
|
var toolbar_1 = __webpack_require__(198);
|
|
var editor_1 = __webpack_require__(199);
|
|
var preview_1 = __webpack_require__(202);
|
|
var ErrorMessage = function (props) { return (React.createElement("div", {className: "error-message"}, React.createElement("span", {className: "error-message-line"}, "Line ", props.line, ":"), " " + props.message)); };
|
|
var App = (function (_super) {
|
|
__extends(App, _super);
|
|
function App(props) {
|
|
var _this = this;
|
|
_super.call(this, props);
|
|
this.handleEditorChange = function (newValue, canUndo, canRedo) {
|
|
_this.setState({
|
|
editorContent: newValue,
|
|
canUndo: canUndo,
|
|
canRedo: canRedo
|
|
});
|
|
_this.props.autosaver.save(newValue);
|
|
};
|
|
this.handlePreviewError = function (message, line) {
|
|
_this.setState({
|
|
lastError: {
|
|
message: message,
|
|
line: line
|
|
}
|
|
});
|
|
};
|
|
this.handleRevertClick = function () {
|
|
_this.setState({
|
|
isPlaying: false,
|
|
editorContent: _this.props.initialContent
|
|
});
|
|
};
|
|
this.handlePlayClick = function () {
|
|
_this.setState(function (prevState, props) { return ({
|
|
isPlaying: true,
|
|
previewContent: prevState.editorContent,
|
|
startPlayTimestamp: Date.now(),
|
|
lastError: null
|
|
}); });
|
|
};
|
|
this.handleStopClick = function () {
|
|
_this.setState({ isPlaying: false });
|
|
window.parent.postMessage({
|
|
from: 'p5.widget',
|
|
status: 'stop'
|
|
}, '*');
|
|
};
|
|
this.handleUndoClick = function () {
|
|
_this.refs.editor.undo();
|
|
};
|
|
this.handleRedoClick = function () {
|
|
_this.refs.editor.redo();
|
|
};
|
|
this.state = {
|
|
canUndo: false,
|
|
canRedo: false,
|
|
previewContent: this.props.initialContent,
|
|
editorContent: this.props.initialContent,
|
|
progress: 1
|
|
};
|
|
}
|
|
App.prototype.componentDidMount = function () {
|
|
var _this = this;
|
|
var autosave = this.props.autosaver && this.props.autosaver.restore();
|
|
if (autosave && autosave !== this.state.editorContent) {
|
|
this.setState({ editorContent: autosave });
|
|
}
|
|
else if (this.props.autoplay) {
|
|
this.handlePlayClick();
|
|
}
|
|
window.addEventListener('message', function (event) {
|
|
var data = event.data;
|
|
if (data.from === 'p5.widget' && data.status === 'capture'
|
|
&& data.frameCount != undefined
|
|
&& data.maxCount != undefined && data.maxCount > 0) {
|
|
_this.setState({
|
|
progress: (data.frameCount / data.maxCount).toFixed(2)
|
|
});
|
|
}
|
|
});
|
|
};
|
|
App.prototype.render = function () {
|
|
var errorLine = null;
|
|
var canRevert = (this.state.editorContent !== this.props.initialContent);
|
|
if (this.state.lastError &&
|
|
this.state.editorContent === this.state.previewContent) {
|
|
errorLine = this.state.lastError.line;
|
|
}
|
|
return (React.createElement("div", {className: "app"}, React.createElement(toolbar_1.default, {progress: this.state.progress, onPlayClick: this.handlePlayClick, onStopClick: this.state.isPlaying && this.handleStopClick, onUndoClick: this.state.canUndo && this.handleUndoClick, onRedoClick: this.state.canRedo && this.handleRedoClick, onRevertClick: canRevert && this.handleRevertClick}), React.createElement("div", {className: "panes"}, React.createElement(editor_1.default, {ref: "editor", content: this.state.editorContent, errorLine: errorLine, onChange: this.handleEditorChange}), React.createElement("div", {className: "preview-holder-wrapper"}, this.state.isPlaying
|
|
? React.createElement(preview_1.default, {content: this.state.previewContent, baseSketchURL: this.props.baseSketchURL, p5version: this.props.p5version, maxRunTime: this.props.maxRunTime, width: this.props.previewWidth, timestamp: this.state.startPlayTimestamp, onError: this.handlePreviewError})
|
|
: null)), React.createElement("div", {className: "status-bar"}, this.state.lastError
|
|
? React.createElement(ErrorMessage, __assign({}, this.state.lastError))
|
|
: null)));
|
|
};
|
|
return App;
|
|
}(pure_component_1.default));
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = App;
|
|
|
|
|
|
/***/ }),
|
|
/* 194 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var __extends = (this && this.__extends) || function (d, b) {
|
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
|
function __() { this.constructor = d; }
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
var React = __webpack_require__(1);
|
|
var PureRenderMixin = __webpack_require__(195);
|
|
var PureComponent = (function (_super) {
|
|
__extends(PureComponent, _super);
|
|
function PureComponent() {
|
|
_super.apply(this, arguments);
|
|
}
|
|
PureComponent.prototype.shouldComponentUpdate = function () {
|
|
return PureRenderMixin.shouldComponentUpdate.apply(this, arguments);
|
|
};
|
|
return PureComponent;
|
|
}(React.Component));
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = PureComponent;
|
|
|
|
|
|
/***/ }),
|
|
/* 195 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
module.exports = __webpack_require__(196);
|
|
|
|
/***/ }),
|
|
/* 196 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule ReactComponentWithPureRenderMixin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var shallowCompare = __webpack_require__(197);
|
|
|
|
/**
|
|
* If your React component's render function is "pure", e.g. it will render the
|
|
* same result given the same props and state, provide this Mixin for a
|
|
* considerable performance boost.
|
|
*
|
|
* Most React components have pure render functions.
|
|
*
|
|
* Example:
|
|
*
|
|
* var ReactComponentWithPureRenderMixin =
|
|
* require('ReactComponentWithPureRenderMixin');
|
|
* React.createClass({
|
|
* mixins: [ReactComponentWithPureRenderMixin],
|
|
*
|
|
* render: function() {
|
|
* return <div className={this.props.className}>foo</div>;
|
|
* }
|
|
* });
|
|
*
|
|
* Note: This only checks shallow equality for props and state. If these contain
|
|
* complex data structures this mixin may have false-negatives for deeper
|
|
* differences. Only mixin to components which have simple props and state, or
|
|
* use `forceUpdate()` when you know deep data structures have changed.
|
|
*/
|
|
var ReactComponentWithPureRenderMixin = {
|
|
shouldComponentUpdate: function (nextProps, nextState) {
|
|
return shallowCompare(this, nextProps, nextState);
|
|
}
|
|
};
|
|
|
|
module.exports = ReactComponentWithPureRenderMixin;
|
|
|
|
/***/ }),
|
|
/* 197 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/**
|
|
* Copyright 2013-2015, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule shallowCompare
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var shallowEqual = __webpack_require__(117);
|
|
|
|
/**
|
|
* Does a shallow comparison for props and state.
|
|
* See ReactComponentWithPureRenderMixin
|
|
*/
|
|
function shallowCompare(instance, nextProps, nextState) {
|
|
return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
|
|
}
|
|
|
|
module.exports = shallowCompare;
|
|
|
|
/***/ }),
|
|
/* 198 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var __extends = (this && this.__extends) || function (d, b) {
|
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
|
function __() { this.constructor = d; }
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
var React = __webpack_require__(1);
|
|
var pure_component_1 = __webpack_require__(194);
|
|
// https://useiconic.com/open/
|
|
var OpenIconicMediaPlay = function () { return (React.createElement("svg", {className: "open-iconic media-play", width: "8", height: "8", viewBox: "0 0 8 8"}, React.createElement("path", {d: "M0 0v6l6-3-6-3z", transform: "translate(1 1)"}))); };
|
|
var OpenIconicMediaStop = function () { return (React.createElement("svg", {className: "open-iconic media-stop", width: "8", height: "8", viewBox: "0 0 8 8"}, React.createElement("path", {d: "M0 0v6h6v-6h-6z", transform: "translate(1 1)"}))); };
|
|
var OpenIconicActionUndo = function () { return (React.createElement("svg", {className: "open-iconic action-undo", width: "8", height: "8", viewBox: "0 0 8 8"}, React.createElement("path", {d: "M4.5 0c-1.93 0-3.5 1.57-3.5 3.5v.5h-1l2 2 2-2h-1v-.5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5c0-1.93-1.57-3.5-3.5-3.5z", transform: "translate(0 1)"}))); };
|
|
var OpenIconicActionRedo = function () { return (React.createElement("svg", {className: "open-iconic action-redo", width: "8", height: "8", viewBox: "0 0 8 8"}, React.createElement("path", {d: "M3.5 0c-1.93 0-3.5 1.57-3.5 3.5 0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v.5h-1l2 2 2-2h-1v-.5c0-1.93-1.57-3.5-3.5-3.5z", transform: "translate(0 1)"}))); };
|
|
var Toolbar = (function (_super) {
|
|
__extends(Toolbar, _super);
|
|
function Toolbar() {
|
|
_super.apply(this, arguments);
|
|
}
|
|
Toolbar.prototype.render = function () {
|
|
return (React.createElement("div", {className: "toolbar"}, React.createElement("a", {className: "p5-logo", href: "http://p5js.org/", target: "_blank"}, React.createElement("img", {src: "static/img/p5js-beta.svg", alt: "p5js.org"})), React.createElement("button", {onClick: this.props.onPlayClick}, React.createElement(OpenIconicMediaPlay, null), "Play"), this.props.onStopClick
|
|
? React.createElement("button", {onClick: this.props.onStopClick}, React.createElement(OpenIconicMediaStop, null), "Stop")
|
|
: null, this.props.onUndoClick
|
|
? React.createElement("button", {onClick: this.props.onUndoClick}, React.createElement(OpenIconicActionUndo, null), "Undo")
|
|
: null, this.props.onRedoClick
|
|
? React.createElement("button", {onClick: this.props.onRedoClick}, React.createElement(OpenIconicActionRedo, null), "Redo")
|
|
: null, this.props.onRevertClick
|
|
? React.createElement("button", {onClick: this.props.onRevertClick}, "Revert")
|
|
: null));
|
|
};
|
|
return Toolbar;
|
|
}(pure_component_1.default));
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Toolbar;
|
|
|
|
|
|
/***/ }),
|
|
/* 199 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var __extends = (this && this.__extends) || function (d, b) {
|
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
|
function __() { this.constructor = d; }
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
var React = __webpack_require__(1);
|
|
var CodeMirror = __webpack_require__(200);
|
|
__webpack_require__(201);
|
|
var pure_component_1 = __webpack_require__(194);
|
|
// It seems like CodeMirror behaves oddly with a flexbox layout, so
|
|
// we will manually size it. However, Chrome seems to have a bug
|
|
// whereby we need to wait a bit before resizing it after the
|
|
// component initially mounts (this isn't required for Firefox or MS Edge).
|
|
var INITIAL_RESIZE_DELAY_MS = 100;
|
|
var Editor = (function (_super) {
|
|
__extends(Editor, _super);
|
|
function Editor() {
|
|
var _this = this;
|
|
_super.apply(this, arguments);
|
|
this.resizeEditor = function () {
|
|
var wrapper = _this._cm.getWrapperElement();
|
|
var oldDisplay = wrapper.style.display;
|
|
// We need to get the size of our container when it's
|
|
// "uncorrupted" by the height of our codemirror widget, so
|
|
// temporarily hide the widget.
|
|
wrapper.style.display = 'none';
|
|
var rectHeight = _this.refs.container.getBoundingClientRect().height;
|
|
wrapper.style.display = oldDisplay;
|
|
_this._cm.setSize(null, rectHeight);
|
|
};
|
|
}
|
|
Editor.prototype.componentDidUpdate = function (prevProps) {
|
|
if (this.props.content !== prevProps.content &&
|
|
this.props.content !== this._cm.getValue()) {
|
|
this._cm.setValue(this.props.content);
|
|
}
|
|
if (this.props.errorLine !== prevProps.errorLine) {
|
|
if (this._errorLineHandle) {
|
|
this._cm.removeLineClass(this._errorLineHandle, 'background', 'error-line');
|
|
this._errorLineHandle = null;
|
|
}
|
|
if (this.props.errorLine) {
|
|
this._errorLineHandle = this._cm.addLineClass(this.props.errorLine - 1, 'background', 'error-line');
|
|
}
|
|
}
|
|
};
|
|
Editor.prototype.componentDidMount = function () {
|
|
var _this = this;
|
|
this._cm = CodeMirror(this.refs.container, {
|
|
theme: 'p5-widget',
|
|
value: this.props.content,
|
|
lineNumbers: true,
|
|
mode: 'javascript'
|
|
});
|
|
this._cm.on('change', function () {
|
|
if (_this.props.onChange) {
|
|
var size = _this._cm.getDoc().historySize();
|
|
_this.props.onChange(_this._cm.getValue(), size.undo > 0, size.redo > 0);
|
|
}
|
|
});
|
|
this.resizeEditor();
|
|
this._resizeTimeout = setTimeout(this.resizeEditor, INITIAL_RESIZE_DELAY_MS);
|
|
window.addEventListener('resize', this.resizeEditor, false);
|
|
};
|
|
Editor.prototype.componentWillUnmount = function () {
|
|
// CodeMirror instances have no remove/destroy methods, so we
|
|
// don't need to do anything: http://stackoverflow.com/a/18890324/2422398
|
|
this._cm = null;
|
|
clearTimeout(this._resizeTimeout);
|
|
window.removeEventListener('resize', this.resizeEditor, false);
|
|
};
|
|
Editor.prototype.undo = function () {
|
|
this._cm.getDoc().undo();
|
|
};
|
|
Editor.prototype.redo = function () {
|
|
this._cm.getDoc().redo();
|
|
};
|
|
Editor.prototype.render = function () {
|
|
return React.createElement("div", {ref: "container", className: "editor-holder"});
|
|
};
|
|
return Editor;
|
|
}(pure_component_1.default));
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Editor;
|
|
|
|
|
|
/***/ }),
|
|
/* 200 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
|
|
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
|
|
|
|
// This is CodeMirror (https://codemirror.net/5), 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 = global || self, 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\/(\d+)/.exec(userAgent);
|
|
var chrome_version = chrome && +chrome[1];
|
|
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 = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
|
|
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(rootNode) {
|
|
// 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 doc = rootNode.ownerDocument || rootNode;
|
|
var activeElement;
|
|
try {
|
|
activeElement = rootNode.activeElement;
|
|
} catch(e) {
|
|
activeElement = doc.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 doc(cm) { return cm.display.wrapper.ownerDocument }
|
|
|
|
function root(cm) {
|
|
return rootNode(cm.display.wrapper)
|
|
}
|
|
|
|
function rootNode(element) {
|
|
// Detect modern browsers (2017+).
|
|
return element.getRootNode ? element.getRootNode() : element.ownerDocument
|
|
}
|
|
|
|
function win(cm) { return doc(cm).defaultView }
|
|
|
|
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;
|
|
this.f = null;
|
|
this.time = 0;
|
|
this.handler = bind(this.onTimeout, this);
|
|
};
|
|
Delayed.prototype.onTimeout = function (self) {
|
|
self.id = 0;
|
|
if (self.time <= +new Date) {
|
|
self.f();
|
|
} else {
|
|
setTimeout(self.handler, self.time - +new Date);
|
|
}
|
|
};
|
|
Delayed.prototype.set = function (ms, f) {
|
|
this.f = f;
|
|
var time = +new Date + ms;
|
|
if (!this.id || time < this.time) {
|
|
clearTimeout(this.id);
|
|
this.id = setTimeout(this.handler, ms);
|
|
this.time = time;
|
|
}
|
|
};
|
|
|
|
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 = 50;
|
|
|
|
// 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}, sel_mouse = {origin: "*mouse"}, 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; }
|
|
}
|
|
}
|
|
|
|
// 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, isRTL = direction == "rtl" ? 1 : 0;
|
|
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)); at += isRTL; }
|
|
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));
|
|
at += isRTL;
|
|
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 = emitter._handlers || (emitter._handlers = {});
|
|
map[type] = (map[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 = emitter._handlers, arr = map && map[type];
|
|
if (arr) {
|
|
var index = indexOf(arr, f);
|
|
if (index > -1)
|
|
{ map[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;
|
|
try {range = te.ownerDocument.selection.createRange();}
|
|
catch(e) {}
|
|
if (!range || range.parentElement() != te) { return false }
|
|
return range.compareEndPoints("StartToEnd", range) != 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 = {}, 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 start = this.pos;
|
|
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.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)
|
|
};
|
|
|
|
// 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
|
|
}
|
|
|
|
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) {
|
|
if (!this.baseTokens) { return null }
|
|
while (this.baseTokens[this.baseTokenPos] <= n)
|
|
{ this.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);
|
|
}
|
|
|
|
// Optimize some code when these features are not used.
|
|
var sawReadOnlySpans = false, 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, op) {
|
|
var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
|
|
if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
|
|
line.markedSpans.push(span);
|
|
} else {
|
|
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
|
|
if (inThisOp) { inThisOp.add(line.markedSpans); }
|
|
}
|
|
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) }
|
|
|
|
function collapsedSpanAround(line, ch) {
|
|
var sps = sawCollapsedSpans && line.markedSpans, found;
|
|
if (sps) { for (var i = 0; i < sps.length; ++i) {
|
|
var sp = sps[i];
|
|
if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
|
|
(!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
|
|
} }
|
|
return found
|
|
}
|
|
|
|
// 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, from, to, marker) {
|
|
var line = getLine(doc, lineNo);
|
|
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;
|
|
}
|
|
});
|
|
}
|
|
|
|
// 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 = {}, 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: 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, css, attributes) {
|
|
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 || attributes) {
|
|
var fullStyle = style || "";
|
|
if (startStyle) { fullStyle += startStyle; }
|
|
if (endStyle) { fullStyle += endStyle; }
|
|
var token = elt("span", [content], fullStyle, css);
|
|
if (attributes) {
|
|
for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
|
|
{ token.setAttribute(attr, attributes[attr]); } }
|
|
}
|
|
return builder.content.appendChild(token)
|
|
}
|
|
builder.content.appendChild(content);
|
|
}
|
|
|
|
// Change some spaces to NBSP to prevent the browser from collapsing
|
|
// trailing spaces at the end of a line when rendering text (issue #1362).
|
|
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, css, attributes) {
|
|
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, css, attributes) }
|
|
inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
|
|
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, collapsed, attributes;
|
|
for (;;) {
|
|
if (nextChange == pos) { // Update current marker set
|
|
spanStyle = spanEndStyle = spanStartStyle = css = "";
|
|
attributes = null;
|
|
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); }
|
|
// support for the old title property
|
|
// https://github.com/codemirror/CodeMirror/pull/5673
|
|
if (m.title) { (attributes || (attributes = {})).title = m.title; }
|
|
if (m.attributes) {
|
|
for (var attr in m.attributes)
|
|
{ (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
|
|
}
|
|
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 : "", css, attributes);
|
|
}
|
|
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"));
|
|
gutterWrap.setAttribute("aria-hidden", "true");
|
|
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.display.gutterSpecs.length; ++k) {
|
|
var id = cm.display.gutterSpecs[k].className, 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; }
|
|
var isWidget = classTest("CodeMirror-linewidget");
|
|
for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
|
|
next = node.nextSibling;
|
|
if (isWidget.test(node.className)) { 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" + (widget.className ? " " + widget.className : ""));
|
|
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", "CodeMirror-line-like"));
|
|
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} }
|
|
if (lineView.rest) {
|
|
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, 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.length; i += 3) {
|
|
mStart = map[i];
|
|
mEnd = map[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.length - 3 || ch == mEnd && map[i + 3] > ch) {
|
|
end = mEnd - mStart;
|
|
start = end - 1;
|
|
if (ch >= mEnd) { collapse = "right"; }
|
|
}
|
|
if (start != null) {
|
|
node = map[i + 2];
|
|
if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
|
|
{ collapse = bias; }
|
|
if (bias == "left" && start == 0)
|
|
{ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
|
|
node = map[(i -= 3) + 2];
|
|
collapse = "left";
|
|
} }
|
|
if (bias == "right" && start == mEnd - mStart)
|
|
{ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
|
|
node = map[(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(doc) {
|
|
// 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 -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
|
|
return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
|
|
}
|
|
function pageScrollY(doc) {
|
|
if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
|
|
return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
|
|
}
|
|
|
|
function widgetTopHeight(lineObj) {
|
|
var ref = visualLine(lineObj);
|
|
var widgets = ref.widgets;
|
|
var height = 0;
|
|
if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
|
|
{ height += widgetHeight(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(doc(cm)));
|
|
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
|
|
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(doc(cm));
|
|
top -= pageScrollY(doc(cm));
|
|
} 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 = outside; }
|
|
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, -1, -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, 1, 1) }
|
|
if (x < 0) { x = 0; }
|
|
|
|
var lineObj = getLine(doc, lineN);
|
|
for (;;) {
|
|
var found = coordsCharInner(cm, lineObj, lineN, x, y);
|
|
var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
|
|
if (!collapsed) { return found }
|
|
var rangeEnd = collapsed.find(1);
|
|
if (rangeEnd.line == lineN) { return rangeEnd }
|
|
lineObj = getLine(doc, lineN = rangeEnd.line);
|
|
}
|
|
}
|
|
|
|
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, 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 = 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, 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; box.bottom += widgetHeight;
|
|
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 <= 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, ch, sticky), "line", lineObj, preparedMeasure);
|
|
baseX = coords.left;
|
|
outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
|
|
}
|
|
|
|
ch = skipExtendingChars(lineObj.text, ch, 1);
|
|
return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
|
|
}
|
|
|
|
function coordsBidiPart(cm, lineObj, lineNo, 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, 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, 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", null, "CodeMirror-line-like");
|
|
// 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], "CodeMirror-line-like");
|
|
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) {
|
|
var id = cm.display.gutterSpecs[i].className;
|
|
left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
|
|
width[id] = 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$1) { return null }
|
|
var coords = coordsChar(cm, x, y), line;
|
|
if (forRect && coords.xRel > 0 && (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 }
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
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();
|
|
|
|
var customCursor = cm.options.$customCursor;
|
|
if (customCursor) { primary = true; }
|
|
for (var i = 0; i < doc.sel.ranges.length; i++) {
|
|
if (!primary && i == doc.sel.primIndex) { continue }
|
|
var range = doc.sel.ranges[i];
|
|
if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
|
|
var collapsed = range.empty();
|
|
if (customCursor) {
|
|
var head = customCursor(cm, range);
|
|
if (head) { drawSelectionCursor(cm, head, curFragment); }
|
|
} else if (collapsed || cm.options.showCursorWhenSelecting) {
|
|
drawSelectionCursor(cm, range.head, curFragment);
|
|
}
|
|
if (!collapsed)
|
|
{ drawSelectionRange(cm, range, 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 (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
|
|
var charPos = charCoords(cm, head, "div", null, null);
|
|
var width = charPos.right - charPos.left;
|
|
cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "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, 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.from(), sTo = range.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 () {
|
|
if (!cm.hasFocus()) { onBlur(cm); }
|
|
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.hasFocus()) {
|
|
cm.display.input.focus();
|
|
if (!cm.state.focused) { onFocus(cm); }
|
|
}
|
|
}
|
|
|
|
function delayBlurEvent(cm) {
|
|
cm.state.delayingBlurEvent = true;
|
|
setTimeout(function () { if (cm.state.delayingBlurEvent) {
|
|
cm.state.delayingBlurEvent = false;
|
|
if (cm.state.focused) { onBlur(cm); }
|
|
} }, 100);
|
|
}
|
|
|
|
function onFocus(cm, e) {
|
|
if (cm.state.delayingBlurEvent && !cm.state.draggingText) { 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;
|
|
var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
|
|
var oldHeight = display.lineDiv.getBoundingClientRect().top;
|
|
var mustScroll = 0;
|
|
for (var i = 0; i < display.view.length; i++) {
|
|
var cur = display.view[i], wrapping = cm.options.lineWrapping;
|
|
var height = (void 0), width = 0;
|
|
if (cur.hidden) { continue }
|
|
oldHeight += cur.line.height;
|
|
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;
|
|
// Check that lines don't extend past the right of the current
|
|
// editor width
|
|
if (!wrapping && cur.text.firstChild)
|
|
{ width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
|
|
}
|
|
var diff = cur.line.height - height;
|
|
if (diff > .005 || diff < -.005) {
|
|
if (oldHeight < viewTop) { mustScroll -= diff; }
|
|
updateLineHeight(cur.line, height);
|
|
updateWidgetHeight(cur.line);
|
|
if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
|
|
{ updateWidgetHeight(cur.rest[j]); } }
|
|
}
|
|
if (width > cm.display.sizerWidth) {
|
|
var chWidth = Math.ceil(width / charWidth(cm.display));
|
|
if (chWidth > cm.display.maxLineLength) {
|
|
cm.display.maxLineLength = chWidth;
|
|
cm.display.maxLine = cur.line;
|
|
cm.display.maxLineChanged = true;
|
|
}
|
|
}
|
|
}
|
|
if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
|
|
}
|
|
|
|
// 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)}
|
|
}
|
|
|
|
// 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;
|
|
var doc = display.wrapper.ownerDocument;
|
|
if (rect.top + box.top < 0) { doScroll = true; }
|
|
else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.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
|
|
end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
|
|
pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : 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 gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
|
|
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
|
|
var screenw = displayWidth(cm) - display.gutters.offsetWidth;
|
|
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 + gutterSpace - (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) {
|
|
resolveScrollToPos(cm);
|
|
cm.curOp.scrollToPos = range;
|
|
}
|
|
|
|
// 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 = cm.curOp.scrollToPos;
|
|
if (range) {
|
|
cm.curOp.scrollToPos = null;
|
|
var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
|
|
scrollToCoordsRange(cm, from, to, range.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.max(0, 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.max(0, 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");
|
|
vert.tabIndex = horiz.tabIndex = -1;
|
|
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.scrollTop = 0;
|
|
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.visibility = this.vert.style.visibility = "hidden";
|
|
this.disableHoriz = new Delayed;
|
|
this.disableVert = new Delayed;
|
|
};
|
|
|
|
NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
|
|
bar.style.visibility = "";
|
|
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 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
|
|
: document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
|
|
if (elt != bar) { bar.style.visibility = "hidden"; }
|
|
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: 0, // 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
|
|
markArrays: null // Used by addMarkedSpan
|
|
};
|
|
pushOperation(cm.curOp);
|
|
}
|
|
|
|
// Finish an operation, updating the display and signalling delayed events
|
|
function endOperation(cm) {
|
|
var op = cm.curOp;
|
|
if (op) { 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(root(cm));
|
|
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); }
|
|
}
|
|
}
|
|
|
|
// 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 () {
|
|
for (var i = 0; i < this.events.length; i++)
|
|
{ signal.apply(null, this.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(root(cm));
|
|
if (!active || !contains(cm.display.lineDiv, active)) { return null }
|
|
var result = {activeElt: active};
|
|
if (window.getSelection) {
|
|
var sel = win(cm).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(rootNode(snapshot.activeElt))) { return }
|
|
snapshot.activeElt.focus();
|
|
if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
|
|
snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
|
|
var doc = snapshot.activeElt.ownerDocument;
|
|
var sel = doc.defaultView.getSelection(), range = doc.createRange();
|
|
range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
|
|
range.collapse(false);
|
|
sel.removeAllRanges();
|
|
sel.addRange(range);
|
|
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 }
|
|
} else if (first) {
|
|
update.visible = visibleLines(cm.display, cm.doc, viewport);
|
|
}
|
|
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(display) {
|
|
var width = display.gutters.offsetWidth;
|
|
display.sizer.style.marginLeft = width + "px";
|
|
// Send an event to consumers responding to changes in gutter width.
|
|
signalLater(display, "gutterChanged", display);
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
// 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.display);
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
function getGutters(gutters, lineNumbers) {
|
|
var result = [], sawLineNumbers = false;
|
|
for (var i = 0; i < gutters.length; i++) {
|
|
var name = gutters[i], style = null;
|
|
if (typeof name != "string") { style = name.style; name = name.className; }
|
|
if (name == "CodeMirror-linenumbers") {
|
|
if (!lineNumbers) { continue }
|
|
else { sawLineNumbers = true; }
|
|
}
|
|
result.push({className: name, style: style});
|
|
}
|
|
if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
|
|
return result
|
|
}
|
|
|
|
// Rebuild the gutter elements, ensure the margin to the left of the
|
|
// code matches their width.
|
|
function renderGutters(display) {
|
|
var gutters = display.gutters, specs = display.gutterSpecs;
|
|
removeChildren(gutters);
|
|
display.lineGutter = null;
|
|
for (var i = 0; i < specs.length; ++i) {
|
|
var ref = specs[i];
|
|
var className = ref.className;
|
|
var style = ref.style;
|
|
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
|
|
if (style) { gElt.style.cssText = style; }
|
|
if (className == "CodeMirror-linenumbers") {
|
|
display.lineGutter = gElt;
|
|
gElt.style.width = (display.lineNumWidth || 1) + "px";
|
|
}
|
|
}
|
|
gutters.style.display = specs.length ? "" : "none";
|
|
updateGutterSpace(display);
|
|
}
|
|
|
|
function updateGutters(cm) {
|
|
renderGutters(cm.display);
|
|
regChange(cm);
|
|
alignHorizontally(cm);
|
|
}
|
|
|
|
// 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, options) {
|
|
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");
|
|
// See #6982. FIXME remove when this has been fixed for a while in Chrome
|
|
if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }
|
|
|
|
// This attribute is respected by automatic translation systems such as Google Translate,
|
|
// and may also be respected by tools used by human translators.
|
|
d.wrapper.setAttribute('translate', 'no');
|
|
|
|
// 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;
|
|
|
|
d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
|
|
renderGutters(d);
|
|
|
|
input.init(d);
|
|
}
|
|
|
|
// 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, 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) {
|
|
// On Chrome 102, viewport updates somehow stop wheel-based
|
|
// scrolling. Turning off pointer events during the scroll seems
|
|
// to avoid the issue.
|
|
if (chrome && chrome_version == 102) {
|
|
if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
|
|
else { clearTimeout(cm.display.chromeScrollHack); }
|
|
cm.display.chromeScrollHack = setTimeout(function () {
|
|
cm.display.chromeScrollHack = null;
|
|
cm.display.sizer.style.pointerEvents = "";
|
|
}, 100);
|
|
}
|
|
var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
|
|
var pixelsPerUnit = wheelPixelsPerUnit;
|
|
if (e.deltaMode === 0) {
|
|
dx = e.deltaX;
|
|
dy = e.deltaY;
|
|
pixelsPerUnit = 1;
|
|
}
|
|
|
|
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 && pixelsPerUnit != null) {
|
|
if (dy && canScrollY)
|
|
{ updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
|
|
setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
|
|
// 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 && pixelsPerUnit != null) {
|
|
var pixels = dy * pixelsPerUnit;
|
|
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 && e.deltaMode !== 0) {
|
|
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) {
|
|
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.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 out = [];
|
|
for (var i = 0; i < this.ranges.length; i++)
|
|
{ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
|
|
return new Selection(out, this.primIndex)
|
|
};
|
|
|
|
Selection.prototype.somethingSelected = function () {
|
|
for (var i = 0; i < this.ranges.length; i++)
|
|
{ if (!this.ranges[i].empty()) { return true } }
|
|
return false
|
|
};
|
|
|
|
Selection.prototype.contains = function (pos, end) {
|
|
if (!end) { end = pos; }
|
|
for (var i = 0; i < this.ranges.length; i++) {
|
|
var range = this.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(cm, ranges, primIndex) {
|
|
var mayTouch = cm && cm.options.selectionsMayTouch;
|
|
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];
|
|
var diff = cmp(prev.to(), cur.from());
|
|
if (mayTouch && !cur.empty() ? diff > 0 : diff >= 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(doc.cm, 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) {
|
|
function spansFor(n) {return markedSpans ? markedSpans[n] : null}
|
|
function update(line, text, spans) {
|
|
updateLine(line, text, spans, estimateHeight);
|
|
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)); }
|
|
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));
|
|
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);
|
|
cm.options.direction = doc.direction;
|
|
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(prev) {
|
|
// 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 = prev ? prev.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 = prev ? prev.maxGeneration : 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(doc.cm, 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(doc.cm, 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) {
|
|
this.ranges = [];
|
|
for (var i = 0; i < ranges.length; i++)
|
|
{ this.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(doc.cm, 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 && doc.cm.getOption("readOnly") != "nocursor")
|
|
{ ensureCursorVisible(doc.cm); }
|
|
}
|
|
|
|
function setSelectionInner(doc, sel) {
|
|
if (sel.equals(doc.sel)) { return }
|
|
|
|
doc.sel = sel;
|
|
|
|
if (doc.cm) {
|
|
doc.cm.curOp.updateInput = 1;
|
|
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 = range.head == range.anchor ? newAnchor : 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(doc.cm, 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;
|
|
|
|
// Determine if we should prevent the cursor being placed to the left/right of an atomic marker
|
|
// Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
|
|
// is with selectLeft/Right
|
|
var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
|
|
var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
|
|
|
|
if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
|
|
(sp.to == null || (preventCursorRight ? 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 ? preventCursorRight : preventCursorLeft)
|
|
{ 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 ? preventCursorLeft : preventCursorRight)
|
|
{ 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) {
|
|
if (doc.cm) { doc.cm.curOp.updateInput = 2; }
|
|
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);
|
|
|
|
if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
|
|
{ doc.cantEdit = false; }
|
|
}
|
|
|
|
// 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) {
|
|
var assign;
|
|
|
|
if (!to) { to = from; }
|
|
if (cmp(to, from) < 0) { (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) {
|
|
this.lines = lines;
|
|
this.parent = null;
|
|
var height = 0;
|
|
for (var i = 0; i < lines.length; ++i) {
|
|
lines[i].parent = this;
|
|
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) {
|
|
for (var i = at, e = at + n; i < e; ++i) {
|
|
var line = this.lines[i];
|
|
this.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) {
|
|
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; }
|
|
},
|
|
|
|
// Used to iterate over a part of the tree.
|
|
iterN: function(at, n, op) {
|
|
for (var e = at + n; at < e; ++at)
|
|
{ if (op(this.lines[at])) { return true } }
|
|
}
|
|
};
|
|
|
|
function BranchChunk(children) {
|
|
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;
|
|
}
|
|
this.size = size;
|
|
this.height = height;
|
|
this.parent = null;
|
|
}
|
|
|
|
BranchChunk.prototype = {
|
|
chunkSize: function() { return this.size },
|
|
|
|
removeInner: function(at, n) {
|
|
this.size -= n;
|
|
for (var i = 0; i < this.children.length; ++i) {
|
|
var child = this.children[i], sz = child.chunkSize();
|
|
if (at < sz) {
|
|
var rm = Math.min(n, sz - at), oldHeight = child.height;
|
|
child.removeInner(at, rm);
|
|
this.height -= oldHeight - child.height;
|
|
if (sz == rm) { this.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) {
|
|
for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
|
|
},
|
|
|
|
insertInner: function(at, lines, height) {
|
|
this.size += lines.length;
|
|
this.height += height;
|
|
for (var i = 0; i < this.children.length; ++i) {
|
|
var child = this.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.children.splice(++i, 0, leaf);
|
|
leaf.parent = this;
|
|
}
|
|
child.lines = child.lines.slice(0, remaining);
|
|
this.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) {
|
|
for (var i = 0; i < this.children.length; ++i) {
|
|
var child = this.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) {
|
|
if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
|
|
{ this[opt] = options[opt]; } } }
|
|
this.doc = doc;
|
|
this.node = node;
|
|
};
|
|
|
|
LineWidget.prototype.clear = function () {
|
|
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) { 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 }
|
|
if (!lineIsHidden(this.doc, line)) { 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, 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 () {
|
|
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.lines[i];
|
|
var span = getMarkedSpanFor(line.markedSpans, this);
|
|
if (cm && !this.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.collapsed && !lineIsHidden(this.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.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) {
|
|
if (side == null && this.type == "bookmark") { side = 1; }
|
|
var from, to;
|
|
for (var i = 0; i < this.lines.length; ++i) {
|
|
var line = this.lines[i];
|
|
var span = getMarkedSpanFor(line.markedSpans, this);
|
|
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), doc.cm && doc.cm.curOp);
|
|
++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.startStyle || marker.endStyle || marker.css ||
|
|
marker.attributes || marker.title)
|
|
{ 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) {
|
|
this.markers = markers;
|
|
this.primary = primary;
|
|
for (var i = 0; i < markers.length; ++i)
|
|
{ markers[i].parent = this; }
|
|
};
|
|
|
|
SharedTextMarker.prototype.clear = function () {
|
|
if (this.explicitlyCleared) { return }
|
|
this.explicitlyCleared = true;
|
|
for (var i = 0; i < this.markers.length; ++i)
|
|
{ this.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 }
|
|
if (lineSep === '') { return lines.join('') }
|
|
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 = this.sel.primary(), pos;
|
|
if (start == null || start == "head") { pos = range.head; }
|
|
else if (start == "anchor") { pos = range.anchor; }
|
|
else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
|
|
else { pos = range.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) {
|
|
if (!ranges.length) { return }
|
|
var out = [];
|
|
for (var i = 0; i < ranges.length; i++)
|
|
{ out[i] = new Range(clipPos(this, ranges[i].anchor),
|
|
clipPos(this, ranges[i].head || ranges[i].anchor)); }
|
|
if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
|
|
setSelection(this, normalizeSelection(this.cm, 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(this.cm, ranges, ranges.length - 1), options);
|
|
}),
|
|
|
|
getSelection: function(lineSep) {
|
|
var ranges = this.sel.ranges, lines;
|
|
for (var i = 0; i < ranges.length; i++) {
|
|
var sel = getBetween(this, 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 parts = [], ranges = this.sel.ranges;
|
|
for (var i = 0; i < ranges.length; i++) {
|
|
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
|
|
if (lineSep !== false) { sel = sel.join(lineSep || this.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 changes = [], sel = this.sel;
|
|
for (var i = 0; i < sel.ranges.length; i++) {
|
|
var range = sel.ranges[i];
|
|
changes[i] = {from: range.from(), to: range.to(), text: this.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, 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() {
|
|
var this$1 = this;
|
|
|
|
this.history = new History(this.history);
|
|
linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
|
|
},
|
|
|
|
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);
|
|
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 = 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 == from.line && from.ch >= span.to ||
|
|
span.from == null && lineNo != from.line ||
|
|
span.from != null && lineNo == to.line && span.from >= to.ch) &&
|
|
(!filter || filter(span.marker)))
|
|
{ found.push(span.marker.parent || span.marker); }
|
|
} }
|
|
++lineNo;
|
|
});
|
|
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 = 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;
|
|
});
|
|
return clipPos(this, Pos(lineNo, 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) {
|
|
if (other instanceof CodeMirror) { other = other.doc; }
|
|
if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
|
|
var link = this.linked[i];
|
|
if (link.doc != other) { continue }
|
|
this.linked.splice(i, 1);
|
|
other.unlinkDoc(this);
|
|
detachSharedMarkers(findSharedMarkers(this));
|
|
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 markAsReadAndPasteIfAllFilesAreRead = function () {
|
|
if (++read == n) {
|
|
operation(cm, function () {
|
|
pos = clipPos(cm.doc, pos);
|
|
var change = {from: pos, to: pos,
|
|
text: cm.doc.splitLines(
|
|
text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
|
|
origin: "paste"};
|
|
makeChange(cm.doc, change);
|
|
setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
|
|
})();
|
|
}
|
|
};
|
|
var readTextFromFile = function (file, i) {
|
|
if (cm.options.allowDropFileTypes &&
|
|
indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
|
|
markAsReadAndPasteIfAllFilesAreRead();
|
|
return
|
|
}
|
|
var reader = new FileReader;
|
|
reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
|
|
reader.onload = function () {
|
|
var content = reader.result;
|
|
if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
|
|
markAsReadAndPasteIfAllFilesAreRead();
|
|
return
|
|
}
|
|
text[i] = content;
|
|
markAsReadAndPasteIfAllFilesAreRead();
|
|
};
|
|
reader.readAsText(file);
|
|
};
|
|
for (var i = 0; i < files.length; i++) { readTextFromFile(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$1){}
|
|
}
|
|
}
|
|
|
|
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"), editors = [];
|
|
for (var i = 0; i < byClass.length; i++) {
|
|
var cm = byClass[i].CodeMirror;
|
|
if (cm) { editors.push(cm); }
|
|
}
|
|
if (editors.length) { editors[0].operation(function () {
|
|
for (var i = 0; i < editors.length; i++) { f(editors[i]); }
|
|
}); }
|
|
}
|
|
|
|
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;
|
|
// 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: "/", 145: "ScrollLock",
|
|
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
|
|
221: "]", 222: "'", 224: "Mod", 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",
|
|
"Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
|
|
"Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "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, handle, context) {
|
|
map = getKeyMap(map);
|
|
var found = map.call ? map.call(key, context) : map[key];
|
|
if (found === false) { return "nothing" }
|
|
if (found === "...") { return "multi" }
|
|
if (found != null && handle(found)) { return "handled" }
|
|
|
|
if (map.fallthrough) {
|
|
if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
|
|
{ return lookupKey(key, map.fallthrough, handle, context) }
|
|
for (var i = 0; i < map.fallthrough.length; i++) {
|
|
var result = lookupKey(key, map.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 != "Mod") { 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) {
|
|
if (cm.doc.direction == "rtl") { dir = -dir; }
|
|
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, "codepoint"); },
|
|
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(start.ch, 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;
|
|
if (e.target && e.target != cm.display.input.getField()) { return }
|
|
cm.curOp.focus = activeElt(root(cm));
|
|
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"); }
|
|
}
|
|
if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
|
|
{ document.execCommand("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 (e.target && e.target != cm.display.input.getField()) { return }
|
|
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, 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";
|
|
win(cm).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) { cm.display.input.onContextMenu(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(root(cm)); }
|
|
|
|
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;
|
|
if (cm.state.delayingBlurEvent) {
|
|
if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
|
|
else { delayBlurEvent(cm); }
|
|
}
|
|
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 && !safari) || ie && ie_version == 9)
|
|
{ setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); 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;
|
|
on(display.wrapper.ownerDocument, "mouseup", dragEnd);
|
|
on(display.wrapper.ownerDocument, "mousemove", mouseMove);
|
|
on(display.scroller, "dragstart", dragStart);
|
|
on(display.scroller, "drop", dragEnd);
|
|
|
|
cm.state.delayingBlurEvent = true;
|
|
setTimeout(function () { return display.input.focus(); }, 20);
|
|
// IE's approach to draggable
|
|
if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
|
|
}
|
|
|
|
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) {
|
|
if (ie) { delayBlurEvent(cm); }
|
|
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 = rangeForUnit(cm, start, behavior.unit);
|
|
if (behavior.extend)
|
|
{ ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
|
|
else
|
|
{ ourRange = range; }
|
|
}
|
|
|
|
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(cm, ranges.concat([ourRange]), ourIndex),
|
|
{scroll: false, origin: "*mouse"});
|
|
} else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
|
|
setSelection(doc, normalizeSelection(cm, 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(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
|
|
{origin: "*mouse", scroll: false});
|
|
cm.scrollIntoView(pos);
|
|
} else {
|
|
var oldRange = ourRange;
|
|
var range = rangeForUnit(cm, pos, behavior.unit);
|
|
var anchor = oldRange.anchor, head;
|
|
if (cmp(range.anchor, anchor) > 0) {
|
|
head = range.head;
|
|
anchor = minPos(oldRange.from(), range.anchor);
|
|
} else {
|
|
head = range.anchor;
|
|
anchor = maxPos(oldRange.to(), range.head);
|
|
}
|
|
var ranges$1 = startSel.ranges.slice(0);
|
|
ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
|
|
setSelection(doc, normalizeSelection(cm, 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(root(cm));
|
|
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;
|
|
// If e is null or undefined we interpret this as someone trying
|
|
// to explicitly cancel the selection rather than the user
|
|
// letting go of the mouse button.
|
|
if (e) {
|
|
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.buttons === 0 || !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) {
|
|
var anchor = range.anchor;
|
|
var head = range.head;
|
|
var anchorLine = getLine(cm.doc, anchor.line);
|
|
if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
|
|
var order = getOrder(anchorLine);
|
|
if (!order) { return range }
|
|
var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
|
|
if (part.from != anchor.ch && part.to != anchor.ch) { return range }
|
|
var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
|
|
if (boundary == 0 || boundary == order.length) { return range }
|
|
|
|
// 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 : 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$1) { 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.display.gutterSpecs.length; ++i) {
|
|
var g = display.gutters.childNodes[i];
|
|
if (g && g.getBoundingClientRect().right >= mX) {
|
|
var line = lineAtHeight(cm.doc, mY);
|
|
var gutter = cm.display.gutterSpecs[i];
|
|
signal(cm, type, cm, line, gutter.className, 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 }
|
|
if (!captureRightClick) { 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\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/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("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
|
|
option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
|
|
option("rtlMoveVisually", !windows);
|
|
option("wholeLineUpdateBefore", true);
|
|
|
|
option("theme", "default", function (cm) {
|
|
themeChanged(cm);
|
|
updateGutters(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, val) {
|
|
cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
|
|
updateGutters(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, val) {
|
|
cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
|
|
updateGutters(cm);
|
|
}, true);
|
|
option("firstLineNumber", 1, updateGutters, true);
|
|
option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
|
|
option("showCursorWhenSelecting", false, updateSelection, true);
|
|
|
|
option("resetSelectionOnContextMenu", true);
|
|
option("lineWiseCopyCut", true);
|
|
option("pasteLinesPerSelection", true);
|
|
option("selectionsMayTouch", false);
|
|
|
|
option("readOnly", false, function (cm, val) {
|
|
if (val == "nocursor") {
|
|
onBlur(cm);
|
|
cm.display.input.blur();
|
|
}
|
|
cm.display.input.readOnlyChanged(val);
|
|
});
|
|
|
|
option("screenReaderLabel", null, function (cm, val) {
|
|
val = (val === '') ? null : val;
|
|
cm.display.input.screenReaderLabelChanged(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);
|
|
option("phrases", null);
|
|
}
|
|
|
|
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(place, options) {
|
|
var this$1 = this;
|
|
|
|
if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
|
|
|
|
this.options = options = options ? copyObj(options) : {};
|
|
// Determine effective options based on given values and defaults.
|
|
copyObj(defaults, options, false);
|
|
|
|
var doc = options.value;
|
|
if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
|
|
else if (options.mode) { doc.modeOption = options.mode; }
|
|
this.doc = doc;
|
|
|
|
var input = new CodeMirror.inputStyles[options.inputStyle](this);
|
|
var display = this.display = new Display(place, doc, input, options);
|
|
display.wrapper.CodeMirror = 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: -1, cutIncoming: -1, // 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(function () {
|
|
if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
|
|
}, 20); }
|
|
else
|
|
{ onBlur(this); }
|
|
|
|
for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
|
|
{ optionHandlers[opt](this, options[opt], Init); } }
|
|
maybeUpdateLineNumberWidth(this);
|
|
if (options.finishInit) { options.finishInit(this); }
|
|
for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
|
|
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.defaults = defaults;
|
|
// Functions to run when options are changed.
|
|
CodeMirror.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.
|
|
on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
|
|
on(d.input.getField(), "contextmenu", function (e) {
|
|
if (!d.scroller.contains(e.target)) { 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.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 recent = +new Date - 200;
|
|
var paste = origin == "paste" || cm.state.pasteIncoming > recent;
|
|
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 = cm.curOp.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 = sel.ranges[i$1];
|
|
var from = range.from(), to = range.to();
|
|
if (range.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 (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
|
|
{ from = to = Pos(from.line, 0); }
|
|
}
|
|
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
|
|
origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
|
|
makeChange(cm.doc, changeEvent);
|
|
signalLater(cm, "inputRead", cm, changeEvent);
|
|
}
|
|
if (inserted && !paste)
|
|
{ triggerElectric(cm, inserted); }
|
|
|
|
ensureCursorVisible(cm);
|
|
if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
|
|
cm.curOp.typing = true;
|
|
cm.state.pasteIncoming = cm.state.cutIncoming = -1;
|
|
}
|
|
|
|
function handlePaste(e, cm) {
|
|
var pasted = e.clipboardData && e.clipboardData.getData("Text");
|
|
if (pasted) {
|
|
e.preventDefault();
|
|
if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
|
|
{ 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 = sel.ranges[i];
|
|
if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
|
|
var mode = cm.getModeAt(range.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.head.line, "smart");
|
|
break
|
|
} }
|
|
} else if (mode.electricInput) {
|
|
if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
|
|
{ indented = indentLine(cm, range.head.line, "smart"); }
|
|
}
|
|
if (indented) { signalLater(cm, "electricInput", cm, range.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, autocorrect, autocapitalize) {
|
|
field.setAttribute("autocorrect", autocorrect ? "on" : "off");
|
|
field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
|
|
field.setAttribute("spellcheck", !!spellcheck);
|
|
}
|
|
|
|
function hiddenTextarea() {
|
|
var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-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"; }
|
|
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.
|
|
|
|
function addEditorMethods(CodeMirror) {
|
|
var optionHandlers = CodeMirror.optionHandlers;
|
|
|
|
var helpers = CodeMirror.helpers = {};
|
|
|
|
CodeMirror.prototype = {
|
|
constructor: CodeMirror,
|
|
focus: function(){win(this).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, bottom) {
|
|
this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
|
|
},
|
|
removeKeyMap: function(map) {
|
|
var maps = this.state.keyMaps;
|
|
for (var i = 0; i < maps.length; ++i)
|
|
{ if (maps[i] == map || maps[i].name == map) {
|
|
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 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.state.modeGen++;
|
|
regChange(this);
|
|
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 ranges = this.doc.sel.ranges, end = -1;
|
|
for (var i = 0; i < ranges.length; i++) {
|
|
var range = ranges[i];
|
|
if (!range.empty()) {
|
|
var from = range.from(), to = range.to();
|
|
var start = Math.max(end, from.line);
|
|
end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
|
|
for (var j = start; j < end; ++j)
|
|
{ indentLine(this, j, how); }
|
|
var newRanges = this.doc.sel.ranges;
|
|
if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
|
|
{ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
|
|
} else if (range.head.line > end) {
|
|
indentLine(this, range.head.line, how, true);
|
|
end = range.head.line;
|
|
if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
|
|
}
|
|
}
|
|
}),
|
|
|
|
// 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 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) && 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 = this.doc.sel.primary();
|
|
if (start == null) { pos = range.head; }
|
|
else if (typeof start == "object") { pos = clipPos(this.doc, start); }
|
|
else { pos = start ? range.from() : range.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 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.doc, cur, dir, unit, visually);
|
|
if (cur.hitSide) { break }
|
|
}
|
|
return cur
|
|
},
|
|
|
|
moveH: methodOp(function(dir, unit) {
|
|
var this$1 = this;
|
|
|
|
this.extendSelectionsBy(function (range) {
|
|
if (this$1.display.shift || this$1.doc.extend || range.empty())
|
|
{ return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
|
|
else
|
|
{ return dir < 0 ? range.from() : range.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) {
|
|
var other = findPosH(doc, range.head, dir, unit, false);
|
|
return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
|
|
}); }
|
|
}),
|
|
|
|
findPosV: function(from, amount, unit, goalColumn) {
|
|
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, cur, "div");
|
|
if (x == null) { x = coords.left; }
|
|
else { coords.left = x; }
|
|
cur = findPosV(this, 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) {
|
|
if (collapse)
|
|
{ return dir < 0 ? range.from() : range.to() }
|
|
var headPos = cursorCoords(this$1, range.head, "div");
|
|
if (range.goalColumn != null) { headPos.left = range.goalColumn; }
|
|
goals.push(headPos.left);
|
|
var pos = findPosV(this$1, headPos, dir, unit);
|
|
if (unit == "page" && range == 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(root(this)) },
|
|
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, margin) {
|
|
if (range == null) {
|
|
range = {from: this.doc.sel.primary().head, to: null};
|
|
if (margin == null) { margin = this.options.cursorScrollMargin; }
|
|
} else if (typeof range == "number") {
|
|
range = {from: Pos(range, 0), to: null};
|
|
} else if (range.from == null) {
|
|
range = {from: range, to: null};
|
|
}
|
|
if (!range.to) { range.to = range.from; }
|
|
range.margin = margin || 0;
|
|
|
|
if (range.from.line != null) {
|
|
scrollToRange(this, range);
|
|
} else {
|
|
scrollToCoordsRange(this, range.from, range.to, range.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 = this.display.viewFrom;
|
|
this.doc.iter(lineNo, 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, "widget"); break } } }
|
|
++lineNo;
|
|
});
|
|
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.display);
|
|
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
|
|
{ estimateLineHeights(this); }
|
|
signal(this, "refresh", this);
|
|
}),
|
|
|
|
swapDoc: methodOp(function(doc) {
|
|
var old = this.doc;
|
|
old.cm = null;
|
|
// Cancel the current text selection if any (#5821)
|
|
if (this.state.selectingText) { this.state.selectingText(); }
|
|
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
|
|
}),
|
|
|
|
phrase: function(phraseText) {
|
|
var phrases = this.options.phrases;
|
|
return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
|
|
},
|
|
|
|
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 "codepoint", "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);
|
|
var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
|
|
function findNextLine() {
|
|
var l = pos.line + lineDir;
|
|
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 (unit == "codepoint") {
|
|
var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
|
|
if (isNaN(ch)) {
|
|
next = null;
|
|
} else {
|
|
var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
|
|
next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
|
|
}
|
|
} else 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, lineDir); }
|
|
else
|
|
{ return false }
|
|
} else {
|
|
pos = next;
|
|
}
|
|
return true
|
|
}
|
|
|
|
if (unit == "char" || unit == "codepoint") {
|
|
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, win(cm).innerHeight || doc(cm).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;
|
|
div.contentEditable = true;
|
|
disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
|
|
|
|
function belongsToInput(e) {
|
|
for (var t = e.target; t; t = t.parentNode) {
|
|
if (t == div) { return true }
|
|
if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
|
|
}
|
|
return false
|
|
}
|
|
|
|
on(div, "paste", function (e) {
|
|
if (!belongsToInput(e) || 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 (!belongsToInput(e) || 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;
|
|
disableBrowserMagic(te);
|
|
cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
|
|
te.value = lastCopied.text.join("\n");
|
|
var hadFocus = activeElt(rootNode(div));
|
|
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.screenReaderLabelChanged = function (label) {
|
|
// Label for screenreaders, accessibility
|
|
if(label) {
|
|
this.div.setAttribute('aria-label', label);
|
|
} else {
|
|
this.div.removeAttribute('aria-label');
|
|
}
|
|
};
|
|
|
|
ContentEditableInput.prototype.prepareSelection = function () {
|
|
var result = prepareSelection(this.cm, false);
|
|
result.focus = activeElt(rootNode(this.div)) == this.div;
|
|
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.getSelection = function () {
|
|
return this.cm.display.wrapper.ownerDocument.getSelection()
|
|
};
|
|
|
|
ContentEditableInput.prototype.showPrimarySelection = function () {
|
|
var sel = this.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 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
|
|
end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.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 = this.getSelection();
|
|
this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
|
|
this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
|
|
};
|
|
|
|
ContentEditableInput.prototype.selectionInEditor = function () {
|
|
var sel = this.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() || activeElt(rootNode(this.div)) != this.div)
|
|
{ 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 this$1 = this;
|
|
|
|
var input = this;
|
|
if (this.selectionInEditor())
|
|
{ setTimeout(function () { return this$1.pollSelection(); }, 20); }
|
|
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 = this.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 = this.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.display.gutterSpecs.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(), extraLinebreak = false;
|
|
function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
|
|
function close() {
|
|
if (closing) {
|
|
text += lineSep;
|
|
if (extraLinebreak) { text += lineSep; }
|
|
closing = extraLinebreak = false;
|
|
}
|
|
}
|
|
function addText(str) {
|
|
if (str) {
|
|
close();
|
|
text += str;
|
|
}
|
|
}
|
|
function walk(node) {
|
|
if (node.nodeType == 1) {
|
|
var cmText = node.getAttribute("cm-text");
|
|
if (cmText) {
|
|
addText(cmText);
|
|
return
|
|
}
|
|
var markerID = node.getAttribute("cm-marker"), range;
|
|
if (markerID) {
|
|
var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
|
|
if (found.length && (range = found[0].find(0)))
|
|
{ addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
|
|
return
|
|
}
|
|
if (node.getAttribute("contenteditable") == "false") { return }
|
|
var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
|
|
if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
|
|
|
|
if (isBlock) { close(); }
|
|
for (var i = 0; i < node.childNodes.length; i++)
|
|
{ walk(node.childNodes[i]); }
|
|
|
|
if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
|
|
if (isBlock) { closing = true; }
|
|
} else if (node.nodeType == 3) {
|
|
addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
|
|
}
|
|
}
|
|
for (;;) {
|
|
walk(from);
|
|
if (from == to) { break }
|
|
from = from.nextSibling;
|
|
extraLinebreak = false;
|
|
}
|
|
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 = i < 0 ? measure.map : maps[i];
|
|
for (var j = 0; j < map.length; j += 3) {
|
|
var curNode = map[j + 2];
|
|
if (curNode == textNode || curNode == topNode) {
|
|
var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
|
|
var ch = map[j] + offset;
|
|
if (offset < 0 || curNode != textNode) { ch = map[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;
|
|
this.resetting = false;
|
|
};
|
|
|
|
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 = +new Date;
|
|
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 = +new Date; }
|
|
}
|
|
on(te, "cut", prepareCopyCut);
|
|
on(te, "copy", prepareCopyCut);
|
|
|
|
on(display.scroller, "paste", function (e) {
|
|
if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
|
|
if (!te.dispatchEvent) {
|
|
cm.state.pasteIncoming = +new Date;
|
|
input.focus();
|
|
return
|
|
}
|
|
|
|
// Pass the `paste` event to the textarea so it's handled by its event listener.
|
|
var event = new Event("paste");
|
|
event.clipboardData = e.clipboardData;
|
|
te.dispatchEvent(event);
|
|
});
|
|
|
|
// 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;
|
|
var opts = this.cm.options;
|
|
disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
|
|
};
|
|
|
|
TextareaInput.prototype.screenReaderLabelChanged = function (label) {
|
|
// Label for screenreaders, accessibility
|
|
if(label) {
|
|
this.textarea.setAttribute('aria-label', label);
|
|
} else {
|
|
this.textarea.removeAttribute('aria-label');
|
|
}
|
|
};
|
|
|
|
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 && typing) { return }
|
|
var cm = this.cm;
|
|
this.resetting = true;
|
|
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; }
|
|
}
|
|
this.resetting = false;
|
|
};
|
|
|
|
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(rootNode(this.textarea)) != 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 || this.resetting || !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;
|
|
if (input.contextMenuPending) { input.contextMenuPending(); }
|
|
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;
|
|
var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
|
|
input.wrapper.style.cssText = "position: static";
|
|
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 = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
|
|
display.input.focus();
|
|
if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
|
|
display.input.reset();
|
|
// Adds "Select all" to context menu in FF
|
|
if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
|
|
input.contextMenuPending = rehide;
|
|
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() {
|
|
if (input.contextMenuPending != rehide) { return }
|
|
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";
|
|
this.textarea.readOnly = !!val;
|
|
};
|
|
|
|
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(rootNode(textarea));
|
|
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 (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
|
|
{ textarea.form.submit = realSubmit; }
|
|
}
|
|
};
|
|
};
|
|
|
|
textarea.style.display = "none";
|
|
var cm = CodeMirror(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);
|
|
|
|
addEditorMethods(CodeMirror);
|
|
|
|
// 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.prototype[prop] = (function(method) {
|
|
return function() {return method.apply(this.doc, arguments)}
|
|
})(Doc.prototype[prop]); } }
|
|
|
|
eventMixin(Doc);
|
|
CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
|
|
|
|
// 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.defineMode = function(name/*, mode, …*/) {
|
|
if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
|
|
defineMode.apply(this, arguments);
|
|
};
|
|
|
|
CodeMirror.defineMIME = defineMIME;
|
|
|
|
// Minimal default mode.
|
|
CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
|
|
CodeMirror.defineMIME("text/plain", "null");
|
|
|
|
// EXTENSIONS
|
|
|
|
CodeMirror.defineExtension = function (name, func) {
|
|
CodeMirror.prototype[name] = func;
|
|
};
|
|
CodeMirror.defineDocExtension = function (name, func) {
|
|
Doc.prototype[name] = func;
|
|
};
|
|
|
|
CodeMirror.fromTextArea = fromTextArea;
|
|
|
|
addLegacyProps(CodeMirror);
|
|
|
|
CodeMirror.version = "5.65.17";
|
|
|
|
return CodeMirror;
|
|
|
|
})));
|
|
|
|
|
|
/***/ }),
|
|
/* 201 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
|
|
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
|
|
|
|
(function(mod) {
|
|
if (true) // CommonJS
|
|
mod(__webpack_require__(200));
|
|
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 trackScope = parserConfig.trackScope !== false
|
|
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[\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.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
|
|
return ret("number", "number");
|
|
} else if (/\d/.test(ch)) {
|
|
stream.match(/^[\d_]*(?:n|(?:\.[\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(([gimyus])(?![gimyus]*\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.peek() == "!") {
|
|
stream.skipToEnd();
|
|
return ret("meta", "meta");
|
|
} else if (ch == "#" && stream.eatWhile(wordRE)) {
|
|
return ret("variable", "property")
|
|
} else if (ch == "<" && stream.match("!--") ||
|
|
(ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
|
|
stream.skipToEnd()
|
|
return ret("comment", "comment")
|
|
} 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)
|
|
}
|
|
}
|
|
if (ch == "?" && stream.eat(".")) return ret(".")
|
|
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)) {
|
|
for (;; --pos) {
|
|
if (pos == 0) return
|
|
var next = stream.string.charAt(pos - 1)
|
|
if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
|
|
}
|
|
} 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, "import": 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) {
|
|
if (!trackScope) return false
|
|
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 inList(name, list) {
|
|
for (var v = list; v; v = v.next) if (v.name == name) return true
|
|
return false;
|
|
}
|
|
function register(varname) {
|
|
var state = cx.state;
|
|
cx.marked = "def";
|
|
if (!trackScope) return
|
|
if (state.context) {
|
|
if (state.lexical.info == "var" && state.context && state.context.block) {
|
|
// FIXME function decls are also not block scoped
|
|
var newContext = registerVarScoped(varname, state.context)
|
|
if (newContext != null) {
|
|
state.context = newContext
|
|
return
|
|
}
|
|
} else if (!inList(varname, state.localVars)) {
|
|
state.localVars = new Var(varname, state.localVars)
|
|
return
|
|
}
|
|
}
|
|
// Fall through means this is global
|
|
if (parserConfig.globalVars && !inList(varname, state.globalVars))
|
|
state.globalVars = new Var(varname, state.globalVars)
|
|
}
|
|
function registerVarScoped(varname, context) {
|
|
if (!context) {
|
|
return null
|
|
} else if (context.block) {
|
|
var inner = registerVarScoped(varname, context.prev)
|
|
if (!inner) return null
|
|
if (inner == context.prev) return context
|
|
return new Context(inner, context.vars, true)
|
|
} else if (inList(varname, context.vars)) {
|
|
return context
|
|
} else {
|
|
return new Context(context.prev, new Var(varname, context.vars), false)
|
|
}
|
|
}
|
|
|
|
function isModifier(name) {
|
|
return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
|
|
}
|
|
|
|
// Combinators
|
|
|
|
function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
|
|
function Var(name, next) { this.name = name; this.next = next }
|
|
|
|
var defaultVars = new Var("this", new Var("arguments", null))
|
|
function pushcontext() {
|
|
cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
|
|
cx.state.localVars = defaultVars
|
|
}
|
|
function pushblockcontext() {
|
|
cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
|
|
cx.state.localVars = null
|
|
}
|
|
pushcontext.lex = pushblockcontext.lex = true
|
|
function popcontext() {
|
|
cx.state.localVars = cx.state.context.vars
|
|
cx.state.context = cx.state.context.prev
|
|
}
|
|
popcontext.lex = true
|
|
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 == ";" || type == "}" || type == ")" || type == "]") return pass();
|
|
else return cont(exp);
|
|
};
|
|
return exp;
|
|
}
|
|
|
|
function statement(type, value) {
|
|
if (type == "var") return cont(pushlex("vardef", value), 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("}"), pushblockcontext, block, poplex, popcontext);
|
|
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"), pushblockcontext, forspec, statement, popcontext, poplex);
|
|
if (type == "class" || (isTS && value == "interface")) {
|
|
cx.marked = "keyword"
|
|
return cont(pushlex("form", type == "class" ? type : value), 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(typename, 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, statement, 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"), pushblockcontext,
|
|
block, poplex, poplex, popcontext);
|
|
if (type == "case") return cont(expression, expect(":"));
|
|
if (type == "default") return cont(expect(":"));
|
|
if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, 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 maybeCatchBinding(type) {
|
|
if (type == "(") return cont(funarg, expect(")"))
|
|
}
|
|
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(")"), maybeexpression, 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));
|
|
return cont();
|
|
}
|
|
function maybeexpression(type) {
|
|
if (type.match(/[;\}\)\],]/)) return pass();
|
|
return pass(expression);
|
|
}
|
|
|
|
function maybeoperatorComma(type, value) {
|
|
if (type == ",") return cont(maybeexpression);
|
|
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(maybeexpression, 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();
|
|
if (sep && sep.indexOf(";") > -1) return pass(what)
|
|
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 maybetypeOrIn(type, value) {
|
|
if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
|
|
}
|
|
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" || value == "infer" || value == "readonly") {
|
|
cx.marked = "keyword"
|
|
return cont(value == "typeof" ? expressionNoComma : typeexpr)
|
|
}
|
|
if (type == "variable" || value == "void") {
|
|
cx.marked = "type"
|
|
return cont(afterType)
|
|
}
|
|
if (value == "|" || value == "&") return cont(typeexpr)
|
|
if (type == "string" || type == "number" || type == "atom") return cont(afterType);
|
|
if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
|
|
if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType)
|
|
if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
|
|
if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
|
|
if (type == "quasi") { return pass(quasiType, afterType); }
|
|
}
|
|
function maybeReturnType(type) {
|
|
if (type == "=>") return cont(typeexpr)
|
|
}
|
|
function typeprops(type) {
|
|
if (type.match(/[\}\)\]]/)) return cont()
|
|
if (type == "," || type == ";") return cont(typeprops)
|
|
return pass(typeprop, typeprops)
|
|
}
|
|
function typeprop(type, value) {
|
|
if (type == "variable" || cx.style == "keyword") {
|
|
cx.marked = "property"
|
|
return cont(typeprop)
|
|
} else if (value == "?" || type == "number" || type == "string") {
|
|
return cont(typeprop)
|
|
} else if (type == ":") {
|
|
return cont(typeexpr)
|
|
} else if (type == "[") {
|
|
return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
|
|
} else if (type == "(") {
|
|
return pass(functiondecl, typeprop)
|
|
} else if (!type.match(/[;\}\)\],]/)) {
|
|
return cont()
|
|
}
|
|
}
|
|
function quasiType(type, value) {
|
|
if (type != "quasi") return pass();
|
|
if (value.slice(value.length - 2) != "${") return cont(quasiType);
|
|
return cont(typeexpr, continueQuasiType);
|
|
}
|
|
function continueQuasiType(type) {
|
|
if (type == "}") {
|
|
cx.marked = "string-2";
|
|
cx.state.tokenize = tokenQuasi;
|
|
return cont(quasiType);
|
|
}
|
|
}
|
|
function typearg(type, value) {
|
|
if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
|
|
if (type == ":") return cont(typeexpr)
|
|
if (type == "spread") return cont(typearg)
|
|
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(typeexpr, expect("]"), afterType)
|
|
if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
|
|
if (value == "?") return cont(typeexpr, expect(":"), 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(eltpattern, "]");
|
|
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();
|
|
if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
|
|
return cont(expect(":"), pattern, maybeAssign);
|
|
}
|
|
function eltpattern() {
|
|
return pass(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, poplex);
|
|
}
|
|
function forspec1(type) {
|
|
if (type == "var") return cont(vardef, forspec2);
|
|
if (type == "variable") return cont(forspec2);
|
|
return pass(forspec2)
|
|
}
|
|
function forspec2(type, value) {
|
|
if (type == ")") return cont()
|
|
if (type == ";") return cont(forspec2)
|
|
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
|
|
return pass(expression, forspec2)
|
|
}
|
|
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 functiondecl(type, value) {
|
|
if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
|
|
if (type == "variable") {register(value); return cont(functiondecl);}
|
|
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
|
|
if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
|
|
}
|
|
function typename(type, value) {
|
|
if (type == "keyword" || type == "variable") {
|
|
cx.marked = "type"
|
|
return cont(typename)
|
|
} else if (value == "<") {
|
|
return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
|
|
}
|
|
}
|
|
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); }
|
|
if (isTS && type == "this") return cont(maybetype, maybeAssign)
|
|
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(classfield, classBody);
|
|
}
|
|
if (type == "number" || type == "string") return cont(classfield, classBody);
|
|
if (type == "[")
|
|
return cont(expression, maybetype, expect("]"), classfield, classBody)
|
|
if (value == "*") {
|
|
cx.marked = "keyword";
|
|
return cont(classBody);
|
|
}
|
|
if (isTS && type == "(") return pass(functiondecl, classBody)
|
|
if (type == ";" || type == ",") return cont(classBody);
|
|
if (type == "}") return cont();
|
|
if (value == "@") return cont(expression, classBody)
|
|
}
|
|
function classfield(type, value) {
|
|
if (value == "!") return cont(classfield)
|
|
if (value == "?") return cont(classfield)
|
|
if (type == ":") return cont(typeexpr, maybeAssign)
|
|
if (value == "=") return cont(expressionNoComma)
|
|
var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
|
|
return pass(isInterface ? functiondecl : 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);
|
|
if (type == ".") return pass(maybeoperatorComma);
|
|
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 && new Context(null, null, false),
|
|
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 || state.tokenize == tokenQuasi) 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 && c != popcontext) 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.length + 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) {
|
|
parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null))
|
|
}
|
|
};
|
|
});
|
|
|
|
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/manifest+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 });
|
|
|
|
});
|
|
|
|
|
|
/***/ }),
|
|
/* 202 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var __extends = (this && this.__extends) || function (d, b) {
|
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
|
function __() { this.constructor = d; }
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
var React = __webpack_require__(1);
|
|
var falafel_1 = __webpack_require__(203);
|
|
var loop_inserter_1 = __webpack_require__(205);
|
|
var implicit_sketch_1 = __webpack_require__(206);
|
|
var pure_component_1 = __webpack_require__(194);
|
|
var LOOP_CHECK_FUNC_NAME = '__loopCheck';
|
|
var Preview = (function (_super) {
|
|
__extends(Preview, _super);
|
|
function Preview() {
|
|
_super.apply(this, arguments);
|
|
}
|
|
Preview.prototype.resetIframe = function () {
|
|
var _this = this;
|
|
var content = this.props.content;
|
|
content = implicit_sketch_1.default(content);
|
|
try {
|
|
content = falafel_1.default(content, {}, loop_inserter_1.default(function (node) {
|
|
return LOOP_CHECK_FUNC_NAME + "(" + JSON.stringify(node.range) + ");";
|
|
})).toString();
|
|
}
|
|
catch (e) {
|
|
}
|
|
if (this._iframe) {
|
|
this._iframe.parentNode.removeChild(this._iframe);
|
|
this._iframe = null;
|
|
}
|
|
var iframe = document.createElement('iframe');
|
|
iframe.setAttribute('src', 'preview-frame.html');
|
|
iframe.setAttribute('width', this.props.width.toString());
|
|
iframe.addEventListener('load', function () {
|
|
// Note that this should never be called if we're already unmounted,
|
|
// since that means the iframe will have been removed from the DOM,
|
|
// in which case it shouldn't be emitting events anymore.
|
|
var frame = iframe.contentWindow;
|
|
console.log("#p5 content", content);
|
|
frame.startSketch(content, _this.props.p5version, _this.props.maxRunTime, LOOP_CHECK_FUNC_NAME, _this.props.baseSketchURL, _this.props.onError);
|
|
});
|
|
this.refs.container.appendChild(iframe);
|
|
this._iframe = iframe;
|
|
};
|
|
Preview.prototype.componentDidUpdate = function (prevProps, prevState) {
|
|
if (prevProps.timestamp !== this.props.timestamp) {
|
|
this.resetIframe();
|
|
}
|
|
};
|
|
Preview.prototype.componentDidMount = function () {
|
|
this.resetIframe();
|
|
};
|
|
Preview.prototype.componentWillUnmount = function () {
|
|
this._iframe = null;
|
|
};
|
|
Preview.prototype.render = function () {
|
|
return React.createElement("div", {ref: "container", className: "preview-holder"});
|
|
};
|
|
return Preview;
|
|
}(pure_component_1.default));
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Preview;
|
|
|
|
|
|
/***/ }),
|
|
/* 203 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// This is an older version of falafel that used esprima instead of acorn.
|
|
// Taken from https://github.com/toolness/slowmo-js.
|
|
"use strict";
|
|
var esprima = __webpack_require__(204);
|
|
var parse = esprima.parse;
|
|
var LOOP_CHECK_FUNC_NAME = '__loopCheck';
|
|
function default_1(src, opts, fn) {
|
|
if (typeof opts === 'function') {
|
|
fn = opts;
|
|
opts = {};
|
|
}
|
|
if (typeof src === 'object') {
|
|
opts = src;
|
|
src = opts.source;
|
|
delete opts.source;
|
|
}
|
|
src = src || opts.source;
|
|
opts.range = true;
|
|
if (typeof src !== 'string')
|
|
src = String(src);
|
|
var ast = parse(src, opts);
|
|
var result = {
|
|
chunks: src.split(''),
|
|
toString: function () {
|
|
return result.chunks.join('');
|
|
},
|
|
inspect: function () {
|
|
return result.toString();
|
|
}
|
|
};
|
|
var index = 0;
|
|
(function walk(node, parent) {
|
|
insertHelpers(node, parent, result.chunks);
|
|
node = addCapturer(node, result.chunks);
|
|
Object.keys(node).forEach(function (key) {
|
|
if (key === 'parent')
|
|
return;
|
|
var child = node[key];
|
|
if (Array.isArray(child)) {
|
|
child.forEach(function (c) {
|
|
if (c && typeof c.type === 'string') {
|
|
walk(c, node);
|
|
}
|
|
});
|
|
}
|
|
else if (child && typeof child.type === 'string') {
|
|
insertHelpers(child, node, result.chunks);
|
|
walk(child, node);
|
|
}
|
|
});
|
|
fn(node);
|
|
})(ast, undefined);
|
|
return result;
|
|
}
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = default_1;
|
|
function insertHelpers(node, parent, chunks) {
|
|
if (!node.range)
|
|
return;
|
|
node.parent = parent;
|
|
node.source = function () {
|
|
return chunks.slice(node.range[0], node.range[1]).join('');
|
|
};
|
|
if (node.update && typeof node.update === 'object') {
|
|
var prev = node.update;
|
|
Object.keys(prev).forEach(function (key) {
|
|
update[key] = prev[key];
|
|
});
|
|
node.update = update;
|
|
}
|
|
else {
|
|
node.update = update;
|
|
}
|
|
function update(s) {
|
|
chunks[node.range[0]] = s;
|
|
for (var i = node.range[0] + 1; i < node.range[1]; i++) {
|
|
chunks[i] = '';
|
|
}
|
|
}
|
|
}
|
|
function addCapturer(node, chunks) {
|
|
// Check if the node is a function declaration named 'draw'
|
|
if (node.type === 'FunctionDeclaration' &&
|
|
node.id &&
|
|
node.id.name === 'draw') {
|
|
console.log('#Found draw function:', node);
|
|
var hasCapturerStart_1 = false;
|
|
var hasCapturerEnd_1 = false;
|
|
(function checkCapturerCalls(bodyNode) {
|
|
if (bodyNode.type === 'CallExpression' &&
|
|
bodyNode.callee &&
|
|
bodyNode.callee.type === 'Identifier') {
|
|
if (bodyNode.callee.name === 'capturer_start') {
|
|
hasCapturerStart_1 = true;
|
|
}
|
|
else if (bodyNode.callee.name === 'capturer_end') {
|
|
hasCapturerEnd_1 = true;
|
|
}
|
|
}
|
|
if (bodyNode.body && Array.isArray(bodyNode.body)) {
|
|
bodyNode.body.forEach(checkCapturerCalls);
|
|
}
|
|
})(node.body);
|
|
if (!hasCapturerStart_1) {
|
|
console.log('capturer_start() not found in draw function, adding it.');
|
|
var startInsertPos = node.body.range[0] + 1;
|
|
chunks.splice(startInsertPos, 0, 'capturer_start();\n');
|
|
}
|
|
if (!hasCapturerEnd_1) {
|
|
console.log('capturer_end() not found in draw function, adding it.');
|
|
var endInsertPos = node.body.range[1] - 1;
|
|
chunks.splice(endInsertPos, 0, '\ncapturer_end();');
|
|
}
|
|
}
|
|
return node;
|
|
}
|
|
|
|
|
|
/***/ }),
|
|
/* 204 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
|
|
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
|
|
|
|
Redistribution and use in source and binary forms, with or without
|
|
modification, are permitted provided that the following conditions are met:
|
|
|
|
* Redistributions of source code must retain the above copyright
|
|
notice, this list of conditions and the following disclaimer.
|
|
* Redistributions in binary form must reproduce the above copyright
|
|
notice, this list of conditions and the following disclaimer in the
|
|
documentation and/or other materials provided with the distribution.
|
|
|
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
|
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
|
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
*/
|
|
|
|
(function (root, factory) {
|
|
'use strict';
|
|
|
|
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
|
|
// Rhino, and plain browser loading.
|
|
|
|
/* istanbul ignore next */
|
|
if (true) {
|
|
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
|
|
} else if (typeof exports !== 'undefined') {
|
|
factory(exports);
|
|
} else {
|
|
factory((root.esprima = {}));
|
|
}
|
|
}(this, function (exports) {
|
|
'use strict';
|
|
|
|
var Token,
|
|
TokenName,
|
|
FnExprTokens,
|
|
Syntax,
|
|
PlaceHolders,
|
|
Messages,
|
|
Regex,
|
|
source,
|
|
strict,
|
|
index,
|
|
lineNumber,
|
|
lineStart,
|
|
hasLineTerminator,
|
|
lastIndex,
|
|
lastLineNumber,
|
|
lastLineStart,
|
|
startIndex,
|
|
startLineNumber,
|
|
startLineStart,
|
|
scanning,
|
|
length,
|
|
lookahead,
|
|
state,
|
|
extra,
|
|
isBindingElement,
|
|
isAssignmentTarget,
|
|
firstCoverInitializedNameError;
|
|
|
|
Token = {
|
|
BooleanLiteral: 1,
|
|
EOF: 2,
|
|
Identifier: 3,
|
|
Keyword: 4,
|
|
NullLiteral: 5,
|
|
NumericLiteral: 6,
|
|
Punctuator: 7,
|
|
StringLiteral: 8,
|
|
RegularExpression: 9,
|
|
Template: 10
|
|
};
|
|
|
|
TokenName = {};
|
|
TokenName[Token.BooleanLiteral] = 'Boolean';
|
|
TokenName[Token.EOF] = '<end>';
|
|
TokenName[Token.Identifier] = 'Identifier';
|
|
TokenName[Token.Keyword] = 'Keyword';
|
|
TokenName[Token.NullLiteral] = 'Null';
|
|
TokenName[Token.NumericLiteral] = 'Numeric';
|
|
TokenName[Token.Punctuator] = 'Punctuator';
|
|
TokenName[Token.StringLiteral] = 'String';
|
|
TokenName[Token.RegularExpression] = 'RegularExpression';
|
|
TokenName[Token.Template] = 'Template';
|
|
|
|
// A function following one of those tokens is an expression.
|
|
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
|
|
'return', 'case', 'delete', 'throw', 'void',
|
|
// assignment operators
|
|
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
|
|
'&=', '|=', '^=', ',',
|
|
// binary/unary operators
|
|
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
|
|
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
|
|
'<=', '<', '>', '!=', '!=='];
|
|
|
|
Syntax = {
|
|
AssignmentExpression: 'AssignmentExpression',
|
|
AssignmentPattern: 'AssignmentPattern',
|
|
ArrayExpression: 'ArrayExpression',
|
|
ArrayPattern: 'ArrayPattern',
|
|
ArrowFunctionExpression: 'ArrowFunctionExpression',
|
|
BlockStatement: 'BlockStatement',
|
|
BinaryExpression: 'BinaryExpression',
|
|
BreakStatement: 'BreakStatement',
|
|
CallExpression: 'CallExpression',
|
|
CatchClause: 'CatchClause',
|
|
ClassBody: 'ClassBody',
|
|
ClassDeclaration: 'ClassDeclaration',
|
|
ClassExpression: 'ClassExpression',
|
|
ConditionalExpression: 'ConditionalExpression',
|
|
ContinueStatement: 'ContinueStatement',
|
|
DoWhileStatement: 'DoWhileStatement',
|
|
DebuggerStatement: 'DebuggerStatement',
|
|
EmptyStatement: 'EmptyStatement',
|
|
ExportAllDeclaration: 'ExportAllDeclaration',
|
|
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
|
|
ExportNamedDeclaration: 'ExportNamedDeclaration',
|
|
ExportSpecifier: 'ExportSpecifier',
|
|
ExpressionStatement: 'ExpressionStatement',
|
|
ForStatement: 'ForStatement',
|
|
ForOfStatement: 'ForOfStatement',
|
|
ForInStatement: 'ForInStatement',
|
|
FunctionDeclaration: 'FunctionDeclaration',
|
|
FunctionExpression: 'FunctionExpression',
|
|
Identifier: 'Identifier',
|
|
IfStatement: 'IfStatement',
|
|
ImportDeclaration: 'ImportDeclaration',
|
|
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
|
|
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
|
|
ImportSpecifier: 'ImportSpecifier',
|
|
Literal: 'Literal',
|
|
LabeledStatement: 'LabeledStatement',
|
|
LogicalExpression: 'LogicalExpression',
|
|
MemberExpression: 'MemberExpression',
|
|
MetaProperty: 'MetaProperty',
|
|
MethodDefinition: 'MethodDefinition',
|
|
NewExpression: 'NewExpression',
|
|
ObjectExpression: 'ObjectExpression',
|
|
ObjectPattern: 'ObjectPattern',
|
|
Program: 'Program',
|
|
Property: 'Property',
|
|
RestElement: 'RestElement',
|
|
ReturnStatement: 'ReturnStatement',
|
|
SequenceExpression: 'SequenceExpression',
|
|
SpreadElement: 'SpreadElement',
|
|
Super: 'Super',
|
|
SwitchCase: 'SwitchCase',
|
|
SwitchStatement: 'SwitchStatement',
|
|
TaggedTemplateExpression: 'TaggedTemplateExpression',
|
|
TemplateElement: 'TemplateElement',
|
|
TemplateLiteral: 'TemplateLiteral',
|
|
ThisExpression: 'ThisExpression',
|
|
ThrowStatement: 'ThrowStatement',
|
|
TryStatement: 'TryStatement',
|
|
UnaryExpression: 'UnaryExpression',
|
|
UpdateExpression: 'UpdateExpression',
|
|
VariableDeclaration: 'VariableDeclaration',
|
|
VariableDeclarator: 'VariableDeclarator',
|
|
WhileStatement: 'WhileStatement',
|
|
WithStatement: 'WithStatement',
|
|
YieldExpression: 'YieldExpression'
|
|
};
|
|
|
|
PlaceHolders = {
|
|
ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
|
|
};
|
|
|
|
// Error messages should be identical to V8.
|
|
Messages = {
|
|
UnexpectedToken: 'Unexpected token %0',
|
|
UnexpectedNumber: 'Unexpected number',
|
|
UnexpectedString: 'Unexpected string',
|
|
UnexpectedIdentifier: 'Unexpected identifier',
|
|
UnexpectedReserved: 'Unexpected reserved word',
|
|
UnexpectedTemplate: 'Unexpected quasi %0',
|
|
UnexpectedEOS: 'Unexpected end of input',
|
|
NewlineAfterThrow: 'Illegal newline after throw',
|
|
InvalidRegExp: 'Invalid regular expression',
|
|
UnterminatedRegExp: 'Invalid regular expression: missing /',
|
|
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
|
|
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
|
|
InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
|
|
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
|
|
NoCatchOrFinally: 'Missing catch or finally after try',
|
|
UnknownLabel: 'Undefined label \'%0\'',
|
|
Redeclaration: '%0 \'%1\' has already been declared',
|
|
IllegalContinue: 'Illegal continue statement',
|
|
IllegalBreak: 'Illegal break statement',
|
|
IllegalReturn: 'Illegal return statement',
|
|
StrictModeWith: 'Strict mode code may not include a with statement',
|
|
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
|
|
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
|
|
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
|
|
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
|
|
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
|
|
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
|
|
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
|
|
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
|
|
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
|
|
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
|
|
StrictReservedWord: 'Use of future reserved word in strict mode',
|
|
TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
|
|
ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
|
|
DefaultRestParameter: 'Unexpected token =',
|
|
ObjectPatternAsRestParameter: 'Unexpected token {',
|
|
DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
|
|
ConstructorSpecialMethod: 'Class constructor may not be an accessor',
|
|
DuplicateConstructor: 'A class may only have one constructor',
|
|
StaticPrototype: 'Classes may not have static property named prototype',
|
|
MissingFromClause: 'Unexpected token',
|
|
NoAsAfterImportNamespace: 'Unexpected token',
|
|
InvalidModuleSpecifier: 'Unexpected token',
|
|
IllegalImportDeclaration: 'Unexpected token',
|
|
IllegalExportDeclaration: 'Unexpected token',
|
|
DuplicateBinding: 'Duplicate binding %0'
|
|
};
|
|
|
|
// See also tools/generate-unicode-regex.js.
|
|
Regex = {
|
|
// ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
|
|
NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
|
|
|
|
// ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
|
|
NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
|
|
};
|
|
|
|
// Ensure the condition is true, otherwise throw an error.
|
|
// This is only to have a better contract semantic, i.e. another safety net
|
|
// to catch a logic error. The condition shall be fulfilled in normal case.
|
|
// Do NOT use this to enforce a certain condition on any user input.
|
|
|
|
function assert(condition, message) {
|
|
/* istanbul ignore if */
|
|
if (!condition) {
|
|
throw new Error('ASSERT: ' + message);
|
|
}
|
|
}
|
|
|
|
function isDecimalDigit(ch) {
|
|
return (ch >= 0x30 && ch <= 0x39); // 0..9
|
|
}
|
|
|
|
function isHexDigit(ch) {
|
|
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
|
|
}
|
|
|
|
function isOctalDigit(ch) {
|
|
return '01234567'.indexOf(ch) >= 0;
|
|
}
|
|
|
|
function octalToDecimal(ch) {
|
|
// \0 is not octal escape sequence
|
|
var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
|
|
|
|
if (index < length && isOctalDigit(source[index])) {
|
|
octal = true;
|
|
code = code * 8 + '01234567'.indexOf(source[index++]);
|
|
|
|
// 3 digits are only allowed when string starts
|
|
// with 0, 1, 2, 3
|
|
if ('0123'.indexOf(ch) >= 0 &&
|
|
index < length &&
|
|
isOctalDigit(source[index])) {
|
|
code = code * 8 + '01234567'.indexOf(source[index++]);
|
|
}
|
|
}
|
|
|
|
return {
|
|
code: code,
|
|
octal: octal
|
|
};
|
|
}
|
|
|
|
// ECMA-262 11.2 White Space
|
|
|
|
function isWhiteSpace(ch) {
|
|
return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
|
|
(ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
|
|
}
|
|
|
|
// ECMA-262 11.3 Line Terminators
|
|
|
|
function isLineTerminator(ch) {
|
|
return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
|
|
}
|
|
|
|
// ECMA-262 11.6 Identifier Names and Identifiers
|
|
|
|
function fromCodePoint(cp) {
|
|
return (cp < 0x10000) ? String.fromCharCode(cp) :
|
|
String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
|
|
String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
|
|
}
|
|
|
|
function isIdentifierStart(ch) {
|
|
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
|
|
(ch >= 0x41 && ch <= 0x5A) || // A..Z
|
|
(ch >= 0x61 && ch <= 0x7A) || // a..z
|
|
(ch === 0x5C) || // \ (backslash)
|
|
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
|
|
}
|
|
|
|
function isIdentifierPart(ch) {
|
|
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
|
|
(ch >= 0x41 && ch <= 0x5A) || // A..Z
|
|
(ch >= 0x61 && ch <= 0x7A) || // a..z
|
|
(ch >= 0x30 && ch <= 0x39) || // 0..9
|
|
(ch === 0x5C) || // \ (backslash)
|
|
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
|
|
}
|
|
|
|
// ECMA-262 11.6.2.2 Future Reserved Words
|
|
|
|
function isFutureReservedWord(id) {
|
|
switch (id) {
|
|
case 'enum':
|
|
case 'export':
|
|
case 'import':
|
|
case 'super':
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isStrictModeReservedWord(id) {
|
|
switch (id) {
|
|
case 'implements':
|
|
case 'interface':
|
|
case 'package':
|
|
case 'private':
|
|
case 'protected':
|
|
case 'public':
|
|
case 'static':
|
|
case 'yield':
|
|
case 'let':
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isRestrictedWord(id) {
|
|
return id === 'eval' || id === 'arguments';
|
|
}
|
|
|
|
// ECMA-262 11.6.2.1 Keywords
|
|
|
|
function isKeyword(id) {
|
|
switch (id.length) {
|
|
case 2:
|
|
return (id === 'if') || (id === 'in') || (id === 'do');
|
|
case 3:
|
|
return (id === 'var') || (id === 'for') || (id === 'new') ||
|
|
(id === 'try') || (id === 'let');
|
|
case 4:
|
|
return (id === 'this') || (id === 'else') || (id === 'case') ||
|
|
(id === 'void') || (id === 'with') || (id === 'enum');
|
|
case 5:
|
|
return (id === 'while') || (id === 'break') || (id === 'catch') ||
|
|
(id === 'throw') || (id === 'const') || (id === 'yield') ||
|
|
(id === 'class') || (id === 'super');
|
|
case 6:
|
|
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
|
|
(id === 'switch') || (id === 'export') || (id === 'import');
|
|
case 7:
|
|
return (id === 'default') || (id === 'finally') || (id === 'extends');
|
|
case 8:
|
|
return (id === 'function') || (id === 'continue') || (id === 'debugger');
|
|
case 10:
|
|
return (id === 'instanceof');
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ECMA-262 11.4 Comments
|
|
|
|
function addComment(type, value, start, end, loc) {
|
|
var comment;
|
|
|
|
assert(typeof start === 'number', 'Comment must have valid position');
|
|
|
|
state.lastCommentStart = start;
|
|
|
|
comment = {
|
|
type: type,
|
|
value: value
|
|
};
|
|
if (extra.range) {
|
|
comment.range = [start, end];
|
|
}
|
|
if (extra.loc) {
|
|
comment.loc = loc;
|
|
}
|
|
extra.comments.push(comment);
|
|
if (extra.attachComment) {
|
|
extra.leadingComments.push(comment);
|
|
extra.trailingComments.push(comment);
|
|
}
|
|
if (extra.tokenize) {
|
|
comment.type = comment.type + 'Comment';
|
|
if (extra.delegate) {
|
|
comment = extra.delegate(comment);
|
|
}
|
|
extra.tokens.push(comment);
|
|
}
|
|
}
|
|
|
|
function skipSingleLineComment(offset) {
|
|
var start, loc, ch, comment;
|
|
|
|
start = index - offset;
|
|
loc = {
|
|
start: {
|
|
line: lineNumber,
|
|
column: index - lineStart - offset
|
|
}
|
|
};
|
|
|
|
while (index < length) {
|
|
ch = source.charCodeAt(index);
|
|
++index;
|
|
if (isLineTerminator(ch)) {
|
|
hasLineTerminator = true;
|
|
if (extra.comments) {
|
|
comment = source.slice(start + offset, index - 1);
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart - 1
|
|
};
|
|
addComment('Line', comment, start, index - 1, loc);
|
|
}
|
|
if (ch === 13 && source.charCodeAt(index) === 10) {
|
|
++index;
|
|
}
|
|
++lineNumber;
|
|
lineStart = index;
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (extra.comments) {
|
|
comment = source.slice(start + offset, index);
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
};
|
|
addComment('Line', comment, start, index, loc);
|
|
}
|
|
}
|
|
|
|
function skipMultiLineComment() {
|
|
var start, loc, ch, comment;
|
|
|
|
if (extra.comments) {
|
|
start = index - 2;
|
|
loc = {
|
|
start: {
|
|
line: lineNumber,
|
|
column: index - lineStart - 2
|
|
}
|
|
};
|
|
}
|
|
|
|
while (index < length) {
|
|
ch = source.charCodeAt(index);
|
|
if (isLineTerminator(ch)) {
|
|
if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
|
|
++index;
|
|
}
|
|
hasLineTerminator = true;
|
|
++lineNumber;
|
|
++index;
|
|
lineStart = index;
|
|
} else if (ch === 0x2A) {
|
|
// Block comment ends with '*/'.
|
|
if (source.charCodeAt(index + 1) === 0x2F) {
|
|
++index;
|
|
++index;
|
|
if (extra.comments) {
|
|
comment = source.slice(start + 2, index - 2);
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
};
|
|
addComment('Block', comment, start, index, loc);
|
|
}
|
|
return;
|
|
}
|
|
++index;
|
|
} else {
|
|
++index;
|
|
}
|
|
}
|
|
|
|
// Ran off the end of the file - the whole thing is a comment
|
|
if (extra.comments) {
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
};
|
|
comment = source.slice(start + 2, index);
|
|
addComment('Block', comment, start, index, loc);
|
|
}
|
|
tolerateUnexpectedToken();
|
|
}
|
|
|
|
function skipComment() {
|
|
var ch, start;
|
|
hasLineTerminator = false;
|
|
|
|
start = (index === 0);
|
|
while (index < length) {
|
|
ch = source.charCodeAt(index);
|
|
|
|
if (isWhiteSpace(ch)) {
|
|
++index;
|
|
} else if (isLineTerminator(ch)) {
|
|
hasLineTerminator = true;
|
|
++index;
|
|
if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
|
|
++index;
|
|
}
|
|
++lineNumber;
|
|
lineStart = index;
|
|
start = true;
|
|
} else if (ch === 0x2F) { // U+002F is '/'
|
|
ch = source.charCodeAt(index + 1);
|
|
if (ch === 0x2F) {
|
|
++index;
|
|
++index;
|
|
skipSingleLineComment(2);
|
|
start = true;
|
|
} else if (ch === 0x2A) { // U+002A is '*'
|
|
++index;
|
|
++index;
|
|
skipMultiLineComment();
|
|
} else {
|
|
break;
|
|
}
|
|
} else if (start && ch === 0x2D) { // U+002D is '-'
|
|
// U+003E is '>'
|
|
if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
|
|
// '-->' is a single-line comment
|
|
index += 3;
|
|
skipSingleLineComment(3);
|
|
} else {
|
|
break;
|
|
}
|
|
} else if (ch === 0x3C) { // U+003C is '<'
|
|
if (source.slice(index + 1, index + 4) === '!--') {
|
|
++index; // `<`
|
|
++index; // `!`
|
|
++index; // `-`
|
|
++index; // `-`
|
|
skipSingleLineComment(4);
|
|
} else {
|
|
break;
|
|
}
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
function scanHexEscape(prefix) {
|
|
var i, len, ch, code = 0;
|
|
|
|
len = (prefix === 'u') ? 4 : 2;
|
|
for (i = 0; i < len; ++i) {
|
|
if (index < length && isHexDigit(source[index])) {
|
|
ch = source[index++];
|
|
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
|
|
} else {
|
|
return '';
|
|
}
|
|
}
|
|
return String.fromCharCode(code);
|
|
}
|
|
|
|
function scanUnicodeCodePointEscape() {
|
|
var ch, code;
|
|
|
|
ch = source[index];
|
|
code = 0;
|
|
|
|
// At least, one hex digit is required.
|
|
if (ch === '}') {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
while (index < length) {
|
|
ch = source[index++];
|
|
if (!isHexDigit(ch)) {
|
|
break;
|
|
}
|
|
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
|
|
}
|
|
|
|
if (code > 0x10FFFF || ch !== '}') {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
return fromCodePoint(code);
|
|
}
|
|
|
|
function codePointAt(i) {
|
|
var cp, first, second;
|
|
|
|
cp = source.charCodeAt(i);
|
|
if (cp >= 0xD800 && cp <= 0xDBFF) {
|
|
second = source.charCodeAt(i + 1);
|
|
if (second >= 0xDC00 && second <= 0xDFFF) {
|
|
first = cp;
|
|
cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
|
|
}
|
|
}
|
|
|
|
return cp;
|
|
}
|
|
|
|
function getComplexIdentifier() {
|
|
var cp, ch, id;
|
|
|
|
cp = codePointAt(index);
|
|
id = fromCodePoint(cp);
|
|
index += id.length;
|
|
|
|
// '\u' (U+005C, U+0075) denotes an escaped character.
|
|
if (cp === 0x5C) {
|
|
if (source.charCodeAt(index) !== 0x75) {
|
|
throwUnexpectedToken();
|
|
}
|
|
++index;
|
|
if (source[index] === '{') {
|
|
++index;
|
|
ch = scanUnicodeCodePointEscape();
|
|
} else {
|
|
ch = scanHexEscape('u');
|
|
cp = ch.charCodeAt(0);
|
|
if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
|
|
throwUnexpectedToken();
|
|
}
|
|
}
|
|
id = ch;
|
|
}
|
|
|
|
while (index < length) {
|
|
cp = codePointAt(index);
|
|
if (!isIdentifierPart(cp)) {
|
|
break;
|
|
}
|
|
ch = fromCodePoint(cp);
|
|
id += ch;
|
|
index += ch.length;
|
|
|
|
// '\u' (U+005C, U+0075) denotes an escaped character.
|
|
if (cp === 0x5C) {
|
|
id = id.substr(0, id.length - 1);
|
|
if (source.charCodeAt(index) !== 0x75) {
|
|
throwUnexpectedToken();
|
|
}
|
|
++index;
|
|
if (source[index] === '{') {
|
|
++index;
|
|
ch = scanUnicodeCodePointEscape();
|
|
} else {
|
|
ch = scanHexEscape('u');
|
|
cp = ch.charCodeAt(0);
|
|
if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
|
|
throwUnexpectedToken();
|
|
}
|
|
}
|
|
id += ch;
|
|
}
|
|
}
|
|
|
|
return id;
|
|
}
|
|
|
|
function getIdentifier() {
|
|
var start, ch;
|
|
|
|
start = index++;
|
|
while (index < length) {
|
|
ch = source.charCodeAt(index);
|
|
if (ch === 0x5C) {
|
|
// Blackslash (U+005C) marks Unicode escape sequence.
|
|
index = start;
|
|
return getComplexIdentifier();
|
|
} else if (ch >= 0xD800 && ch < 0xDFFF) {
|
|
// Need to handle surrogate pairs.
|
|
index = start;
|
|
return getComplexIdentifier();
|
|
}
|
|
if (isIdentifierPart(ch)) {
|
|
++index;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
return source.slice(start, index);
|
|
}
|
|
|
|
function scanIdentifier() {
|
|
var start, id, type;
|
|
|
|
start = index;
|
|
|
|
// Backslash (U+005C) starts an escaped character.
|
|
id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();
|
|
|
|
// There is no keyword or literal with only one character.
|
|
// Thus, it must be an identifier.
|
|
if (id.length === 1) {
|
|
type = Token.Identifier;
|
|
} else if (isKeyword(id)) {
|
|
type = Token.Keyword;
|
|
} else if (id === 'null') {
|
|
type = Token.NullLiteral;
|
|
} else if (id === 'true' || id === 'false') {
|
|
type = Token.BooleanLiteral;
|
|
} else {
|
|
type = Token.Identifier;
|
|
}
|
|
|
|
return {
|
|
type: type,
|
|
value: id,
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
|
|
// ECMA-262 11.7 Punctuators
|
|
|
|
function scanPunctuator() {
|
|
var token, str;
|
|
|
|
token = {
|
|
type: Token.Punctuator,
|
|
value: '',
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: index,
|
|
end: index
|
|
};
|
|
|
|
// Check for most common single-character punctuators.
|
|
str = source[index];
|
|
switch (str) {
|
|
|
|
case '(':
|
|
if (extra.tokenize) {
|
|
extra.openParenToken = extra.tokenValues.length;
|
|
}
|
|
++index;
|
|
break;
|
|
|
|
case '{':
|
|
if (extra.tokenize) {
|
|
extra.openCurlyToken = extra.tokenValues.length;
|
|
}
|
|
state.curlyStack.push('{');
|
|
++index;
|
|
break;
|
|
|
|
case '.':
|
|
++index;
|
|
if (source[index] === '.' && source[index + 1] === '.') {
|
|
// Spread operator: ...
|
|
index += 2;
|
|
str = '...';
|
|
}
|
|
break;
|
|
|
|
case '}':
|
|
++index;
|
|
state.curlyStack.pop();
|
|
break;
|
|
case ')':
|
|
case ';':
|
|
case ',':
|
|
case '[':
|
|
case ']':
|
|
case ':':
|
|
case '?':
|
|
case '~':
|
|
++index;
|
|
break;
|
|
|
|
default:
|
|
// 4-character punctuator.
|
|
str = source.substr(index, 4);
|
|
if (str === '>>>=') {
|
|
index += 4;
|
|
} else {
|
|
|
|
// 3-character punctuators.
|
|
str = str.substr(0, 3);
|
|
if (str === '===' || str === '!==' || str === '>>>' ||
|
|
str === '<<=' || str === '>>=') {
|
|
index += 3;
|
|
} else {
|
|
|
|
// 2-character punctuators.
|
|
str = str.substr(0, 2);
|
|
if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
|
|
str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
|
|
str === '++' || str === '--' || str === '<<' || str === '>>' ||
|
|
str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
|
|
str === '<=' || str === '>=' || str === '=>') {
|
|
index += 2;
|
|
} else {
|
|
|
|
// 1-character punctuators.
|
|
str = source[index];
|
|
if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
|
|
++index;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (index === token.start) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
token.end = index;
|
|
token.value = str;
|
|
return token;
|
|
}
|
|
|
|
// ECMA-262 11.8.3 Numeric Literals
|
|
|
|
function scanHexLiteral(start) {
|
|
var number = '';
|
|
|
|
while (index < length) {
|
|
if (!isHexDigit(source[index])) {
|
|
break;
|
|
}
|
|
number += source[index++];
|
|
}
|
|
|
|
if (number.length === 0) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
if (isIdentifierStart(source.charCodeAt(index))) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
return {
|
|
type: Token.NumericLiteral,
|
|
value: parseInt('0x' + number, 16),
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
function scanBinaryLiteral(start) {
|
|
var ch, number;
|
|
|
|
number = '';
|
|
|
|
while (index < length) {
|
|
ch = source[index];
|
|
if (ch !== '0' && ch !== '1') {
|
|
break;
|
|
}
|
|
number += source[index++];
|
|
}
|
|
|
|
if (number.length === 0) {
|
|
// only 0b or 0B
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
if (index < length) {
|
|
ch = source.charCodeAt(index);
|
|
/* istanbul ignore else */
|
|
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
|
|
throwUnexpectedToken();
|
|
}
|
|
}
|
|
|
|
return {
|
|
type: Token.NumericLiteral,
|
|
value: parseInt(number, 2),
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
function scanOctalLiteral(prefix, start) {
|
|
var number, octal;
|
|
|
|
if (isOctalDigit(prefix)) {
|
|
octal = true;
|
|
number = '0' + source[index++];
|
|
} else {
|
|
octal = false;
|
|
++index;
|
|
number = '';
|
|
}
|
|
|
|
while (index < length) {
|
|
if (!isOctalDigit(source[index])) {
|
|
break;
|
|
}
|
|
number += source[index++];
|
|
}
|
|
|
|
if (!octal && number.length === 0) {
|
|
// only 0o or 0O
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
return {
|
|
type: Token.NumericLiteral,
|
|
value: parseInt(number, 8),
|
|
octal: octal,
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
function isImplicitOctalLiteral() {
|
|
var i, ch;
|
|
|
|
// Implicit octal, unless there is a non-octal digit.
|
|
// (Annex B.1.1 on Numeric Literals)
|
|
for (i = index + 1; i < length; ++i) {
|
|
ch = source[i];
|
|
if (ch === '8' || ch === '9') {
|
|
return false;
|
|
}
|
|
if (!isOctalDigit(ch)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
function scanNumericLiteral() {
|
|
var number, start, ch;
|
|
|
|
ch = source[index];
|
|
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
|
|
'Numeric literal must start with a decimal digit or a decimal point');
|
|
|
|
start = index;
|
|
number = '';
|
|
if (ch !== '.') {
|
|
number = source[index++];
|
|
ch = source[index];
|
|
|
|
// Hex number starts with '0x'.
|
|
// Octal number starts with '0'.
|
|
// Octal number in ES6 starts with '0o'.
|
|
// Binary number in ES6 starts with '0b'.
|
|
if (number === '0') {
|
|
if (ch === 'x' || ch === 'X') {
|
|
++index;
|
|
return scanHexLiteral(start);
|
|
}
|
|
if (ch === 'b' || ch === 'B') {
|
|
++index;
|
|
return scanBinaryLiteral(start);
|
|
}
|
|
if (ch === 'o' || ch === 'O') {
|
|
return scanOctalLiteral(ch, start);
|
|
}
|
|
|
|
if (isOctalDigit(ch)) {
|
|
if (isImplicitOctalLiteral()) {
|
|
return scanOctalLiteral(ch, start);
|
|
}
|
|
}
|
|
}
|
|
|
|
while (isDecimalDigit(source.charCodeAt(index))) {
|
|
number += source[index++];
|
|
}
|
|
ch = source[index];
|
|
}
|
|
|
|
if (ch === '.') {
|
|
number += source[index++];
|
|
while (isDecimalDigit(source.charCodeAt(index))) {
|
|
number += source[index++];
|
|
}
|
|
ch = source[index];
|
|
}
|
|
|
|
if (ch === 'e' || ch === 'E') {
|
|
number += source[index++];
|
|
|
|
ch = source[index];
|
|
if (ch === '+' || ch === '-') {
|
|
number += source[index++];
|
|
}
|
|
if (isDecimalDigit(source.charCodeAt(index))) {
|
|
while (isDecimalDigit(source.charCodeAt(index))) {
|
|
number += source[index++];
|
|
}
|
|
} else {
|
|
throwUnexpectedToken();
|
|
}
|
|
}
|
|
|
|
if (isIdentifierStart(source.charCodeAt(index))) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
return {
|
|
type: Token.NumericLiteral,
|
|
value: parseFloat(number),
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
// ECMA-262 11.8.4 String Literals
|
|
|
|
function scanStringLiteral() {
|
|
var str = '', quote, start, ch, unescaped, octToDec, octal = false;
|
|
|
|
quote = source[index];
|
|
assert((quote === '\'' || quote === '"'),
|
|
'String literal must starts with a quote');
|
|
|
|
start = index;
|
|
++index;
|
|
|
|
while (index < length) {
|
|
ch = source[index++];
|
|
|
|
if (ch === quote) {
|
|
quote = '';
|
|
break;
|
|
} else if (ch === '\\') {
|
|
ch = source[index++];
|
|
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
|
|
switch (ch) {
|
|
case 'u':
|
|
case 'x':
|
|
if (source[index] === '{') {
|
|
++index;
|
|
str += scanUnicodeCodePointEscape();
|
|
} else {
|
|
unescaped = scanHexEscape(ch);
|
|
if (!unescaped) {
|
|
throw throwUnexpectedToken();
|
|
}
|
|
str += unescaped;
|
|
}
|
|
break;
|
|
case 'n':
|
|
str += '\n';
|
|
break;
|
|
case 'r':
|
|
str += '\r';
|
|
break;
|
|
case 't':
|
|
str += '\t';
|
|
break;
|
|
case 'b':
|
|
str += '\b';
|
|
break;
|
|
case 'f':
|
|
str += '\f';
|
|
break;
|
|
case 'v':
|
|
str += '\x0B';
|
|
break;
|
|
case '8':
|
|
case '9':
|
|
str += ch;
|
|
tolerateUnexpectedToken();
|
|
break;
|
|
|
|
default:
|
|
if (isOctalDigit(ch)) {
|
|
octToDec = octalToDecimal(ch);
|
|
|
|
octal = octToDec.octal || octal;
|
|
str += String.fromCharCode(octToDec.code);
|
|
} else {
|
|
str += ch;
|
|
}
|
|
break;
|
|
}
|
|
} else {
|
|
++lineNumber;
|
|
if (ch === '\r' && source[index] === '\n') {
|
|
++index;
|
|
}
|
|
lineStart = index;
|
|
}
|
|
} else if (isLineTerminator(ch.charCodeAt(0))) {
|
|
break;
|
|
} else {
|
|
str += ch;
|
|
}
|
|
}
|
|
|
|
if (quote !== '') {
|
|
index = start;
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
return {
|
|
type: Token.StringLiteral,
|
|
value: str,
|
|
octal: octal,
|
|
lineNumber: startLineNumber,
|
|
lineStart: startLineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
// ECMA-262 11.8.6 Template Literal Lexical Components
|
|
|
|
function scanTemplate() {
|
|
var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
|
|
|
|
terminated = false;
|
|
tail = false;
|
|
start = index;
|
|
head = (source[index] === '`');
|
|
rawOffset = 2;
|
|
|
|
++index;
|
|
|
|
while (index < length) {
|
|
ch = source[index++];
|
|
if (ch === '`') {
|
|
rawOffset = 1;
|
|
tail = true;
|
|
terminated = true;
|
|
break;
|
|
} else if (ch === '$') {
|
|
if (source[index] === '{') {
|
|
state.curlyStack.push('${');
|
|
++index;
|
|
terminated = true;
|
|
break;
|
|
}
|
|
cooked += ch;
|
|
} else if (ch === '\\') {
|
|
ch = source[index++];
|
|
if (!isLineTerminator(ch.charCodeAt(0))) {
|
|
switch (ch) {
|
|
case 'n':
|
|
cooked += '\n';
|
|
break;
|
|
case 'r':
|
|
cooked += '\r';
|
|
break;
|
|
case 't':
|
|
cooked += '\t';
|
|
break;
|
|
case 'u':
|
|
case 'x':
|
|
if (source[index] === '{') {
|
|
++index;
|
|
cooked += scanUnicodeCodePointEscape();
|
|
} else {
|
|
restore = index;
|
|
unescaped = scanHexEscape(ch);
|
|
if (unescaped) {
|
|
cooked += unescaped;
|
|
} else {
|
|
index = restore;
|
|
cooked += ch;
|
|
}
|
|
}
|
|
break;
|
|
case 'b':
|
|
cooked += '\b';
|
|
break;
|
|
case 'f':
|
|
cooked += '\f';
|
|
break;
|
|
case 'v':
|
|
cooked += '\v';
|
|
break;
|
|
|
|
default:
|
|
if (ch === '0') {
|
|
if (isDecimalDigit(source.charCodeAt(index))) {
|
|
// Illegal: \01 \02 and so on
|
|
throwError(Messages.TemplateOctalLiteral);
|
|
}
|
|
cooked += '\0';
|
|
} else if (isOctalDigit(ch)) {
|
|
// Illegal: \1 \2
|
|
throwError(Messages.TemplateOctalLiteral);
|
|
} else {
|
|
cooked += ch;
|
|
}
|
|
break;
|
|
}
|
|
} else {
|
|
++lineNumber;
|
|
if (ch === '\r' && source[index] === '\n') {
|
|
++index;
|
|
}
|
|
lineStart = index;
|
|
}
|
|
} else if (isLineTerminator(ch.charCodeAt(0))) {
|
|
++lineNumber;
|
|
if (ch === '\r' && source[index] === '\n') {
|
|
++index;
|
|
}
|
|
lineStart = index;
|
|
cooked += '\n';
|
|
} else {
|
|
cooked += ch;
|
|
}
|
|
}
|
|
|
|
if (!terminated) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
if (!head) {
|
|
state.curlyStack.pop();
|
|
}
|
|
|
|
return {
|
|
type: Token.Template,
|
|
value: {
|
|
cooked: cooked,
|
|
raw: source.slice(start + 1, index - rawOffset)
|
|
},
|
|
head: head,
|
|
tail: tail,
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
// ECMA-262 11.8.5 Regular Expression Literals
|
|
|
|
function testRegExp(pattern, flags) {
|
|
// The BMP character to use as a replacement for astral symbols when
|
|
// translating an ES6 "u"-flagged pattern to an ES5-compatible
|
|
// approximation.
|
|
// Note: replacing with '\uFFFF' enables false positives in unlikely
|
|
// scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
|
|
// pattern that would not be detected by this substitution.
|
|
var astralSubstitute = '\uFFFF',
|
|
tmp = pattern;
|
|
|
|
if (flags.indexOf('u') >= 0) {
|
|
tmp = tmp
|
|
// Replace every Unicode escape sequence with the equivalent
|
|
// BMP character or a constant ASCII code point in the case of
|
|
// astral symbols. (See the above note on `astralSubstitute`
|
|
// for more information.)
|
|
.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
|
|
var codePoint = parseInt($1 || $2, 16);
|
|
if (codePoint > 0x10FFFF) {
|
|
throwUnexpectedToken(null, Messages.InvalidRegExp);
|
|
}
|
|
if (codePoint <= 0xFFFF) {
|
|
return String.fromCharCode(codePoint);
|
|
}
|
|
return astralSubstitute;
|
|
})
|
|
// Replace each paired surrogate with a single ASCII symbol to
|
|
// avoid throwing on regular expressions that are only valid in
|
|
// combination with the "u" flag.
|
|
.replace(
|
|
/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
|
|
astralSubstitute
|
|
);
|
|
}
|
|
|
|
// First, detect invalid regular expressions.
|
|
try {
|
|
RegExp(tmp);
|
|
} catch (e) {
|
|
throwUnexpectedToken(null, Messages.InvalidRegExp);
|
|
}
|
|
|
|
// Return a regular expression object for this pattern-flag pair, or
|
|
// `null` in case the current environment doesn't support the flags it
|
|
// uses.
|
|
try {
|
|
return new RegExp(pattern, flags);
|
|
} catch (exception) {
|
|
/* istanbul ignore next */
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function scanRegExpBody() {
|
|
var ch, str, classMarker, terminated, body;
|
|
|
|
ch = source[index];
|
|
assert(ch === '/', 'Regular expression literal must start with a slash');
|
|
str = source[index++];
|
|
|
|
classMarker = false;
|
|
terminated = false;
|
|
while (index < length) {
|
|
ch = source[index++];
|
|
str += ch;
|
|
if (ch === '\\') {
|
|
ch = source[index++];
|
|
// ECMA-262 7.8.5
|
|
if (isLineTerminator(ch.charCodeAt(0))) {
|
|
throwUnexpectedToken(null, Messages.UnterminatedRegExp);
|
|
}
|
|
str += ch;
|
|
} else if (isLineTerminator(ch.charCodeAt(0))) {
|
|
throwUnexpectedToken(null, Messages.UnterminatedRegExp);
|
|
} else if (classMarker) {
|
|
if (ch === ']') {
|
|
classMarker = false;
|
|
}
|
|
} else {
|
|
if (ch === '/') {
|
|
terminated = true;
|
|
break;
|
|
} else if (ch === '[') {
|
|
classMarker = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!terminated) {
|
|
throwUnexpectedToken(null, Messages.UnterminatedRegExp);
|
|
}
|
|
|
|
// Exclude leading and trailing slash.
|
|
body = str.substr(1, str.length - 2);
|
|
return {
|
|
value: body,
|
|
literal: str
|
|
};
|
|
}
|
|
|
|
function scanRegExpFlags() {
|
|
var ch, str, flags, restore;
|
|
|
|
str = '';
|
|
flags = '';
|
|
while (index < length) {
|
|
ch = source[index];
|
|
if (!isIdentifierPart(ch.charCodeAt(0))) {
|
|
break;
|
|
}
|
|
|
|
++index;
|
|
if (ch === '\\' && index < length) {
|
|
ch = source[index];
|
|
if (ch === 'u') {
|
|
++index;
|
|
restore = index;
|
|
ch = scanHexEscape('u');
|
|
if (ch) {
|
|
flags += ch;
|
|
for (str += '\\u'; restore < index; ++restore) {
|
|
str += source[restore];
|
|
}
|
|
} else {
|
|
index = restore;
|
|
flags += 'u';
|
|
str += '\\u';
|
|
}
|
|
tolerateUnexpectedToken();
|
|
} else {
|
|
str += '\\';
|
|
tolerateUnexpectedToken();
|
|
}
|
|
} else {
|
|
flags += ch;
|
|
str += ch;
|
|
}
|
|
}
|
|
|
|
return {
|
|
value: flags,
|
|
literal: str
|
|
};
|
|
}
|
|
|
|
function scanRegExp() {
|
|
var start, body, flags, value;
|
|
scanning = true;
|
|
|
|
lookahead = null;
|
|
skipComment();
|
|
start = index;
|
|
|
|
body = scanRegExpBody();
|
|
flags = scanRegExpFlags();
|
|
value = testRegExp(body.value, flags.value);
|
|
scanning = false;
|
|
if (extra.tokenize) {
|
|
return {
|
|
type: Token.RegularExpression,
|
|
value: value,
|
|
regex: {
|
|
pattern: body.value,
|
|
flags: flags.value
|
|
},
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
return {
|
|
literal: body.literal + flags.literal,
|
|
value: value,
|
|
regex: {
|
|
pattern: body.value,
|
|
flags: flags.value
|
|
},
|
|
start: start,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
function collectRegex() {
|
|
var pos, loc, regex, token;
|
|
|
|
skipComment();
|
|
|
|
pos = index;
|
|
loc = {
|
|
start: {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
}
|
|
};
|
|
|
|
regex = scanRegExp();
|
|
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
};
|
|
|
|
/* istanbul ignore next */
|
|
if (!extra.tokenize) {
|
|
// Pop the previous token, which is likely '/' or '/='
|
|
if (extra.tokens.length > 0) {
|
|
token = extra.tokens[extra.tokens.length - 1];
|
|
if (token.range[0] === pos && token.type === 'Punctuator') {
|
|
if (token.value === '/' || token.value === '/=') {
|
|
extra.tokens.pop();
|
|
}
|
|
}
|
|
}
|
|
|
|
extra.tokens.push({
|
|
type: 'RegularExpression',
|
|
value: regex.literal,
|
|
regex: regex.regex,
|
|
range: [pos, index],
|
|
loc: loc
|
|
});
|
|
}
|
|
|
|
return regex;
|
|
}
|
|
|
|
function isIdentifierName(token) {
|
|
return token.type === Token.Identifier ||
|
|
token.type === Token.Keyword ||
|
|
token.type === Token.BooleanLiteral ||
|
|
token.type === Token.NullLiteral;
|
|
}
|
|
|
|
// Using the following algorithm:
|
|
// https://github.com/mozilla/sweet.js/wiki/design
|
|
|
|
function advanceSlash() {
|
|
var regex, previous, check;
|
|
|
|
function testKeyword(value) {
|
|
return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
|
|
}
|
|
|
|
previous = extra.tokenValues[extra.tokenValues.length - 1];
|
|
regex = (previous !== null);
|
|
|
|
switch (previous) {
|
|
case 'this':
|
|
case ']':
|
|
regex = false;
|
|
break;
|
|
|
|
case ')':
|
|
check = extra.tokenValues[extra.openParenToken - 1];
|
|
regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
|
|
break;
|
|
|
|
case '}':
|
|
// Dividing a function by anything makes little sense,
|
|
// but we have to check for that.
|
|
regex = false;
|
|
if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
|
|
// Anonymous function, e.g. function(){} /42
|
|
check = extra.tokenValues[extra.openCurlyToken - 4];
|
|
regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
|
|
} else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
|
|
// Named function, e.g. function f(){} /42/
|
|
check = extra.tokenValues[extra.openCurlyToken - 5];
|
|
regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
|
|
}
|
|
}
|
|
|
|
return regex ? collectRegex() : scanPunctuator();
|
|
}
|
|
|
|
function advance() {
|
|
var cp, token;
|
|
|
|
if (index >= length) {
|
|
return {
|
|
type: Token.EOF,
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
start: index,
|
|
end: index
|
|
};
|
|
}
|
|
|
|
cp = source.charCodeAt(index);
|
|
|
|
if (isIdentifierStart(cp)) {
|
|
token = scanIdentifier();
|
|
if (strict && isStrictModeReservedWord(token.value)) {
|
|
token.type = Token.Keyword;
|
|
}
|
|
return token;
|
|
}
|
|
|
|
// Very common: ( and ) and ;
|
|
if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
|
|
return scanPunctuator();
|
|
}
|
|
|
|
// String literal starts with single quote (U+0027) or double quote (U+0022).
|
|
if (cp === 0x27 || cp === 0x22) {
|
|
return scanStringLiteral();
|
|
}
|
|
|
|
// Dot (.) U+002E can also start a floating-point number, hence the need
|
|
// to check the next character.
|
|
if (cp === 0x2E) {
|
|
if (isDecimalDigit(source.charCodeAt(index + 1))) {
|
|
return scanNumericLiteral();
|
|
}
|
|
return scanPunctuator();
|
|
}
|
|
|
|
if (isDecimalDigit(cp)) {
|
|
return scanNumericLiteral();
|
|
}
|
|
|
|
// Slash (/) U+002F can also start a regex.
|
|
if (extra.tokenize && cp === 0x2F) {
|
|
return advanceSlash();
|
|
}
|
|
|
|
// Template literals start with ` (U+0060) for template head
|
|
// or } (U+007D) for template middle or template tail.
|
|
if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
|
|
return scanTemplate();
|
|
}
|
|
|
|
// Possible identifier start in a surrogate pair.
|
|
if (cp >= 0xD800 && cp < 0xDFFF) {
|
|
cp = codePointAt(index);
|
|
if (isIdentifierStart(cp)) {
|
|
return scanIdentifier();
|
|
}
|
|
}
|
|
|
|
return scanPunctuator();
|
|
}
|
|
|
|
function collectToken() {
|
|
var loc, token, value, entry;
|
|
|
|
loc = {
|
|
start: {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
}
|
|
};
|
|
|
|
token = advance();
|
|
loc.end = {
|
|
line: lineNumber,
|
|
column: index - lineStart
|
|
};
|
|
|
|
if (token.type !== Token.EOF) {
|
|
value = source.slice(token.start, token.end);
|
|
entry = {
|
|
type: TokenName[token.type],
|
|
value: value,
|
|
range: [token.start, token.end],
|
|
loc: loc
|
|
};
|
|
if (token.regex) {
|
|
entry.regex = {
|
|
pattern: token.regex.pattern,
|
|
flags: token.regex.flags
|
|
};
|
|
}
|
|
if (extra.tokenValues) {
|
|
extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
|
|
}
|
|
if (extra.tokenize) {
|
|
if (!extra.range) {
|
|
delete entry.range;
|
|
}
|
|
if (!extra.loc) {
|
|
delete entry.loc;
|
|
}
|
|
if (extra.delegate) {
|
|
entry = extra.delegate(entry);
|
|
}
|
|
}
|
|
extra.tokens.push(entry);
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
function lex() {
|
|
var token;
|
|
scanning = true;
|
|
|
|
lastIndex = index;
|
|
lastLineNumber = lineNumber;
|
|
lastLineStart = lineStart;
|
|
|
|
skipComment();
|
|
|
|
token = lookahead;
|
|
|
|
startIndex = index;
|
|
startLineNumber = lineNumber;
|
|
startLineStart = lineStart;
|
|
|
|
lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
|
|
scanning = false;
|
|
return token;
|
|
}
|
|
|
|
function peek() {
|
|
scanning = true;
|
|
|
|
skipComment();
|
|
|
|
lastIndex = index;
|
|
lastLineNumber = lineNumber;
|
|
lastLineStart = lineStart;
|
|
|
|
startIndex = index;
|
|
startLineNumber = lineNumber;
|
|
startLineStart = lineStart;
|
|
|
|
lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
|
|
scanning = false;
|
|
}
|
|
|
|
function Position() {
|
|
this.line = startLineNumber;
|
|
this.column = startIndex - startLineStart;
|
|
}
|
|
|
|
function SourceLocation() {
|
|
this.start = new Position();
|
|
this.end = null;
|
|
}
|
|
|
|
function WrappingSourceLocation(startToken) {
|
|
this.start = {
|
|
line: startToken.lineNumber,
|
|
column: startToken.start - startToken.lineStart
|
|
};
|
|
this.end = null;
|
|
}
|
|
|
|
function Node() {
|
|
if (extra.range) {
|
|
this.range = [startIndex, 0];
|
|
}
|
|
if (extra.loc) {
|
|
this.loc = new SourceLocation();
|
|
}
|
|
}
|
|
|
|
function WrappingNode(startToken) {
|
|
if (extra.range) {
|
|
this.range = [startToken.start, 0];
|
|
}
|
|
if (extra.loc) {
|
|
this.loc = new WrappingSourceLocation(startToken);
|
|
}
|
|
}
|
|
|
|
WrappingNode.prototype = Node.prototype = {
|
|
|
|
processComment: function () {
|
|
var lastChild,
|
|
innerComments,
|
|
leadingComments,
|
|
trailingComments,
|
|
bottomRight = extra.bottomRightStack,
|
|
i,
|
|
comment,
|
|
last = bottomRight[bottomRight.length - 1];
|
|
|
|
if (this.type === Syntax.Program) {
|
|
if (this.body.length > 0) {
|
|
return;
|
|
}
|
|
}
|
|
/**
|
|
* patch innnerComments for properties empty block
|
|
* `function a() {/** comments **\/}`
|
|
*/
|
|
|
|
if (this.type === Syntax.BlockStatement && this.body.length === 0) {
|
|
innerComments = [];
|
|
for (i = extra.leadingComments.length - 1; i >= 0; --i) {
|
|
comment = extra.leadingComments[i];
|
|
if (this.range[1] >= comment.range[1]) {
|
|
innerComments.unshift(comment);
|
|
extra.leadingComments.splice(i, 1);
|
|
extra.trailingComments.splice(i, 1);
|
|
}
|
|
}
|
|
if (innerComments.length) {
|
|
this.innerComments = innerComments;
|
|
//bottomRight.push(this);
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (extra.trailingComments.length > 0) {
|
|
trailingComments = [];
|
|
for (i = extra.trailingComments.length - 1; i >= 0; --i) {
|
|
comment = extra.trailingComments[i];
|
|
if (comment.range[0] >= this.range[1]) {
|
|
trailingComments.unshift(comment);
|
|
extra.trailingComments.splice(i, 1);
|
|
}
|
|
}
|
|
extra.trailingComments = [];
|
|
} else {
|
|
if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
|
|
trailingComments = last.trailingComments;
|
|
delete last.trailingComments;
|
|
}
|
|
}
|
|
|
|
// Eating the stack.
|
|
while (last && last.range[0] >= this.range[0]) {
|
|
lastChild = bottomRight.pop();
|
|
last = bottomRight[bottomRight.length - 1];
|
|
}
|
|
|
|
if (lastChild) {
|
|
if (lastChild.leadingComments) {
|
|
leadingComments = [];
|
|
for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
|
|
comment = lastChild.leadingComments[i];
|
|
if (comment.range[1] <= this.range[0]) {
|
|
leadingComments.unshift(comment);
|
|
lastChild.leadingComments.splice(i, 1);
|
|
}
|
|
}
|
|
|
|
if (!lastChild.leadingComments.length) {
|
|
lastChild.leadingComments = undefined;
|
|
}
|
|
}
|
|
} else if (extra.leadingComments.length > 0) {
|
|
leadingComments = [];
|
|
for (i = extra.leadingComments.length - 1; i >= 0; --i) {
|
|
comment = extra.leadingComments[i];
|
|
if (comment.range[1] <= this.range[0]) {
|
|
leadingComments.unshift(comment);
|
|
extra.leadingComments.splice(i, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
if (leadingComments && leadingComments.length > 0) {
|
|
this.leadingComments = leadingComments;
|
|
}
|
|
if (trailingComments && trailingComments.length > 0) {
|
|
this.trailingComments = trailingComments;
|
|
}
|
|
|
|
bottomRight.push(this);
|
|
},
|
|
|
|
finish: function () {
|
|
if (extra.range) {
|
|
this.range[1] = lastIndex;
|
|
}
|
|
if (extra.loc) {
|
|
this.loc.end = {
|
|
line: lastLineNumber,
|
|
column: lastIndex - lastLineStart
|
|
};
|
|
if (extra.source) {
|
|
this.loc.source = extra.source;
|
|
}
|
|
}
|
|
|
|
if (extra.attachComment) {
|
|
this.processComment();
|
|
}
|
|
},
|
|
|
|
finishArrayExpression: function (elements) {
|
|
this.type = Syntax.ArrayExpression;
|
|
this.elements = elements;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishArrayPattern: function (elements) {
|
|
this.type = Syntax.ArrayPattern;
|
|
this.elements = elements;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishArrowFunctionExpression: function (params, defaults, body, expression) {
|
|
this.type = Syntax.ArrowFunctionExpression;
|
|
this.id = null;
|
|
this.params = params;
|
|
this.defaults = defaults;
|
|
this.body = body;
|
|
this.generator = false;
|
|
this.expression = expression;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishAssignmentExpression: function (operator, left, right) {
|
|
this.type = Syntax.AssignmentExpression;
|
|
this.operator = operator;
|
|
this.left = left;
|
|
this.right = right;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishAssignmentPattern: function (left, right) {
|
|
this.type = Syntax.AssignmentPattern;
|
|
this.left = left;
|
|
this.right = right;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishBinaryExpression: function (operator, left, right) {
|
|
this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
|
|
this.operator = operator;
|
|
this.left = left;
|
|
this.right = right;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishBlockStatement: function (body) {
|
|
this.type = Syntax.BlockStatement;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishBreakStatement: function (label) {
|
|
this.type = Syntax.BreakStatement;
|
|
this.label = label;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishCallExpression: function (callee, args) {
|
|
this.type = Syntax.CallExpression;
|
|
this.callee = callee;
|
|
this.arguments = args;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishCatchClause: function (param, body) {
|
|
this.type = Syntax.CatchClause;
|
|
this.param = param;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishClassBody: function (body) {
|
|
this.type = Syntax.ClassBody;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishClassDeclaration: function (id, superClass, body) {
|
|
this.type = Syntax.ClassDeclaration;
|
|
this.id = id;
|
|
this.superClass = superClass;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishClassExpression: function (id, superClass, body) {
|
|
this.type = Syntax.ClassExpression;
|
|
this.id = id;
|
|
this.superClass = superClass;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishConditionalExpression: function (test, consequent, alternate) {
|
|
this.type = Syntax.ConditionalExpression;
|
|
this.test = test;
|
|
this.consequent = consequent;
|
|
this.alternate = alternate;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishContinueStatement: function (label) {
|
|
this.type = Syntax.ContinueStatement;
|
|
this.label = label;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishDebuggerStatement: function () {
|
|
this.type = Syntax.DebuggerStatement;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishDoWhileStatement: function (body, test) {
|
|
this.type = Syntax.DoWhileStatement;
|
|
this.body = body;
|
|
this.test = test;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishEmptyStatement: function () {
|
|
this.type = Syntax.EmptyStatement;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishExpressionStatement: function (expression) {
|
|
this.type = Syntax.ExpressionStatement;
|
|
this.expression = expression;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishForStatement: function (init, test, update, body) {
|
|
this.type = Syntax.ForStatement;
|
|
this.init = init;
|
|
this.test = test;
|
|
this.update = update;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishForOfStatement: function (left, right, body) {
|
|
this.type = Syntax.ForOfStatement;
|
|
this.left = left;
|
|
this.right = right;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishForInStatement: function (left, right, body) {
|
|
this.type = Syntax.ForInStatement;
|
|
this.left = left;
|
|
this.right = right;
|
|
this.body = body;
|
|
this.each = false;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishFunctionDeclaration: function (id, params, defaults, body, generator) {
|
|
this.type = Syntax.FunctionDeclaration;
|
|
this.id = id;
|
|
this.params = params;
|
|
this.defaults = defaults;
|
|
this.body = body;
|
|
this.generator = generator;
|
|
this.expression = false;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishFunctionExpression: function (id, params, defaults, body, generator) {
|
|
this.type = Syntax.FunctionExpression;
|
|
this.id = id;
|
|
this.params = params;
|
|
this.defaults = defaults;
|
|
this.body = body;
|
|
this.generator = generator;
|
|
this.expression = false;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishIdentifier: function (name) {
|
|
this.type = Syntax.Identifier;
|
|
this.name = name;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishIfStatement: function (test, consequent, alternate) {
|
|
this.type = Syntax.IfStatement;
|
|
this.test = test;
|
|
this.consequent = consequent;
|
|
this.alternate = alternate;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishLabeledStatement: function (label, body) {
|
|
this.type = Syntax.LabeledStatement;
|
|
this.label = label;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishLiteral: function (token) {
|
|
this.type = Syntax.Literal;
|
|
this.value = token.value;
|
|
this.raw = source.slice(token.start, token.end);
|
|
if (token.regex) {
|
|
this.regex = token.regex;
|
|
}
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishMemberExpression: function (accessor, object, property) {
|
|
this.type = Syntax.MemberExpression;
|
|
this.computed = accessor === '[';
|
|
this.object = object;
|
|
this.property = property;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishMetaProperty: function (meta, property) {
|
|
this.type = Syntax.MetaProperty;
|
|
this.meta = meta;
|
|
this.property = property;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishNewExpression: function (callee, args) {
|
|
this.type = Syntax.NewExpression;
|
|
this.callee = callee;
|
|
this.arguments = args;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishObjectExpression: function (properties) {
|
|
this.type = Syntax.ObjectExpression;
|
|
this.properties = properties;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishObjectPattern: function (properties) {
|
|
this.type = Syntax.ObjectPattern;
|
|
this.properties = properties;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishPostfixExpression: function (operator, argument) {
|
|
this.type = Syntax.UpdateExpression;
|
|
this.operator = operator;
|
|
this.argument = argument;
|
|
this.prefix = false;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishProgram: function (body, sourceType) {
|
|
this.type = Syntax.Program;
|
|
this.body = body;
|
|
this.sourceType = sourceType;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishProperty: function (kind, key, computed, value, method, shorthand) {
|
|
this.type = Syntax.Property;
|
|
this.key = key;
|
|
this.computed = computed;
|
|
this.value = value;
|
|
this.kind = kind;
|
|
this.method = method;
|
|
this.shorthand = shorthand;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishRestElement: function (argument) {
|
|
this.type = Syntax.RestElement;
|
|
this.argument = argument;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishReturnStatement: function (argument) {
|
|
this.type = Syntax.ReturnStatement;
|
|
this.argument = argument;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishSequenceExpression: function (expressions) {
|
|
this.type = Syntax.SequenceExpression;
|
|
this.expressions = expressions;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishSpreadElement: function (argument) {
|
|
this.type = Syntax.SpreadElement;
|
|
this.argument = argument;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishSwitchCase: function (test, consequent) {
|
|
this.type = Syntax.SwitchCase;
|
|
this.test = test;
|
|
this.consequent = consequent;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishSuper: function () {
|
|
this.type = Syntax.Super;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishSwitchStatement: function (discriminant, cases) {
|
|
this.type = Syntax.SwitchStatement;
|
|
this.discriminant = discriminant;
|
|
this.cases = cases;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishTaggedTemplateExpression: function (tag, quasi) {
|
|
this.type = Syntax.TaggedTemplateExpression;
|
|
this.tag = tag;
|
|
this.quasi = quasi;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishTemplateElement: function (value, tail) {
|
|
this.type = Syntax.TemplateElement;
|
|
this.value = value;
|
|
this.tail = tail;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishTemplateLiteral: function (quasis, expressions) {
|
|
this.type = Syntax.TemplateLiteral;
|
|
this.quasis = quasis;
|
|
this.expressions = expressions;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishThisExpression: function () {
|
|
this.type = Syntax.ThisExpression;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishThrowStatement: function (argument) {
|
|
this.type = Syntax.ThrowStatement;
|
|
this.argument = argument;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishTryStatement: function (block, handler, finalizer) {
|
|
this.type = Syntax.TryStatement;
|
|
this.block = block;
|
|
this.guardedHandlers = [];
|
|
this.handlers = handler ? [handler] : [];
|
|
this.handler = handler;
|
|
this.finalizer = finalizer;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishUnaryExpression: function (operator, argument) {
|
|
this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
|
|
this.operator = operator;
|
|
this.argument = argument;
|
|
this.prefix = true;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishVariableDeclaration: function (declarations) {
|
|
this.type = Syntax.VariableDeclaration;
|
|
this.declarations = declarations;
|
|
this.kind = 'var';
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishLexicalDeclaration: function (declarations, kind) {
|
|
this.type = Syntax.VariableDeclaration;
|
|
this.declarations = declarations;
|
|
this.kind = kind;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishVariableDeclarator: function (id, init) {
|
|
this.type = Syntax.VariableDeclarator;
|
|
this.id = id;
|
|
this.init = init;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishWhileStatement: function (test, body) {
|
|
this.type = Syntax.WhileStatement;
|
|
this.test = test;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishWithStatement: function (object, body) {
|
|
this.type = Syntax.WithStatement;
|
|
this.object = object;
|
|
this.body = body;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishExportSpecifier: function (local, exported) {
|
|
this.type = Syntax.ExportSpecifier;
|
|
this.exported = exported || local;
|
|
this.local = local;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishImportDefaultSpecifier: function (local) {
|
|
this.type = Syntax.ImportDefaultSpecifier;
|
|
this.local = local;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishImportNamespaceSpecifier: function (local) {
|
|
this.type = Syntax.ImportNamespaceSpecifier;
|
|
this.local = local;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishExportNamedDeclaration: function (declaration, specifiers, src) {
|
|
this.type = Syntax.ExportNamedDeclaration;
|
|
this.declaration = declaration;
|
|
this.specifiers = specifiers;
|
|
this.source = src;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishExportDefaultDeclaration: function (declaration) {
|
|
this.type = Syntax.ExportDefaultDeclaration;
|
|
this.declaration = declaration;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishExportAllDeclaration: function (src) {
|
|
this.type = Syntax.ExportAllDeclaration;
|
|
this.source = src;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishImportSpecifier: function (local, imported) {
|
|
this.type = Syntax.ImportSpecifier;
|
|
this.local = local || imported;
|
|
this.imported = imported;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishImportDeclaration: function (specifiers, src) {
|
|
this.type = Syntax.ImportDeclaration;
|
|
this.specifiers = specifiers;
|
|
this.source = src;
|
|
this.finish();
|
|
return this;
|
|
},
|
|
|
|
finishYieldExpression: function (argument, delegate) {
|
|
this.type = Syntax.YieldExpression;
|
|
this.argument = argument;
|
|
this.delegate = delegate;
|
|
this.finish();
|
|
return this;
|
|
}
|
|
};
|
|
|
|
|
|
function recordError(error) {
|
|
var e, existing;
|
|
|
|
for (e = 0; e < extra.errors.length; e++) {
|
|
existing = extra.errors[e];
|
|
// Prevent duplicated error.
|
|
/* istanbul ignore next */
|
|
if (existing.index === error.index && existing.message === error.message) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
extra.errors.push(error);
|
|
}
|
|
|
|
function constructError(msg, column) {
|
|
var error = new Error(msg);
|
|
try {
|
|
throw error;
|
|
} catch (base) {
|
|
/* istanbul ignore else */
|
|
if (Object.create && Object.defineProperty) {
|
|
error = Object.create(base);
|
|
Object.defineProperty(error, 'column', { value: column });
|
|
}
|
|
} finally {
|
|
return error;
|
|
}
|
|
}
|
|
|
|
function createError(line, pos, description) {
|
|
var msg, column, error;
|
|
|
|
msg = 'Line ' + line + ': ' + description;
|
|
column = pos - (scanning ? lineStart : lastLineStart) + 1;
|
|
error = constructError(msg, column);
|
|
error.lineNumber = line;
|
|
error.description = description;
|
|
error.index = pos;
|
|
return error;
|
|
}
|
|
|
|
// Throw an exception
|
|
|
|
function throwError(messageFormat) {
|
|
var args, msg;
|
|
|
|
args = Array.prototype.slice.call(arguments, 1);
|
|
msg = messageFormat.replace(/%(\d)/g,
|
|
function (whole, idx) {
|
|
assert(idx < args.length, 'Message reference must be in range');
|
|
return args[idx];
|
|
}
|
|
);
|
|
|
|
throw createError(lastLineNumber, lastIndex, msg);
|
|
}
|
|
|
|
function tolerateError(messageFormat) {
|
|
var args, msg, error;
|
|
|
|
args = Array.prototype.slice.call(arguments, 1);
|
|
/* istanbul ignore next */
|
|
msg = messageFormat.replace(/%(\d)/g,
|
|
function (whole, idx) {
|
|
assert(idx < args.length, 'Message reference must be in range');
|
|
return args[idx];
|
|
}
|
|
);
|
|
|
|
error = createError(lineNumber, lastIndex, msg);
|
|
if (extra.errors) {
|
|
recordError(error);
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Throw an exception because of the token.
|
|
|
|
function unexpectedTokenError(token, message) {
|
|
var value, msg = message || Messages.UnexpectedToken;
|
|
|
|
if (token) {
|
|
if (!message) {
|
|
msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
|
|
(token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
|
|
(token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
|
|
(token.type === Token.StringLiteral) ? Messages.UnexpectedString :
|
|
(token.type === Token.Template) ? Messages.UnexpectedTemplate :
|
|
Messages.UnexpectedToken;
|
|
|
|
if (token.type === Token.Keyword) {
|
|
if (isFutureReservedWord(token.value)) {
|
|
msg = Messages.UnexpectedReserved;
|
|
} else if (strict && isStrictModeReservedWord(token.value)) {
|
|
msg = Messages.StrictReservedWord;
|
|
}
|
|
}
|
|
}
|
|
|
|
value = (token.type === Token.Template) ? token.value.raw : token.value;
|
|
} else {
|
|
value = 'ILLEGAL';
|
|
}
|
|
|
|
msg = msg.replace('%0', value);
|
|
|
|
return (token && typeof token.lineNumber === 'number') ?
|
|
createError(token.lineNumber, token.start, msg) :
|
|
createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
|
|
}
|
|
|
|
function throwUnexpectedToken(token, message) {
|
|
throw unexpectedTokenError(token, message);
|
|
}
|
|
|
|
function tolerateUnexpectedToken(token, message) {
|
|
var error = unexpectedTokenError(token, message);
|
|
if (extra.errors) {
|
|
recordError(error);
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Expect the next token to match the specified punctuator.
|
|
// If not, an exception will be thrown.
|
|
|
|
function expect(value) {
|
|
var token = lex();
|
|
if (token.type !== Token.Punctuator || token.value !== value) {
|
|
throwUnexpectedToken(token);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @name expectCommaSeparator
|
|
* @description Quietly expect a comma when in tolerant mode, otherwise delegates
|
|
* to <code>expect(value)</code>
|
|
* @since 2.0
|
|
*/
|
|
function expectCommaSeparator() {
|
|
var token;
|
|
|
|
if (extra.errors) {
|
|
token = lookahead;
|
|
if (token.type === Token.Punctuator && token.value === ',') {
|
|
lex();
|
|
} else if (token.type === Token.Punctuator && token.value === ';') {
|
|
lex();
|
|
tolerateUnexpectedToken(token);
|
|
} else {
|
|
tolerateUnexpectedToken(token, Messages.UnexpectedToken);
|
|
}
|
|
} else {
|
|
expect(',');
|
|
}
|
|
}
|
|
|
|
// Expect the next token to match the specified keyword.
|
|
// If not, an exception will be thrown.
|
|
|
|
function expectKeyword(keyword) {
|
|
var token = lex();
|
|
if (token.type !== Token.Keyword || token.value !== keyword) {
|
|
throwUnexpectedToken(token);
|
|
}
|
|
}
|
|
|
|
// Return true if the next token matches the specified punctuator.
|
|
|
|
function match(value) {
|
|
return lookahead.type === Token.Punctuator && lookahead.value === value;
|
|
}
|
|
|
|
// Return true if the next token matches the specified keyword
|
|
|
|
function matchKeyword(keyword) {
|
|
return lookahead.type === Token.Keyword && lookahead.value === keyword;
|
|
}
|
|
|
|
// Return true if the next token matches the specified contextual keyword
|
|
// (where an identifier is sometimes a keyword depending on the context)
|
|
|
|
function matchContextualKeyword(keyword) {
|
|
return lookahead.type === Token.Identifier && lookahead.value === keyword;
|
|
}
|
|
|
|
// Return true if the next token is an assignment operator
|
|
|
|
function matchAssign() {
|
|
var op;
|
|
|
|
if (lookahead.type !== Token.Punctuator) {
|
|
return false;
|
|
}
|
|
op = lookahead.value;
|
|
return op === '=' ||
|
|
op === '*=' ||
|
|
op === '/=' ||
|
|
op === '%=' ||
|
|
op === '+=' ||
|
|
op === '-=' ||
|
|
op === '<<=' ||
|
|
op === '>>=' ||
|
|
op === '>>>=' ||
|
|
op === '&=' ||
|
|
op === '^=' ||
|
|
op === '|=';
|
|
}
|
|
|
|
function consumeSemicolon() {
|
|
// Catch the very common case first: immediately a semicolon (U+003B).
|
|
if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
|
|
lex();
|
|
return;
|
|
}
|
|
|
|
if (hasLineTerminator) {
|
|
return;
|
|
}
|
|
|
|
// FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
|
|
lastIndex = startIndex;
|
|
lastLineNumber = startLineNumber;
|
|
lastLineStart = startLineStart;
|
|
|
|
if (lookahead.type !== Token.EOF && !match('}')) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
}
|
|
|
|
// Cover grammar support.
|
|
//
|
|
// When an assignment expression position starts with an left parenthesis, the determination of the type
|
|
// of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
|
|
// or the first comma. This situation also defers the determination of all the expressions nested in the pair.
|
|
//
|
|
// There are three productions that can be parsed in a parentheses pair that needs to be determined
|
|
// after the outermost pair is closed. They are:
|
|
//
|
|
// 1. AssignmentExpression
|
|
// 2. BindingElements
|
|
// 3. AssignmentTargets
|
|
//
|
|
// In order to avoid exponential backtracking, we use two flags to denote if the production can be
|
|
// binding element or assignment target.
|
|
//
|
|
// The three productions have the relationship:
|
|
//
|
|
// BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
|
|
//
|
|
// with a single exception that CoverInitializedName when used directly in an Expression, generates
|
|
// an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
|
|
// first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
|
|
//
|
|
// isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
|
|
// effect the current flags. This means the production the parser parses is only used as an expression. Therefore
|
|
// the CoverInitializedName check is conducted.
|
|
//
|
|
// inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
|
|
// the flags outside of the parser. This means the production the parser parses is used as a part of a potential
|
|
// pattern. The CoverInitializedName check is deferred.
|
|
function isolateCoverGrammar(parser) {
|
|
var oldIsBindingElement = isBindingElement,
|
|
oldIsAssignmentTarget = isAssignmentTarget,
|
|
oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
|
|
result;
|
|
isBindingElement = true;
|
|
isAssignmentTarget = true;
|
|
firstCoverInitializedNameError = null;
|
|
result = parser();
|
|
if (firstCoverInitializedNameError !== null) {
|
|
throwUnexpectedToken(firstCoverInitializedNameError);
|
|
}
|
|
isBindingElement = oldIsBindingElement;
|
|
isAssignmentTarget = oldIsAssignmentTarget;
|
|
firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
|
|
return result;
|
|
}
|
|
|
|
function inheritCoverGrammar(parser) {
|
|
var oldIsBindingElement = isBindingElement,
|
|
oldIsAssignmentTarget = isAssignmentTarget,
|
|
oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
|
|
result;
|
|
isBindingElement = true;
|
|
isAssignmentTarget = true;
|
|
firstCoverInitializedNameError = null;
|
|
result = parser();
|
|
isBindingElement = isBindingElement && oldIsBindingElement;
|
|
isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
|
|
firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
|
|
return result;
|
|
}
|
|
|
|
// ECMA-262 13.3.3 Destructuring Binding Patterns
|
|
|
|
function parseArrayPattern(params, kind) {
|
|
var node = new Node(), elements = [], rest, restNode;
|
|
expect('[');
|
|
|
|
while (!match(']')) {
|
|
if (match(',')) {
|
|
lex();
|
|
elements.push(null);
|
|
} else {
|
|
if (match('...')) {
|
|
restNode = new Node();
|
|
lex();
|
|
params.push(lookahead);
|
|
rest = parseVariableIdentifier(kind);
|
|
elements.push(restNode.finishRestElement(rest));
|
|
break;
|
|
} else {
|
|
elements.push(parsePatternWithDefault(params, kind));
|
|
}
|
|
if (!match(']')) {
|
|
expect(',');
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
expect(']');
|
|
|
|
return node.finishArrayPattern(elements);
|
|
}
|
|
|
|
function parsePropertyPattern(params, kind) {
|
|
var node = new Node(), key, keyToken, computed = match('['), init;
|
|
if (lookahead.type === Token.Identifier) {
|
|
keyToken = lookahead;
|
|
key = parseVariableIdentifier();
|
|
if (match('=')) {
|
|
params.push(keyToken);
|
|
lex();
|
|
init = parseAssignmentExpression();
|
|
|
|
return node.finishProperty(
|
|
'init', key, false,
|
|
new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true);
|
|
} else if (!match(':')) {
|
|
params.push(keyToken);
|
|
return node.finishProperty('init', key, false, key, false, true);
|
|
}
|
|
} else {
|
|
key = parseObjectPropertyKey();
|
|
}
|
|
expect(':');
|
|
init = parsePatternWithDefault(params, kind);
|
|
return node.finishProperty('init', key, computed, init, false, false);
|
|
}
|
|
|
|
function parseObjectPattern(params, kind) {
|
|
var node = new Node(), properties = [];
|
|
|
|
expect('{');
|
|
|
|
while (!match('}')) {
|
|
properties.push(parsePropertyPattern(params, kind));
|
|
if (!match('}')) {
|
|
expect(',');
|
|
}
|
|
}
|
|
|
|
lex();
|
|
|
|
return node.finishObjectPattern(properties);
|
|
}
|
|
|
|
function parsePattern(params, kind) {
|
|
if (match('[')) {
|
|
return parseArrayPattern(params, kind);
|
|
} else if (match('{')) {
|
|
return parseObjectPattern(params, kind);
|
|
} else if (matchKeyword('let')) {
|
|
if (kind === 'const' || kind === 'let') {
|
|
tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
|
|
}
|
|
}
|
|
|
|
params.push(lookahead);
|
|
return parseVariableIdentifier(kind);
|
|
}
|
|
|
|
function parsePatternWithDefault(params, kind) {
|
|
var startToken = lookahead, pattern, previousAllowYield, right;
|
|
pattern = parsePattern(params, kind);
|
|
if (match('=')) {
|
|
lex();
|
|
previousAllowYield = state.allowYield;
|
|
state.allowYield = true;
|
|
right = isolateCoverGrammar(parseAssignmentExpression);
|
|
state.allowYield = previousAllowYield;
|
|
pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
|
|
}
|
|
return pattern;
|
|
}
|
|
|
|
// ECMA-262 12.2.5 Array Initializer
|
|
|
|
function parseArrayInitializer() {
|
|
var elements = [], node = new Node(), restSpread;
|
|
|
|
expect('[');
|
|
|
|
while (!match(']')) {
|
|
if (match(',')) {
|
|
lex();
|
|
elements.push(null);
|
|
} else if (match('...')) {
|
|
restSpread = new Node();
|
|
lex();
|
|
restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
|
|
|
|
if (!match(']')) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
expect(',');
|
|
}
|
|
elements.push(restSpread);
|
|
} else {
|
|
elements.push(inheritCoverGrammar(parseAssignmentExpression));
|
|
|
|
if (!match(']')) {
|
|
expect(',');
|
|
}
|
|
}
|
|
}
|
|
|
|
lex();
|
|
|
|
return node.finishArrayExpression(elements);
|
|
}
|
|
|
|
// ECMA-262 12.2.6 Object Initializer
|
|
|
|
function parsePropertyFunction(node, paramInfo, isGenerator) {
|
|
var previousStrict, body;
|
|
|
|
isAssignmentTarget = isBindingElement = false;
|
|
|
|
previousStrict = strict;
|
|
body = isolateCoverGrammar(parseFunctionSourceElements);
|
|
|
|
if (strict && paramInfo.firstRestricted) {
|
|
tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
|
|
}
|
|
if (strict && paramInfo.stricted) {
|
|
tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
|
|
}
|
|
|
|
strict = previousStrict;
|
|
return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
|
|
}
|
|
|
|
function parsePropertyMethodFunction() {
|
|
var params, method, node = new Node(),
|
|
previousAllowYield = state.allowYield;
|
|
|
|
state.allowYield = false;
|
|
params = parseParams();
|
|
state.allowYield = previousAllowYield;
|
|
|
|
state.allowYield = false;
|
|
method = parsePropertyFunction(node, params, false);
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return method;
|
|
}
|
|
|
|
function parseObjectPropertyKey() {
|
|
var token, node = new Node(), expr;
|
|
|
|
token = lex();
|
|
|
|
// Note: This function is called only from parseObjectProperty(), where
|
|
// EOF and Punctuator tokens are already filtered out.
|
|
|
|
switch (token.type) {
|
|
case Token.StringLiteral:
|
|
case Token.NumericLiteral:
|
|
if (strict && token.octal) {
|
|
tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
|
|
}
|
|
return node.finishLiteral(token);
|
|
case Token.Identifier:
|
|
case Token.BooleanLiteral:
|
|
case Token.NullLiteral:
|
|
case Token.Keyword:
|
|
return node.finishIdentifier(token.value);
|
|
case Token.Punctuator:
|
|
if (token.value === '[') {
|
|
expr = isolateCoverGrammar(parseAssignmentExpression);
|
|
expect(']');
|
|
return expr;
|
|
}
|
|
break;
|
|
}
|
|
throwUnexpectedToken(token);
|
|
}
|
|
|
|
function lookaheadPropertyName() {
|
|
switch (lookahead.type) {
|
|
case Token.Identifier:
|
|
case Token.StringLiteral:
|
|
case Token.BooleanLiteral:
|
|
case Token.NullLiteral:
|
|
case Token.NumericLiteral:
|
|
case Token.Keyword:
|
|
return true;
|
|
case Token.Punctuator:
|
|
return lookahead.value === '[';
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
|
|
// it might be called at a position where there is in fact a short hand identifier pattern or a data property.
|
|
// This can only be determined after we consumed up to the left parentheses.
|
|
//
|
|
// In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
|
|
// is responsible to visit other options.
|
|
function tryParseMethodDefinition(token, key, computed, node) {
|
|
var value, options, methodNode, params,
|
|
previousAllowYield = state.allowYield;
|
|
|
|
if (token.type === Token.Identifier) {
|
|
// check for `get` and `set`;
|
|
|
|
if (token.value === 'get' && lookaheadPropertyName()) {
|
|
computed = match('[');
|
|
key = parseObjectPropertyKey();
|
|
methodNode = new Node();
|
|
expect('(');
|
|
expect(')');
|
|
|
|
state.allowYield = false;
|
|
value = parsePropertyFunction(methodNode, {
|
|
params: [],
|
|
defaults: [],
|
|
stricted: null,
|
|
firstRestricted: null,
|
|
message: null
|
|
}, false);
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishProperty('get', key, computed, value, false, false);
|
|
} else if (token.value === 'set' && lookaheadPropertyName()) {
|
|
computed = match('[');
|
|
key = parseObjectPropertyKey();
|
|
methodNode = new Node();
|
|
expect('(');
|
|
|
|
options = {
|
|
params: [],
|
|
defaultCount: 0,
|
|
defaults: [],
|
|
firstRestricted: null,
|
|
paramSet: {}
|
|
};
|
|
if (match(')')) {
|
|
tolerateUnexpectedToken(lookahead);
|
|
} else {
|
|
state.allowYield = false;
|
|
parseParam(options);
|
|
state.allowYield = previousAllowYield;
|
|
if (options.defaultCount === 0) {
|
|
options.defaults = [];
|
|
}
|
|
}
|
|
expect(')');
|
|
|
|
state.allowYield = false;
|
|
value = parsePropertyFunction(methodNode, options, false);
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishProperty('set', key, computed, value, false, false);
|
|
}
|
|
} else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
|
|
computed = match('[');
|
|
key = parseObjectPropertyKey();
|
|
methodNode = new Node();
|
|
|
|
state.allowYield = true;
|
|
params = parseParams();
|
|
state.allowYield = previousAllowYield;
|
|
|
|
state.allowYield = false;
|
|
value = parsePropertyFunction(methodNode, params, true);
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishProperty('init', key, computed, value, true, false);
|
|
}
|
|
|
|
if (key && match('(')) {
|
|
value = parsePropertyMethodFunction();
|
|
return node.finishProperty('init', key, computed, value, true, false);
|
|
}
|
|
|
|
// Not a MethodDefinition.
|
|
return null;
|
|
}
|
|
|
|
function parseObjectProperty(hasProto) {
|
|
var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;
|
|
|
|
computed = match('[');
|
|
if (match('*')) {
|
|
lex();
|
|
} else {
|
|
key = parseObjectPropertyKey();
|
|
}
|
|
maybeMethod = tryParseMethodDefinition(token, key, computed, node);
|
|
if (maybeMethod) {
|
|
return maybeMethod;
|
|
}
|
|
|
|
if (!key) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
// Check for duplicated __proto__
|
|
if (!computed) {
|
|
proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
|
|
(key.type === Syntax.Literal && key.value === '__proto__');
|
|
if (hasProto.value && proto) {
|
|
tolerateError(Messages.DuplicateProtoProperty);
|
|
}
|
|
hasProto.value |= proto;
|
|
}
|
|
|
|
if (match(':')) {
|
|
lex();
|
|
value = inheritCoverGrammar(parseAssignmentExpression);
|
|
return node.finishProperty('init', key, computed, value, false, false);
|
|
}
|
|
|
|
if (token.type === Token.Identifier) {
|
|
if (match('=')) {
|
|
firstCoverInitializedNameError = lookahead;
|
|
lex();
|
|
value = isolateCoverGrammar(parseAssignmentExpression);
|
|
return node.finishProperty('init', key, computed,
|
|
new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
|
|
}
|
|
return node.finishProperty('init', key, computed, key, false, true);
|
|
}
|
|
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
function parseObjectInitializer() {
|
|
var properties = [], hasProto = {value: false}, node = new Node();
|
|
|
|
expect('{');
|
|
|
|
while (!match('}')) {
|
|
properties.push(parseObjectProperty(hasProto));
|
|
|
|
if (!match('}')) {
|
|
expectCommaSeparator();
|
|
}
|
|
}
|
|
|
|
expect('}');
|
|
|
|
return node.finishObjectExpression(properties);
|
|
}
|
|
|
|
function reinterpretExpressionAsPattern(expr) {
|
|
var i;
|
|
switch (expr.type) {
|
|
case Syntax.Identifier:
|
|
case Syntax.MemberExpression:
|
|
case Syntax.RestElement:
|
|
case Syntax.AssignmentPattern:
|
|
break;
|
|
case Syntax.SpreadElement:
|
|
expr.type = Syntax.RestElement;
|
|
reinterpretExpressionAsPattern(expr.argument);
|
|
break;
|
|
case Syntax.ArrayExpression:
|
|
expr.type = Syntax.ArrayPattern;
|
|
for (i = 0; i < expr.elements.length; i++) {
|
|
if (expr.elements[i] !== null) {
|
|
reinterpretExpressionAsPattern(expr.elements[i]);
|
|
}
|
|
}
|
|
break;
|
|
case Syntax.ObjectExpression:
|
|
expr.type = Syntax.ObjectPattern;
|
|
for (i = 0; i < expr.properties.length; i++) {
|
|
reinterpretExpressionAsPattern(expr.properties[i].value);
|
|
}
|
|
break;
|
|
case Syntax.AssignmentExpression:
|
|
expr.type = Syntax.AssignmentPattern;
|
|
reinterpretExpressionAsPattern(expr.left);
|
|
break;
|
|
default:
|
|
// Allow other node type for tolerant parsing.
|
|
break;
|
|
}
|
|
}
|
|
|
|
// ECMA-262 12.2.9 Template Literals
|
|
|
|
function parseTemplateElement(option) {
|
|
var node, token;
|
|
|
|
if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
|
|
throwUnexpectedToken();
|
|
}
|
|
|
|
node = new Node();
|
|
token = lex();
|
|
|
|
return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
|
|
}
|
|
|
|
function parseTemplateLiteral() {
|
|
var quasi, quasis, expressions, node = new Node();
|
|
|
|
quasi = parseTemplateElement({ head: true });
|
|
quasis = [quasi];
|
|
expressions = [];
|
|
|
|
while (!quasi.tail) {
|
|
expressions.push(parseExpression());
|
|
quasi = parseTemplateElement({ head: false });
|
|
quasis.push(quasi);
|
|
}
|
|
|
|
return node.finishTemplateLiteral(quasis, expressions);
|
|
}
|
|
|
|
// ECMA-262 12.2.10 The Grouping Operator
|
|
|
|
function parseGroupExpression() {
|
|
var expr, expressions, startToken, i, params = [];
|
|
|
|
expect('(');
|
|
|
|
if (match(')')) {
|
|
lex();
|
|
if (!match('=>')) {
|
|
expect('=>');
|
|
}
|
|
return {
|
|
type: PlaceHolders.ArrowParameterPlaceHolder,
|
|
params: [],
|
|
rawParams: []
|
|
};
|
|
}
|
|
|
|
startToken = lookahead;
|
|
if (match('...')) {
|
|
expr = parseRestElement(params);
|
|
expect(')');
|
|
if (!match('=>')) {
|
|
expect('=>');
|
|
}
|
|
return {
|
|
type: PlaceHolders.ArrowParameterPlaceHolder,
|
|
params: [expr]
|
|
};
|
|
}
|
|
|
|
isBindingElement = true;
|
|
expr = inheritCoverGrammar(parseAssignmentExpression);
|
|
|
|
if (match(',')) {
|
|
isAssignmentTarget = false;
|
|
expressions = [expr];
|
|
|
|
while (startIndex < length) {
|
|
if (!match(',')) {
|
|
break;
|
|
}
|
|
lex();
|
|
|
|
if (match('...')) {
|
|
if (!isBindingElement) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
expressions.push(parseRestElement(params));
|
|
expect(')');
|
|
if (!match('=>')) {
|
|
expect('=>');
|
|
}
|
|
isBindingElement = false;
|
|
for (i = 0; i < expressions.length; i++) {
|
|
reinterpretExpressionAsPattern(expressions[i]);
|
|
}
|
|
return {
|
|
type: PlaceHolders.ArrowParameterPlaceHolder,
|
|
params: expressions
|
|
};
|
|
}
|
|
|
|
expressions.push(inheritCoverGrammar(parseAssignmentExpression));
|
|
}
|
|
|
|
expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
|
|
}
|
|
|
|
|
|
expect(')');
|
|
|
|
if (match('=>')) {
|
|
if (expr.type === Syntax.Identifier && expr.name === 'yield') {
|
|
return {
|
|
type: PlaceHolders.ArrowParameterPlaceHolder,
|
|
params: [expr]
|
|
};
|
|
}
|
|
|
|
if (!isBindingElement) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
if (expr.type === Syntax.SequenceExpression) {
|
|
for (i = 0; i < expr.expressions.length; i++) {
|
|
reinterpretExpressionAsPattern(expr.expressions[i]);
|
|
}
|
|
} else {
|
|
reinterpretExpressionAsPattern(expr);
|
|
}
|
|
|
|
expr = {
|
|
type: PlaceHolders.ArrowParameterPlaceHolder,
|
|
params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
|
|
};
|
|
}
|
|
isBindingElement = false;
|
|
return expr;
|
|
}
|
|
|
|
|
|
// ECMA-262 12.2 Primary Expressions
|
|
|
|
function parsePrimaryExpression() {
|
|
var type, token, expr, node;
|
|
|
|
if (match('(')) {
|
|
isBindingElement = false;
|
|
return inheritCoverGrammar(parseGroupExpression);
|
|
}
|
|
|
|
if (match('[')) {
|
|
return inheritCoverGrammar(parseArrayInitializer);
|
|
}
|
|
|
|
if (match('{')) {
|
|
return inheritCoverGrammar(parseObjectInitializer);
|
|
}
|
|
|
|
type = lookahead.type;
|
|
node = new Node();
|
|
|
|
if (type === Token.Identifier) {
|
|
if (state.sourceType === 'module' && lookahead.value === 'await') {
|
|
tolerateUnexpectedToken(lookahead);
|
|
}
|
|
expr = node.finishIdentifier(lex().value);
|
|
} else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
if (strict && lookahead.octal) {
|
|
tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
|
|
}
|
|
expr = node.finishLiteral(lex());
|
|
} else if (type === Token.Keyword) {
|
|
if (!strict && state.allowYield && matchKeyword('yield')) {
|
|
return parseNonComputedProperty();
|
|
}
|
|
if (!strict && matchKeyword('let')) {
|
|
return node.finishIdentifier(lex().value);
|
|
}
|
|
isAssignmentTarget = isBindingElement = false;
|
|
if (matchKeyword('function')) {
|
|
return parseFunctionExpression();
|
|
}
|
|
if (matchKeyword('this')) {
|
|
lex();
|
|
return node.finishThisExpression();
|
|
}
|
|
if (matchKeyword('class')) {
|
|
return parseClassExpression();
|
|
}
|
|
throwUnexpectedToken(lex());
|
|
} else if (type === Token.BooleanLiteral) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
token = lex();
|
|
token.value = (token.value === 'true');
|
|
expr = node.finishLiteral(token);
|
|
} else if (type === Token.NullLiteral) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
token = lex();
|
|
token.value = null;
|
|
expr = node.finishLiteral(token);
|
|
} else if (match('/') || match('/=')) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
index = startIndex;
|
|
|
|
if (typeof extra.tokens !== 'undefined') {
|
|
token = collectRegex();
|
|
} else {
|
|
token = scanRegExp();
|
|
}
|
|
lex();
|
|
expr = node.finishLiteral(token);
|
|
} else if (type === Token.Template) {
|
|
expr = parseTemplateLiteral();
|
|
} else {
|
|
throwUnexpectedToken(lex());
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.3 Left-Hand-Side Expressions
|
|
|
|
function parseArguments() {
|
|
var args = [], expr;
|
|
|
|
expect('(');
|
|
|
|
if (!match(')')) {
|
|
while (startIndex < length) {
|
|
if (match('...')) {
|
|
expr = new Node();
|
|
lex();
|
|
expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
|
|
} else {
|
|
expr = isolateCoverGrammar(parseAssignmentExpression);
|
|
}
|
|
args.push(expr);
|
|
if (match(')')) {
|
|
break;
|
|
}
|
|
expectCommaSeparator();
|
|
}
|
|
}
|
|
|
|
expect(')');
|
|
|
|
return args;
|
|
}
|
|
|
|
function parseNonComputedProperty() {
|
|
var token, node = new Node();
|
|
|
|
token = lex();
|
|
|
|
if (!isIdentifierName(token)) {
|
|
throwUnexpectedToken(token);
|
|
}
|
|
|
|
return node.finishIdentifier(token.value);
|
|
}
|
|
|
|
function parseNonComputedMember() {
|
|
expect('.');
|
|
|
|
return parseNonComputedProperty();
|
|
}
|
|
|
|
function parseComputedMember() {
|
|
var expr;
|
|
|
|
expect('[');
|
|
|
|
expr = isolateCoverGrammar(parseExpression);
|
|
|
|
expect(']');
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.3.3 The new Operator
|
|
|
|
function parseNewExpression() {
|
|
var callee, args, node = new Node();
|
|
|
|
expectKeyword('new');
|
|
|
|
if (match('.')) {
|
|
lex();
|
|
if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
|
|
if (state.inFunctionBody) {
|
|
lex();
|
|
return node.finishMetaProperty('new', 'target');
|
|
}
|
|
}
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
callee = isolateCoverGrammar(parseLeftHandSideExpression);
|
|
args = match('(') ? parseArguments() : [];
|
|
|
|
isAssignmentTarget = isBindingElement = false;
|
|
|
|
return node.finishNewExpression(callee, args);
|
|
}
|
|
|
|
// ECMA-262 12.3.4 Function Calls
|
|
|
|
function parseLeftHandSideExpressionAllowCall() {
|
|
var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
|
|
|
|
startToken = lookahead;
|
|
state.allowIn = true;
|
|
|
|
if (matchKeyword('super') && state.inFunctionBody) {
|
|
expr = new Node();
|
|
lex();
|
|
expr = expr.finishSuper();
|
|
if (!match('(') && !match('.') && !match('[')) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
} else {
|
|
expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
|
|
}
|
|
|
|
for (;;) {
|
|
if (match('.')) {
|
|
isBindingElement = false;
|
|
isAssignmentTarget = true;
|
|
property = parseNonComputedMember();
|
|
expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
|
|
} else if (match('(')) {
|
|
isBindingElement = false;
|
|
isAssignmentTarget = false;
|
|
args = parseArguments();
|
|
expr = new WrappingNode(startToken).finishCallExpression(expr, args);
|
|
} else if (match('[')) {
|
|
isBindingElement = false;
|
|
isAssignmentTarget = true;
|
|
property = parseComputedMember();
|
|
expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
|
|
} else if (lookahead.type === Token.Template && lookahead.head) {
|
|
quasi = parseTemplateLiteral();
|
|
expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
state.allowIn = previousAllowIn;
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.3 Left-Hand-Side Expressions
|
|
|
|
function parseLeftHandSideExpression() {
|
|
var quasi, expr, property, startToken;
|
|
assert(state.allowIn, 'callee of new expression always allow in keyword.');
|
|
|
|
startToken = lookahead;
|
|
|
|
if (matchKeyword('super') && state.inFunctionBody) {
|
|
expr = new Node();
|
|
lex();
|
|
expr = expr.finishSuper();
|
|
if (!match('[') && !match('.')) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
} else {
|
|
expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
|
|
}
|
|
|
|
for (;;) {
|
|
if (match('[')) {
|
|
isBindingElement = false;
|
|
isAssignmentTarget = true;
|
|
property = parseComputedMember();
|
|
expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
|
|
} else if (match('.')) {
|
|
isBindingElement = false;
|
|
isAssignmentTarget = true;
|
|
property = parseNonComputedMember();
|
|
expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
|
|
} else if (lookahead.type === Token.Template && lookahead.head) {
|
|
quasi = parseTemplateLiteral();
|
|
expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.4 Postfix Expressions
|
|
|
|
function parsePostfixExpression() {
|
|
var expr, token, startToken = lookahead;
|
|
|
|
expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
|
|
|
|
if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
|
|
if (match('++') || match('--')) {
|
|
// ECMA-262 11.3.1, 11.3.2
|
|
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
|
|
tolerateError(Messages.StrictLHSPostfix);
|
|
}
|
|
|
|
if (!isAssignmentTarget) {
|
|
tolerateError(Messages.InvalidLHSInAssignment);
|
|
}
|
|
|
|
isAssignmentTarget = isBindingElement = false;
|
|
|
|
token = lex();
|
|
expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
|
|
}
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.5 Unary Operators
|
|
|
|
function parseUnaryExpression() {
|
|
var token, expr, startToken;
|
|
|
|
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
|
|
expr = parsePostfixExpression();
|
|
} else if (match('++') || match('--')) {
|
|
startToken = lookahead;
|
|
token = lex();
|
|
expr = inheritCoverGrammar(parseUnaryExpression);
|
|
// ECMA-262 11.4.4, 11.4.5
|
|
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
|
|
tolerateError(Messages.StrictLHSPrefix);
|
|
}
|
|
|
|
if (!isAssignmentTarget) {
|
|
tolerateError(Messages.InvalidLHSInAssignment);
|
|
}
|
|
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
|
|
isAssignmentTarget = isBindingElement = false;
|
|
} else if (match('+') || match('-') || match('~') || match('!')) {
|
|
startToken = lookahead;
|
|
token = lex();
|
|
expr = inheritCoverGrammar(parseUnaryExpression);
|
|
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
|
|
isAssignmentTarget = isBindingElement = false;
|
|
} else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
|
|
startToken = lookahead;
|
|
token = lex();
|
|
expr = inheritCoverGrammar(parseUnaryExpression);
|
|
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
|
|
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
|
|
tolerateError(Messages.StrictDelete);
|
|
}
|
|
isAssignmentTarget = isBindingElement = false;
|
|
} else {
|
|
expr = parsePostfixExpression();
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
function binaryPrecedence(token, allowIn) {
|
|
var prec = 0;
|
|
|
|
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
|
|
return 0;
|
|
}
|
|
|
|
switch (token.value) {
|
|
case '||':
|
|
prec = 1;
|
|
break;
|
|
|
|
case '&&':
|
|
prec = 2;
|
|
break;
|
|
|
|
case '|':
|
|
prec = 3;
|
|
break;
|
|
|
|
case '^':
|
|
prec = 4;
|
|
break;
|
|
|
|
case '&':
|
|
prec = 5;
|
|
break;
|
|
|
|
case '==':
|
|
case '!=':
|
|
case '===':
|
|
case '!==':
|
|
prec = 6;
|
|
break;
|
|
|
|
case '<':
|
|
case '>':
|
|
case '<=':
|
|
case '>=':
|
|
case 'instanceof':
|
|
prec = 7;
|
|
break;
|
|
|
|
case 'in':
|
|
prec = allowIn ? 7 : 0;
|
|
break;
|
|
|
|
case '<<':
|
|
case '>>':
|
|
case '>>>':
|
|
prec = 8;
|
|
break;
|
|
|
|
case '+':
|
|
case '-':
|
|
prec = 9;
|
|
break;
|
|
|
|
case '*':
|
|
case '/':
|
|
case '%':
|
|
prec = 11;
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
|
|
return prec;
|
|
}
|
|
|
|
// ECMA-262 12.6 Multiplicative Operators
|
|
// ECMA-262 12.7 Additive Operators
|
|
// ECMA-262 12.8 Bitwise Shift Operators
|
|
// ECMA-262 12.9 Relational Operators
|
|
// ECMA-262 12.10 Equality Operators
|
|
// ECMA-262 12.11 Binary Bitwise Operators
|
|
// ECMA-262 12.12 Binary Logical Operators
|
|
|
|
function parseBinaryExpression() {
|
|
var marker, markers, expr, token, prec, stack, right, operator, left, i;
|
|
|
|
marker = lookahead;
|
|
left = inheritCoverGrammar(parseUnaryExpression);
|
|
|
|
token = lookahead;
|
|
prec = binaryPrecedence(token, state.allowIn);
|
|
if (prec === 0) {
|
|
return left;
|
|
}
|
|
isAssignmentTarget = isBindingElement = false;
|
|
token.prec = prec;
|
|
lex();
|
|
|
|
markers = [marker, lookahead];
|
|
right = isolateCoverGrammar(parseUnaryExpression);
|
|
|
|
stack = [left, token, right];
|
|
|
|
while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
|
|
|
|
// Reduce: make a binary expression from the three topmost entries.
|
|
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
|
|
right = stack.pop();
|
|
operator = stack.pop().value;
|
|
left = stack.pop();
|
|
markers.pop();
|
|
expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
|
|
stack.push(expr);
|
|
}
|
|
|
|
// Shift.
|
|
token = lex();
|
|
token.prec = prec;
|
|
stack.push(token);
|
|
markers.push(lookahead);
|
|
expr = isolateCoverGrammar(parseUnaryExpression);
|
|
stack.push(expr);
|
|
}
|
|
|
|
// Final reduce to clean-up the stack.
|
|
i = stack.length - 1;
|
|
expr = stack[i];
|
|
markers.pop();
|
|
while (i > 1) {
|
|
expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
|
|
i -= 2;
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
|
|
// ECMA-262 12.13 Conditional Operator
|
|
|
|
function parseConditionalExpression() {
|
|
var expr, previousAllowIn, consequent, alternate, startToken;
|
|
|
|
startToken = lookahead;
|
|
|
|
expr = inheritCoverGrammar(parseBinaryExpression);
|
|
if (match('?')) {
|
|
lex();
|
|
previousAllowIn = state.allowIn;
|
|
state.allowIn = true;
|
|
consequent = isolateCoverGrammar(parseAssignmentExpression);
|
|
state.allowIn = previousAllowIn;
|
|
expect(':');
|
|
alternate = isolateCoverGrammar(parseAssignmentExpression);
|
|
|
|
expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
|
|
isAssignmentTarget = isBindingElement = false;
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 14.2 Arrow Function Definitions
|
|
|
|
function parseConciseBody() {
|
|
if (match('{')) {
|
|
return parseFunctionSourceElements();
|
|
}
|
|
return isolateCoverGrammar(parseAssignmentExpression);
|
|
}
|
|
|
|
function checkPatternParam(options, param) {
|
|
var i;
|
|
switch (param.type) {
|
|
case Syntax.Identifier:
|
|
validateParam(options, param, param.name);
|
|
break;
|
|
case Syntax.RestElement:
|
|
checkPatternParam(options, param.argument);
|
|
break;
|
|
case Syntax.AssignmentPattern:
|
|
checkPatternParam(options, param.left);
|
|
break;
|
|
case Syntax.ArrayPattern:
|
|
for (i = 0; i < param.elements.length; i++) {
|
|
if (param.elements[i] !== null) {
|
|
checkPatternParam(options, param.elements[i]);
|
|
}
|
|
}
|
|
break;
|
|
case Syntax.YieldExpression:
|
|
break;
|
|
default:
|
|
assert(param.type === Syntax.ObjectPattern, 'Invalid type');
|
|
for (i = 0; i < param.properties.length; i++) {
|
|
checkPatternParam(options, param.properties[i].value);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
function reinterpretAsCoverFormalsList(expr) {
|
|
var i, len, param, params, defaults, defaultCount, options, token;
|
|
|
|
defaults = [];
|
|
defaultCount = 0;
|
|
params = [expr];
|
|
|
|
switch (expr.type) {
|
|
case Syntax.Identifier:
|
|
break;
|
|
case PlaceHolders.ArrowParameterPlaceHolder:
|
|
params = expr.params;
|
|
break;
|
|
default:
|
|
return null;
|
|
}
|
|
|
|
options = {
|
|
paramSet: {}
|
|
};
|
|
|
|
for (i = 0, len = params.length; i < len; i += 1) {
|
|
param = params[i];
|
|
switch (param.type) {
|
|
case Syntax.AssignmentPattern:
|
|
params[i] = param.left;
|
|
if (param.right.type === Syntax.YieldExpression) {
|
|
if (param.right.argument) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
param.right.type = Syntax.Identifier;
|
|
param.right.name = 'yield';
|
|
delete param.right.argument;
|
|
delete param.right.delegate;
|
|
}
|
|
defaults.push(param.right);
|
|
++defaultCount;
|
|
checkPatternParam(options, param.left);
|
|
break;
|
|
default:
|
|
checkPatternParam(options, param);
|
|
params[i] = param;
|
|
defaults.push(null);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (strict || !state.allowYield) {
|
|
for (i = 0, len = params.length; i < len; i += 1) {
|
|
param = params[i];
|
|
if (param.type === Syntax.YieldExpression) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (options.message === Messages.StrictParamDupe) {
|
|
token = strict ? options.stricted : options.firstRestricted;
|
|
throwUnexpectedToken(token, options.message);
|
|
}
|
|
|
|
if (defaultCount === 0) {
|
|
defaults = [];
|
|
}
|
|
|
|
return {
|
|
params: params,
|
|
defaults: defaults,
|
|
stricted: options.stricted,
|
|
firstRestricted: options.firstRestricted,
|
|
message: options.message
|
|
};
|
|
}
|
|
|
|
function parseArrowFunctionExpression(options, node) {
|
|
var previousStrict, previousAllowYield, body;
|
|
|
|
if (hasLineTerminator) {
|
|
tolerateUnexpectedToken(lookahead);
|
|
}
|
|
expect('=>');
|
|
|
|
previousStrict = strict;
|
|
previousAllowYield = state.allowYield;
|
|
state.allowYield = true;
|
|
|
|
body = parseConciseBody();
|
|
|
|
if (strict && options.firstRestricted) {
|
|
throwUnexpectedToken(options.firstRestricted, options.message);
|
|
}
|
|
if (strict && options.stricted) {
|
|
tolerateUnexpectedToken(options.stricted, options.message);
|
|
}
|
|
|
|
strict = previousStrict;
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
|
|
}
|
|
|
|
// ECMA-262 14.4 Yield expression
|
|
|
|
function parseYieldExpression() {
|
|
var argument, expr, delegate, previousAllowYield;
|
|
|
|
argument = null;
|
|
expr = new Node();
|
|
delegate = false;
|
|
|
|
expectKeyword('yield');
|
|
|
|
if (!hasLineTerminator) {
|
|
previousAllowYield = state.allowYield;
|
|
state.allowYield = false;
|
|
delegate = match('*');
|
|
if (delegate) {
|
|
lex();
|
|
argument = parseAssignmentExpression();
|
|
} else {
|
|
if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
|
|
argument = parseAssignmentExpression();
|
|
}
|
|
}
|
|
state.allowYield = previousAllowYield;
|
|
}
|
|
|
|
return expr.finishYieldExpression(argument, delegate);
|
|
}
|
|
|
|
// ECMA-262 12.14 Assignment Operators
|
|
|
|
function parseAssignmentExpression() {
|
|
var token, expr, right, list, startToken;
|
|
|
|
startToken = lookahead;
|
|
token = lookahead;
|
|
|
|
if (!state.allowYield && matchKeyword('yield')) {
|
|
return parseYieldExpression();
|
|
}
|
|
|
|
expr = parseConditionalExpression();
|
|
|
|
if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
list = reinterpretAsCoverFormalsList(expr);
|
|
|
|
if (list) {
|
|
firstCoverInitializedNameError = null;
|
|
return parseArrowFunctionExpression(list, new WrappingNode(startToken));
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
if (matchAssign()) {
|
|
if (!isAssignmentTarget) {
|
|
tolerateError(Messages.InvalidLHSInAssignment);
|
|
}
|
|
|
|
// ECMA-262 12.1.1
|
|
if (strict && expr.type === Syntax.Identifier) {
|
|
if (isRestrictedWord(expr.name)) {
|
|
tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
|
|
}
|
|
if (isStrictModeReservedWord(expr.name)) {
|
|
tolerateUnexpectedToken(token, Messages.StrictReservedWord);
|
|
}
|
|
}
|
|
|
|
if (!match('=')) {
|
|
isAssignmentTarget = isBindingElement = false;
|
|
} else {
|
|
reinterpretExpressionAsPattern(expr);
|
|
}
|
|
|
|
token = lex();
|
|
right = isolateCoverGrammar(parseAssignmentExpression);
|
|
expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
|
|
firstCoverInitializedNameError = null;
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 12.15 Comma Operator
|
|
|
|
function parseExpression() {
|
|
var expr, startToken = lookahead, expressions;
|
|
|
|
expr = isolateCoverGrammar(parseAssignmentExpression);
|
|
|
|
if (match(',')) {
|
|
expressions = [expr];
|
|
|
|
while (startIndex < length) {
|
|
if (!match(',')) {
|
|
break;
|
|
}
|
|
lex();
|
|
expressions.push(isolateCoverGrammar(parseAssignmentExpression));
|
|
}
|
|
|
|
expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
|
|
}
|
|
|
|
return expr;
|
|
}
|
|
|
|
// ECMA-262 13.2 Block
|
|
|
|
function parseStatementListItem() {
|
|
if (lookahead.type === Token.Keyword) {
|
|
switch (lookahead.value) {
|
|
case 'export':
|
|
if (state.sourceType !== 'module') {
|
|
tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
|
|
}
|
|
return parseExportDeclaration();
|
|
case 'import':
|
|
if (state.sourceType !== 'module') {
|
|
tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
|
|
}
|
|
return parseImportDeclaration();
|
|
case 'const':
|
|
return parseLexicalDeclaration({inFor: false});
|
|
case 'function':
|
|
return parseFunctionDeclaration(new Node());
|
|
case 'class':
|
|
return parseClassDeclaration();
|
|
}
|
|
}
|
|
|
|
if (matchKeyword('let') && isLexicalDeclaration()) {
|
|
return parseLexicalDeclaration({inFor: false});
|
|
}
|
|
|
|
return parseStatement();
|
|
}
|
|
|
|
function parseStatementList() {
|
|
var list = [];
|
|
while (startIndex < length) {
|
|
if (match('}')) {
|
|
break;
|
|
}
|
|
list.push(parseStatementListItem());
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
function parseBlock() {
|
|
var block, node = new Node();
|
|
|
|
expect('{');
|
|
|
|
block = parseStatementList();
|
|
|
|
expect('}');
|
|
|
|
return node.finishBlockStatement(block);
|
|
}
|
|
|
|
// ECMA-262 13.3.2 Variable Statement
|
|
|
|
function parseVariableIdentifier(kind) {
|
|
var token, node = new Node();
|
|
|
|
token = lex();
|
|
|
|
if (token.type === Token.Keyword && token.value === 'yield') {
|
|
if (strict) {
|
|
tolerateUnexpectedToken(token, Messages.StrictReservedWord);
|
|
} if (!state.allowYield) {
|
|
throwUnexpectedToken(token);
|
|
}
|
|
} else if (token.type !== Token.Identifier) {
|
|
if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
|
|
tolerateUnexpectedToken(token, Messages.StrictReservedWord);
|
|
} else {
|
|
if (strict || token.value !== 'let' || kind !== 'var') {
|
|
throwUnexpectedToken(token);
|
|
}
|
|
}
|
|
} else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
|
|
tolerateUnexpectedToken(token);
|
|
}
|
|
|
|
return node.finishIdentifier(token.value);
|
|
}
|
|
|
|
function parseVariableDeclaration(options) {
|
|
var init = null, id, node = new Node(), params = [];
|
|
|
|
id = parsePattern(params, 'var');
|
|
|
|
// ECMA-262 12.2.1
|
|
if (strict && isRestrictedWord(id.name)) {
|
|
tolerateError(Messages.StrictVarName);
|
|
}
|
|
|
|
if (match('=')) {
|
|
lex();
|
|
init = isolateCoverGrammar(parseAssignmentExpression);
|
|
} else if (id.type !== Syntax.Identifier && !options.inFor) {
|
|
expect('=');
|
|
}
|
|
|
|
return node.finishVariableDeclarator(id, init);
|
|
}
|
|
|
|
function parseVariableDeclarationList(options) {
|
|
var opt, list;
|
|
|
|
opt = { inFor: options.inFor };
|
|
list = [parseVariableDeclaration(opt)];
|
|
|
|
while (match(',')) {
|
|
lex();
|
|
list.push(parseVariableDeclaration(opt));
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
function parseVariableStatement(node) {
|
|
var declarations;
|
|
|
|
expectKeyword('var');
|
|
|
|
declarations = parseVariableDeclarationList({ inFor: false });
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishVariableDeclaration(declarations);
|
|
}
|
|
|
|
// ECMA-262 13.3.1 Let and Const Declarations
|
|
|
|
function parseLexicalBinding(kind, options) {
|
|
var init = null, id, node = new Node(), params = [];
|
|
|
|
id = parsePattern(params, kind);
|
|
|
|
// ECMA-262 12.2.1
|
|
if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
|
|
tolerateError(Messages.StrictVarName);
|
|
}
|
|
|
|
if (kind === 'const') {
|
|
if (!matchKeyword('in') && !matchContextualKeyword('of')) {
|
|
expect('=');
|
|
init = isolateCoverGrammar(parseAssignmentExpression);
|
|
}
|
|
} else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
|
|
expect('=');
|
|
init = isolateCoverGrammar(parseAssignmentExpression);
|
|
}
|
|
|
|
return node.finishVariableDeclarator(id, init);
|
|
}
|
|
|
|
function parseBindingList(kind, options) {
|
|
var list = [parseLexicalBinding(kind, options)];
|
|
|
|
while (match(',')) {
|
|
lex();
|
|
list.push(parseLexicalBinding(kind, options));
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
|
|
function tokenizerState() {
|
|
return {
|
|
index: index,
|
|
lineNumber: lineNumber,
|
|
lineStart: lineStart,
|
|
hasLineTerminator: hasLineTerminator,
|
|
lastIndex: lastIndex,
|
|
lastLineNumber: lastLineNumber,
|
|
lastLineStart: lastLineStart,
|
|
startIndex: startIndex,
|
|
startLineNumber: startLineNumber,
|
|
startLineStart: startLineStart,
|
|
lookahead: lookahead,
|
|
tokenCount: extra.tokens ? extra.tokens.length : 0
|
|
};
|
|
}
|
|
|
|
function resetTokenizerState(ts) {
|
|
index = ts.index;
|
|
lineNumber = ts.lineNumber;
|
|
lineStart = ts.lineStart;
|
|
hasLineTerminator = ts.hasLineTerminator;
|
|
lastIndex = ts.lastIndex;
|
|
lastLineNumber = ts.lastLineNumber;
|
|
lastLineStart = ts.lastLineStart;
|
|
startIndex = ts.startIndex;
|
|
startLineNumber = ts.startLineNumber;
|
|
startLineStart = ts.startLineStart;
|
|
lookahead = ts.lookahead;
|
|
if (extra.tokens) {
|
|
extra.tokens.splice(ts.tokenCount, extra.tokens.length);
|
|
}
|
|
}
|
|
|
|
function isLexicalDeclaration() {
|
|
var lexical, ts;
|
|
|
|
ts = tokenizerState();
|
|
|
|
lex();
|
|
lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
|
|
matchKeyword('let') || matchKeyword('yield');
|
|
|
|
resetTokenizerState(ts);
|
|
|
|
return lexical;
|
|
}
|
|
|
|
function parseLexicalDeclaration(options) {
|
|
var kind, declarations, node = new Node();
|
|
|
|
kind = lex().value;
|
|
assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
|
|
|
|
declarations = parseBindingList(kind, options);
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishLexicalDeclaration(declarations, kind);
|
|
}
|
|
|
|
function parseRestElement(params) {
|
|
var param, node = new Node();
|
|
|
|
lex();
|
|
|
|
if (match('{')) {
|
|
throwError(Messages.ObjectPatternAsRestParameter);
|
|
}
|
|
|
|
params.push(lookahead);
|
|
|
|
param = parseVariableIdentifier();
|
|
|
|
if (match('=')) {
|
|
throwError(Messages.DefaultRestParameter);
|
|
}
|
|
|
|
if (!match(')')) {
|
|
throwError(Messages.ParameterAfterRestParameter);
|
|
}
|
|
|
|
return node.finishRestElement(param);
|
|
}
|
|
|
|
// ECMA-262 13.4 Empty Statement
|
|
|
|
function parseEmptyStatement(node) {
|
|
expect(';');
|
|
return node.finishEmptyStatement();
|
|
}
|
|
|
|
// ECMA-262 12.4 Expression Statement
|
|
|
|
function parseExpressionStatement(node) {
|
|
var expr = parseExpression();
|
|
consumeSemicolon();
|
|
return node.finishExpressionStatement(expr);
|
|
}
|
|
|
|
// ECMA-262 13.6 If statement
|
|
|
|
function parseIfStatement(node) {
|
|
var test, consequent, alternate;
|
|
|
|
expectKeyword('if');
|
|
|
|
expect('(');
|
|
|
|
test = parseExpression();
|
|
|
|
expect(')');
|
|
|
|
consequent = parseStatement();
|
|
|
|
if (matchKeyword('else')) {
|
|
lex();
|
|
alternate = parseStatement();
|
|
} else {
|
|
alternate = null;
|
|
}
|
|
|
|
return node.finishIfStatement(test, consequent, alternate);
|
|
}
|
|
|
|
// ECMA-262 13.7 Iteration Statements
|
|
|
|
function parseDoWhileStatement(node) {
|
|
var body, test, oldInIteration;
|
|
|
|
expectKeyword('do');
|
|
|
|
oldInIteration = state.inIteration;
|
|
state.inIteration = true;
|
|
|
|
body = parseStatement();
|
|
|
|
state.inIteration = oldInIteration;
|
|
|
|
expectKeyword('while');
|
|
|
|
expect('(');
|
|
|
|
test = parseExpression();
|
|
|
|
expect(')');
|
|
|
|
if (match(';')) {
|
|
lex();
|
|
}
|
|
|
|
return node.finishDoWhileStatement(body, test);
|
|
}
|
|
|
|
function parseWhileStatement(node) {
|
|
var test, body, oldInIteration;
|
|
|
|
expectKeyword('while');
|
|
|
|
expect('(');
|
|
|
|
test = parseExpression();
|
|
|
|
expect(')');
|
|
|
|
oldInIteration = state.inIteration;
|
|
state.inIteration = true;
|
|
|
|
body = parseStatement();
|
|
|
|
state.inIteration = oldInIteration;
|
|
|
|
return node.finishWhileStatement(test, body);
|
|
}
|
|
|
|
function parseForStatement(node) {
|
|
var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
|
|
body, oldInIteration, previousAllowIn = state.allowIn;
|
|
|
|
init = test = update = null;
|
|
forIn = true;
|
|
|
|
expectKeyword('for');
|
|
|
|
expect('(');
|
|
|
|
if (match(';')) {
|
|
lex();
|
|
} else {
|
|
if (matchKeyword('var')) {
|
|
init = new Node();
|
|
lex();
|
|
|
|
state.allowIn = false;
|
|
declarations = parseVariableDeclarationList({ inFor: true });
|
|
state.allowIn = previousAllowIn;
|
|
|
|
if (declarations.length === 1 && matchKeyword('in')) {
|
|
init = init.finishVariableDeclaration(declarations);
|
|
lex();
|
|
left = init;
|
|
right = parseExpression();
|
|
init = null;
|
|
} else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
|
|
init = init.finishVariableDeclaration(declarations);
|
|
lex();
|
|
left = init;
|
|
right = parseAssignmentExpression();
|
|
init = null;
|
|
forIn = false;
|
|
} else {
|
|
init = init.finishVariableDeclaration(declarations);
|
|
expect(';');
|
|
}
|
|
} else if (matchKeyword('const') || matchKeyword('let')) {
|
|
init = new Node();
|
|
kind = lex().value;
|
|
|
|
if (!strict && lookahead.value === 'in') {
|
|
init = init.finishIdentifier(kind);
|
|
lex();
|
|
left = init;
|
|
right = parseExpression();
|
|
init = null;
|
|
} else {
|
|
state.allowIn = false;
|
|
declarations = parseBindingList(kind, {inFor: true});
|
|
state.allowIn = previousAllowIn;
|
|
|
|
if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
|
|
init = init.finishLexicalDeclaration(declarations, kind);
|
|
lex();
|
|
left = init;
|
|
right = parseExpression();
|
|
init = null;
|
|
} else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
|
|
init = init.finishLexicalDeclaration(declarations, kind);
|
|
lex();
|
|
left = init;
|
|
right = parseAssignmentExpression();
|
|
init = null;
|
|
forIn = false;
|
|
} else {
|
|
consumeSemicolon();
|
|
init = init.finishLexicalDeclaration(declarations, kind);
|
|
}
|
|
}
|
|
} else {
|
|
initStartToken = lookahead;
|
|
state.allowIn = false;
|
|
init = inheritCoverGrammar(parseAssignmentExpression);
|
|
state.allowIn = previousAllowIn;
|
|
|
|
if (matchKeyword('in')) {
|
|
if (!isAssignmentTarget) {
|
|
tolerateError(Messages.InvalidLHSInForIn);
|
|
}
|
|
|
|
lex();
|
|
reinterpretExpressionAsPattern(init);
|
|
left = init;
|
|
right = parseExpression();
|
|
init = null;
|
|
} else if (matchContextualKeyword('of')) {
|
|
if (!isAssignmentTarget) {
|
|
tolerateError(Messages.InvalidLHSInForLoop);
|
|
}
|
|
|
|
lex();
|
|
reinterpretExpressionAsPattern(init);
|
|
left = init;
|
|
right = parseAssignmentExpression();
|
|
init = null;
|
|
forIn = false;
|
|
} else {
|
|
if (match(',')) {
|
|
initSeq = [init];
|
|
while (match(',')) {
|
|
lex();
|
|
initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
|
|
}
|
|
init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
|
|
}
|
|
expect(';');
|
|
}
|
|
}
|
|
}
|
|
|
|
if (typeof left === 'undefined') {
|
|
|
|
if (!match(';')) {
|
|
test = parseExpression();
|
|
}
|
|
expect(';');
|
|
|
|
if (!match(')')) {
|
|
update = parseExpression();
|
|
}
|
|
}
|
|
|
|
expect(')');
|
|
|
|
oldInIteration = state.inIteration;
|
|
state.inIteration = true;
|
|
|
|
body = isolateCoverGrammar(parseStatement);
|
|
|
|
state.inIteration = oldInIteration;
|
|
|
|
return (typeof left === 'undefined') ?
|
|
node.finishForStatement(init, test, update, body) :
|
|
forIn ? node.finishForInStatement(left, right, body) :
|
|
node.finishForOfStatement(left, right, body);
|
|
}
|
|
|
|
// ECMA-262 13.8 The continue statement
|
|
|
|
function parseContinueStatement(node) {
|
|
var label = null, key;
|
|
|
|
expectKeyword('continue');
|
|
|
|
// Optimize the most common form: 'continue;'.
|
|
if (source.charCodeAt(startIndex) === 0x3B) {
|
|
lex();
|
|
|
|
if (!state.inIteration) {
|
|
throwError(Messages.IllegalContinue);
|
|
}
|
|
|
|
return node.finishContinueStatement(null);
|
|
}
|
|
|
|
if (hasLineTerminator) {
|
|
if (!state.inIteration) {
|
|
throwError(Messages.IllegalContinue);
|
|
}
|
|
|
|
return node.finishContinueStatement(null);
|
|
}
|
|
|
|
if (lookahead.type === Token.Identifier) {
|
|
label = parseVariableIdentifier();
|
|
|
|
key = '$' + label.name;
|
|
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
|
|
throwError(Messages.UnknownLabel, label.name);
|
|
}
|
|
}
|
|
|
|
consumeSemicolon();
|
|
|
|
if (label === null && !state.inIteration) {
|
|
throwError(Messages.IllegalContinue);
|
|
}
|
|
|
|
return node.finishContinueStatement(label);
|
|
}
|
|
|
|
// ECMA-262 13.9 The break statement
|
|
|
|
function parseBreakStatement(node) {
|
|
var label = null, key;
|
|
|
|
expectKeyword('break');
|
|
|
|
// Catch the very common case first: immediately a semicolon (U+003B).
|
|
if (source.charCodeAt(lastIndex) === 0x3B) {
|
|
lex();
|
|
|
|
if (!(state.inIteration || state.inSwitch)) {
|
|
throwError(Messages.IllegalBreak);
|
|
}
|
|
|
|
return node.finishBreakStatement(null);
|
|
}
|
|
|
|
if (hasLineTerminator) {
|
|
if (!(state.inIteration || state.inSwitch)) {
|
|
throwError(Messages.IllegalBreak);
|
|
}
|
|
} else if (lookahead.type === Token.Identifier) {
|
|
label = parseVariableIdentifier();
|
|
|
|
key = '$' + label.name;
|
|
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
|
|
throwError(Messages.UnknownLabel, label.name);
|
|
}
|
|
}
|
|
|
|
consumeSemicolon();
|
|
|
|
if (label === null && !(state.inIteration || state.inSwitch)) {
|
|
throwError(Messages.IllegalBreak);
|
|
}
|
|
|
|
return node.finishBreakStatement(label);
|
|
}
|
|
|
|
// ECMA-262 13.10 The return statement
|
|
|
|
function parseReturnStatement(node) {
|
|
var argument = null;
|
|
|
|
expectKeyword('return');
|
|
|
|
if (!state.inFunctionBody) {
|
|
tolerateError(Messages.IllegalReturn);
|
|
}
|
|
|
|
// 'return' followed by a space and an identifier is very common.
|
|
if (source.charCodeAt(lastIndex) === 0x20) {
|
|
if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
|
|
argument = parseExpression();
|
|
consumeSemicolon();
|
|
return node.finishReturnStatement(argument);
|
|
}
|
|
}
|
|
|
|
if (hasLineTerminator) {
|
|
// HACK
|
|
return node.finishReturnStatement(null);
|
|
}
|
|
|
|
if (!match(';')) {
|
|
if (!match('}') && lookahead.type !== Token.EOF) {
|
|
argument = parseExpression();
|
|
}
|
|
}
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishReturnStatement(argument);
|
|
}
|
|
|
|
// ECMA-262 13.11 The with statement
|
|
|
|
function parseWithStatement(node) {
|
|
var object, body;
|
|
|
|
if (strict) {
|
|
tolerateError(Messages.StrictModeWith);
|
|
}
|
|
|
|
expectKeyword('with');
|
|
|
|
expect('(');
|
|
|
|
object = parseExpression();
|
|
|
|
expect(')');
|
|
|
|
body = parseStatement();
|
|
|
|
return node.finishWithStatement(object, body);
|
|
}
|
|
|
|
// ECMA-262 13.12 The switch statement
|
|
|
|
function parseSwitchCase() {
|
|
var test, consequent = [], statement, node = new Node();
|
|
|
|
if (matchKeyword('default')) {
|
|
lex();
|
|
test = null;
|
|
} else {
|
|
expectKeyword('case');
|
|
test = parseExpression();
|
|
}
|
|
expect(':');
|
|
|
|
while (startIndex < length) {
|
|
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
|
|
break;
|
|
}
|
|
statement = parseStatementListItem();
|
|
consequent.push(statement);
|
|
}
|
|
|
|
return node.finishSwitchCase(test, consequent);
|
|
}
|
|
|
|
function parseSwitchStatement(node) {
|
|
var discriminant, cases, clause, oldInSwitch, defaultFound;
|
|
|
|
expectKeyword('switch');
|
|
|
|
expect('(');
|
|
|
|
discriminant = parseExpression();
|
|
|
|
expect(')');
|
|
|
|
expect('{');
|
|
|
|
cases = [];
|
|
|
|
if (match('}')) {
|
|
lex();
|
|
return node.finishSwitchStatement(discriminant, cases);
|
|
}
|
|
|
|
oldInSwitch = state.inSwitch;
|
|
state.inSwitch = true;
|
|
defaultFound = false;
|
|
|
|
while (startIndex < length) {
|
|
if (match('}')) {
|
|
break;
|
|
}
|
|
clause = parseSwitchCase();
|
|
if (clause.test === null) {
|
|
if (defaultFound) {
|
|
throwError(Messages.MultipleDefaultsInSwitch);
|
|
}
|
|
defaultFound = true;
|
|
}
|
|
cases.push(clause);
|
|
}
|
|
|
|
state.inSwitch = oldInSwitch;
|
|
|
|
expect('}');
|
|
|
|
return node.finishSwitchStatement(discriminant, cases);
|
|
}
|
|
|
|
// ECMA-262 13.14 The throw statement
|
|
|
|
function parseThrowStatement(node) {
|
|
var argument;
|
|
|
|
expectKeyword('throw');
|
|
|
|
if (hasLineTerminator) {
|
|
throwError(Messages.NewlineAfterThrow);
|
|
}
|
|
|
|
argument = parseExpression();
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishThrowStatement(argument);
|
|
}
|
|
|
|
// ECMA-262 13.15 The try statement
|
|
|
|
function parseCatchClause() {
|
|
var param, params = [], paramMap = {}, key, i, body, node = new Node();
|
|
|
|
expectKeyword('catch');
|
|
|
|
expect('(');
|
|
if (match(')')) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
param = parsePattern(params);
|
|
for (i = 0; i < params.length; i++) {
|
|
key = '$' + params[i].value;
|
|
if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
|
|
tolerateError(Messages.DuplicateBinding, params[i].value);
|
|
}
|
|
paramMap[key] = true;
|
|
}
|
|
|
|
// ECMA-262 12.14.1
|
|
if (strict && isRestrictedWord(param.name)) {
|
|
tolerateError(Messages.StrictCatchVariable);
|
|
}
|
|
|
|
expect(')');
|
|
body = parseBlock();
|
|
return node.finishCatchClause(param, body);
|
|
}
|
|
|
|
function parseTryStatement(node) {
|
|
var block, handler = null, finalizer = null;
|
|
|
|
expectKeyword('try');
|
|
|
|
block = parseBlock();
|
|
|
|
if (matchKeyword('catch')) {
|
|
handler = parseCatchClause();
|
|
}
|
|
|
|
if (matchKeyword('finally')) {
|
|
lex();
|
|
finalizer = parseBlock();
|
|
}
|
|
|
|
if (!handler && !finalizer) {
|
|
throwError(Messages.NoCatchOrFinally);
|
|
}
|
|
|
|
return node.finishTryStatement(block, handler, finalizer);
|
|
}
|
|
|
|
// ECMA-262 13.16 The debugger statement
|
|
|
|
function parseDebuggerStatement(node) {
|
|
expectKeyword('debugger');
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishDebuggerStatement();
|
|
}
|
|
|
|
// 13 Statements
|
|
|
|
function parseStatement() {
|
|
var type = lookahead.type,
|
|
expr,
|
|
labeledBody,
|
|
key,
|
|
node;
|
|
|
|
if (type === Token.EOF) {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
|
|
if (type === Token.Punctuator && lookahead.value === '{') {
|
|
return parseBlock();
|
|
}
|
|
isAssignmentTarget = isBindingElement = true;
|
|
node = new Node();
|
|
|
|
if (type === Token.Punctuator) {
|
|
switch (lookahead.value) {
|
|
case ';':
|
|
return parseEmptyStatement(node);
|
|
case '(':
|
|
return parseExpressionStatement(node);
|
|
default:
|
|
break;
|
|
}
|
|
} else if (type === Token.Keyword) {
|
|
switch (lookahead.value) {
|
|
case 'break':
|
|
return parseBreakStatement(node);
|
|
case 'continue':
|
|
return parseContinueStatement(node);
|
|
case 'debugger':
|
|
return parseDebuggerStatement(node);
|
|
case 'do':
|
|
return parseDoWhileStatement(node);
|
|
case 'for':
|
|
return parseForStatement(node);
|
|
case 'function':
|
|
return parseFunctionDeclaration(node);
|
|
case 'if':
|
|
return parseIfStatement(node);
|
|
case 'return':
|
|
return parseReturnStatement(node);
|
|
case 'switch':
|
|
return parseSwitchStatement(node);
|
|
case 'throw':
|
|
return parseThrowStatement(node);
|
|
case 'try':
|
|
return parseTryStatement(node);
|
|
case 'var':
|
|
return parseVariableStatement(node);
|
|
case 'while':
|
|
return parseWhileStatement(node);
|
|
case 'with':
|
|
return parseWithStatement(node);
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
expr = parseExpression();
|
|
|
|
// ECMA-262 12.12 Labelled Statements
|
|
if ((expr.type === Syntax.Identifier) && match(':')) {
|
|
lex();
|
|
|
|
key = '$' + expr.name;
|
|
if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
|
|
throwError(Messages.Redeclaration, 'Label', expr.name);
|
|
}
|
|
|
|
state.labelSet[key] = true;
|
|
labeledBody = parseStatement();
|
|
delete state.labelSet[key];
|
|
return node.finishLabeledStatement(expr, labeledBody);
|
|
}
|
|
|
|
consumeSemicolon();
|
|
|
|
return node.finishExpressionStatement(expr);
|
|
}
|
|
|
|
// ECMA-262 14.1 Function Definition
|
|
|
|
function parseFunctionSourceElements() {
|
|
var statement, body = [], token, directive, firstRestricted,
|
|
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody,
|
|
node = new Node();
|
|
|
|
expect('{');
|
|
|
|
while (startIndex < length) {
|
|
if (lookahead.type !== Token.StringLiteral) {
|
|
break;
|
|
}
|
|
token = lookahead;
|
|
|
|
statement = parseStatementListItem();
|
|
body.push(statement);
|
|
if (statement.expression.type !== Syntax.Literal) {
|
|
// this is not directive
|
|
break;
|
|
}
|
|
directive = source.slice(token.start + 1, token.end - 1);
|
|
if (directive === 'use strict') {
|
|
strict = true;
|
|
if (firstRestricted) {
|
|
tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
|
|
}
|
|
} else {
|
|
if (!firstRestricted && token.octal) {
|
|
firstRestricted = token;
|
|
}
|
|
}
|
|
}
|
|
|
|
oldLabelSet = state.labelSet;
|
|
oldInIteration = state.inIteration;
|
|
oldInSwitch = state.inSwitch;
|
|
oldInFunctionBody = state.inFunctionBody;
|
|
|
|
state.labelSet = {};
|
|
state.inIteration = false;
|
|
state.inSwitch = false;
|
|
state.inFunctionBody = true;
|
|
|
|
while (startIndex < length) {
|
|
if (match('}')) {
|
|
break;
|
|
}
|
|
body.push(parseStatementListItem());
|
|
}
|
|
|
|
expect('}');
|
|
|
|
state.labelSet = oldLabelSet;
|
|
state.inIteration = oldInIteration;
|
|
state.inSwitch = oldInSwitch;
|
|
state.inFunctionBody = oldInFunctionBody;
|
|
|
|
return node.finishBlockStatement(body);
|
|
}
|
|
|
|
function validateParam(options, param, name) {
|
|
var key = '$' + name;
|
|
if (strict) {
|
|
if (isRestrictedWord(name)) {
|
|
options.stricted = param;
|
|
options.message = Messages.StrictParamName;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
|
|
options.stricted = param;
|
|
options.message = Messages.StrictParamDupe;
|
|
}
|
|
} else if (!options.firstRestricted) {
|
|
if (isRestrictedWord(name)) {
|
|
options.firstRestricted = param;
|
|
options.message = Messages.StrictParamName;
|
|
} else if (isStrictModeReservedWord(name)) {
|
|
options.firstRestricted = param;
|
|
options.message = Messages.StrictReservedWord;
|
|
} else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
|
|
options.stricted = param;
|
|
options.message = Messages.StrictParamDupe;
|
|
}
|
|
}
|
|
options.paramSet[key] = true;
|
|
}
|
|
|
|
function parseParam(options) {
|
|
var token, param, params = [], i, def;
|
|
|
|
token = lookahead;
|
|
if (token.value === '...') {
|
|
param = parseRestElement(params);
|
|
validateParam(options, param.argument, param.argument.name);
|
|
options.params.push(param);
|
|
options.defaults.push(null);
|
|
return false;
|
|
}
|
|
|
|
param = parsePatternWithDefault(params);
|
|
for (i = 0; i < params.length; i++) {
|
|
validateParam(options, params[i], params[i].value);
|
|
}
|
|
|
|
if (param.type === Syntax.AssignmentPattern) {
|
|
def = param.right;
|
|
param = param.left;
|
|
++options.defaultCount;
|
|
}
|
|
|
|
options.params.push(param);
|
|
options.defaults.push(def);
|
|
|
|
return !match(')');
|
|
}
|
|
|
|
function parseParams(firstRestricted) {
|
|
var options;
|
|
|
|
options = {
|
|
params: [],
|
|
defaultCount: 0,
|
|
defaults: [],
|
|
firstRestricted: firstRestricted
|
|
};
|
|
|
|
expect('(');
|
|
|
|
if (!match(')')) {
|
|
options.paramSet = {};
|
|
while (startIndex < length) {
|
|
if (!parseParam(options)) {
|
|
break;
|
|
}
|
|
expect(',');
|
|
}
|
|
}
|
|
|
|
expect(')');
|
|
|
|
if (options.defaultCount === 0) {
|
|
options.defaults = [];
|
|
}
|
|
|
|
return {
|
|
params: options.params,
|
|
defaults: options.defaults,
|
|
stricted: options.stricted,
|
|
firstRestricted: options.firstRestricted,
|
|
message: options.message
|
|
};
|
|
}
|
|
|
|
function parseFunctionDeclaration(node, identifierIsOptional) {
|
|
var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
|
|
isGenerator, previousAllowYield;
|
|
|
|
previousAllowYield = state.allowYield;
|
|
|
|
expectKeyword('function');
|
|
|
|
isGenerator = match('*');
|
|
if (isGenerator) {
|
|
lex();
|
|
}
|
|
|
|
if (!identifierIsOptional || !match('(')) {
|
|
token = lookahead;
|
|
id = parseVariableIdentifier();
|
|
if (strict) {
|
|
if (isRestrictedWord(token.value)) {
|
|
tolerateUnexpectedToken(token, Messages.StrictFunctionName);
|
|
}
|
|
} else {
|
|
if (isRestrictedWord(token.value)) {
|
|
firstRestricted = token;
|
|
message = Messages.StrictFunctionName;
|
|
} else if (isStrictModeReservedWord(token.value)) {
|
|
firstRestricted = token;
|
|
message = Messages.StrictReservedWord;
|
|
}
|
|
}
|
|
}
|
|
|
|
state.allowYield = !isGenerator;
|
|
tmp = parseParams(firstRestricted);
|
|
params = tmp.params;
|
|
defaults = tmp.defaults;
|
|
stricted = tmp.stricted;
|
|
firstRestricted = tmp.firstRestricted;
|
|
if (tmp.message) {
|
|
message = tmp.message;
|
|
}
|
|
|
|
|
|
previousStrict = strict;
|
|
body = parseFunctionSourceElements();
|
|
if (strict && firstRestricted) {
|
|
throwUnexpectedToken(firstRestricted, message);
|
|
}
|
|
if (strict && stricted) {
|
|
tolerateUnexpectedToken(stricted, message);
|
|
}
|
|
|
|
strict = previousStrict;
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
|
|
}
|
|
|
|
function parseFunctionExpression() {
|
|
var token, id = null, stricted, firstRestricted, message, tmp,
|
|
params = [], defaults = [], body, previousStrict, node = new Node(),
|
|
isGenerator, previousAllowYield;
|
|
|
|
previousAllowYield = state.allowYield;
|
|
|
|
expectKeyword('function');
|
|
|
|
isGenerator = match('*');
|
|
if (isGenerator) {
|
|
lex();
|
|
}
|
|
|
|
state.allowYield = !isGenerator;
|
|
if (!match('(')) {
|
|
token = lookahead;
|
|
id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
|
|
if (strict) {
|
|
if (isRestrictedWord(token.value)) {
|
|
tolerateUnexpectedToken(token, Messages.StrictFunctionName);
|
|
}
|
|
} else {
|
|
if (isRestrictedWord(token.value)) {
|
|
firstRestricted = token;
|
|
message = Messages.StrictFunctionName;
|
|
} else if (isStrictModeReservedWord(token.value)) {
|
|
firstRestricted = token;
|
|
message = Messages.StrictReservedWord;
|
|
}
|
|
}
|
|
}
|
|
|
|
tmp = parseParams(firstRestricted);
|
|
params = tmp.params;
|
|
defaults = tmp.defaults;
|
|
stricted = tmp.stricted;
|
|
firstRestricted = tmp.firstRestricted;
|
|
if (tmp.message) {
|
|
message = tmp.message;
|
|
}
|
|
|
|
previousStrict = strict;
|
|
body = parseFunctionSourceElements();
|
|
if (strict && firstRestricted) {
|
|
throwUnexpectedToken(firstRestricted, message);
|
|
}
|
|
if (strict && stricted) {
|
|
tolerateUnexpectedToken(stricted, message);
|
|
}
|
|
strict = previousStrict;
|
|
state.allowYield = previousAllowYield;
|
|
|
|
return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
|
|
}
|
|
|
|
// ECMA-262 14.5 Class Definitions
|
|
|
|
function parseClassBody() {
|
|
var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
|
|
|
|
classBody = new Node();
|
|
|
|
expect('{');
|
|
body = [];
|
|
while (!match('}')) {
|
|
if (match(';')) {
|
|
lex();
|
|
} else {
|
|
method = new Node();
|
|
token = lookahead;
|
|
isStatic = false;
|
|
computed = match('[');
|
|
if (match('*')) {
|
|
lex();
|
|
} else {
|
|
key = parseObjectPropertyKey();
|
|
if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
|
|
token = lookahead;
|
|
isStatic = true;
|
|
computed = match('[');
|
|
if (match('*')) {
|
|
lex();
|
|
} else {
|
|
key = parseObjectPropertyKey();
|
|
}
|
|
}
|
|
}
|
|
method = tryParseMethodDefinition(token, key, computed, method);
|
|
if (method) {
|
|
method['static'] = isStatic; // jscs:ignore requireDotNotation
|
|
if (method.kind === 'init') {
|
|
method.kind = 'method';
|
|
}
|
|
if (!isStatic) {
|
|
if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
|
|
if (method.kind !== 'method' || !method.method || method.value.generator) {
|
|
throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
|
|
}
|
|
if (hasConstructor) {
|
|
throwUnexpectedToken(token, Messages.DuplicateConstructor);
|
|
} else {
|
|
hasConstructor = true;
|
|
}
|
|
method.kind = 'constructor';
|
|
}
|
|
} else {
|
|
if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
|
|
throwUnexpectedToken(token, Messages.StaticPrototype);
|
|
}
|
|
}
|
|
method.type = Syntax.MethodDefinition;
|
|
delete method.method;
|
|
delete method.shorthand;
|
|
body.push(method);
|
|
} else {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
}
|
|
}
|
|
lex();
|
|
return classBody.finishClassBody(body);
|
|
}
|
|
|
|
function parseClassDeclaration(identifierIsOptional) {
|
|
var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
|
|
strict = true;
|
|
|
|
expectKeyword('class');
|
|
|
|
if (!identifierIsOptional || lookahead.type === Token.Identifier) {
|
|
id = parseVariableIdentifier();
|
|
}
|
|
|
|
if (matchKeyword('extends')) {
|
|
lex();
|
|
superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
|
|
}
|
|
classBody = parseClassBody();
|
|
strict = previousStrict;
|
|
|
|
return classNode.finishClassDeclaration(id, superClass, classBody);
|
|
}
|
|
|
|
function parseClassExpression() {
|
|
var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
|
|
strict = true;
|
|
|
|
expectKeyword('class');
|
|
|
|
if (lookahead.type === Token.Identifier) {
|
|
id = parseVariableIdentifier();
|
|
}
|
|
|
|
if (matchKeyword('extends')) {
|
|
lex();
|
|
superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
|
|
}
|
|
classBody = parseClassBody();
|
|
strict = previousStrict;
|
|
|
|
return classNode.finishClassExpression(id, superClass, classBody);
|
|
}
|
|
|
|
// ECMA-262 15.2 Modules
|
|
|
|
function parseModuleSpecifier() {
|
|
var node = new Node();
|
|
|
|
if (lookahead.type !== Token.StringLiteral) {
|
|
throwError(Messages.InvalidModuleSpecifier);
|
|
}
|
|
return node.finishLiteral(lex());
|
|
}
|
|
|
|
// ECMA-262 15.2.3 Exports
|
|
|
|
function parseExportSpecifier() {
|
|
var exported, local, node = new Node(), def;
|
|
if (matchKeyword('default')) {
|
|
// export {default} from 'something';
|
|
def = new Node();
|
|
lex();
|
|
local = def.finishIdentifier('default');
|
|
} else {
|
|
local = parseVariableIdentifier();
|
|
}
|
|
if (matchContextualKeyword('as')) {
|
|
lex();
|
|
exported = parseNonComputedProperty();
|
|
}
|
|
return node.finishExportSpecifier(local, exported);
|
|
}
|
|
|
|
function parseExportNamedDeclaration(node) {
|
|
var declaration = null,
|
|
isExportFromIdentifier,
|
|
src = null, specifiers = [];
|
|
|
|
// non-default export
|
|
if (lookahead.type === Token.Keyword) {
|
|
// covers:
|
|
// export var f = 1;
|
|
switch (lookahead.value) {
|
|
case 'let':
|
|
case 'const':
|
|
declaration = parseLexicalDeclaration({inFor: false});
|
|
return node.finishExportNamedDeclaration(declaration, specifiers, null);
|
|
case 'var':
|
|
case 'class':
|
|
case 'function':
|
|
declaration = parseStatementListItem();
|
|
return node.finishExportNamedDeclaration(declaration, specifiers, null);
|
|
}
|
|
}
|
|
|
|
expect('{');
|
|
while (!match('}')) {
|
|
isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
|
|
specifiers.push(parseExportSpecifier());
|
|
if (!match('}')) {
|
|
expect(',');
|
|
if (match('}')) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
expect('}');
|
|
|
|
if (matchContextualKeyword('from')) {
|
|
// covering:
|
|
// export {default} from 'foo';
|
|
// export {foo} from 'foo';
|
|
lex();
|
|
src = parseModuleSpecifier();
|
|
consumeSemicolon();
|
|
} else if (isExportFromIdentifier) {
|
|
// covering:
|
|
// export {default}; // missing fromClause
|
|
throwError(lookahead.value ?
|
|
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
|
|
} else {
|
|
// cover
|
|
// export {foo};
|
|
consumeSemicolon();
|
|
}
|
|
return node.finishExportNamedDeclaration(declaration, specifiers, src);
|
|
}
|
|
|
|
function parseExportDefaultDeclaration(node) {
|
|
var declaration = null,
|
|
expression = null;
|
|
|
|
// covers:
|
|
// export default ...
|
|
expectKeyword('default');
|
|
|
|
if (matchKeyword('function')) {
|
|
// covers:
|
|
// export default function foo () {}
|
|
// export default function () {}
|
|
declaration = parseFunctionDeclaration(new Node(), true);
|
|
return node.finishExportDefaultDeclaration(declaration);
|
|
}
|
|
if (matchKeyword('class')) {
|
|
declaration = parseClassDeclaration(true);
|
|
return node.finishExportDefaultDeclaration(declaration);
|
|
}
|
|
|
|
if (matchContextualKeyword('from')) {
|
|
throwError(Messages.UnexpectedToken, lookahead.value);
|
|
}
|
|
|
|
// covers:
|
|
// export default {};
|
|
// export default [];
|
|
// export default (1 + 2);
|
|
if (match('{')) {
|
|
expression = parseObjectInitializer();
|
|
} else if (match('[')) {
|
|
expression = parseArrayInitializer();
|
|
} else {
|
|
expression = parseAssignmentExpression();
|
|
}
|
|
consumeSemicolon();
|
|
return node.finishExportDefaultDeclaration(expression);
|
|
}
|
|
|
|
function parseExportAllDeclaration(node) {
|
|
var src;
|
|
|
|
// covers:
|
|
// export * from 'foo';
|
|
expect('*');
|
|
if (!matchContextualKeyword('from')) {
|
|
throwError(lookahead.value ?
|
|
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
|
|
}
|
|
lex();
|
|
src = parseModuleSpecifier();
|
|
consumeSemicolon();
|
|
|
|
return node.finishExportAllDeclaration(src);
|
|
}
|
|
|
|
function parseExportDeclaration() {
|
|
var node = new Node();
|
|
if (state.inFunctionBody) {
|
|
throwError(Messages.IllegalExportDeclaration);
|
|
}
|
|
|
|
expectKeyword('export');
|
|
|
|
if (matchKeyword('default')) {
|
|
return parseExportDefaultDeclaration(node);
|
|
}
|
|
if (match('*')) {
|
|
return parseExportAllDeclaration(node);
|
|
}
|
|
return parseExportNamedDeclaration(node);
|
|
}
|
|
|
|
// ECMA-262 15.2.2 Imports
|
|
|
|
function parseImportSpecifier() {
|
|
// import {<foo as bar>} ...;
|
|
var local, imported, node = new Node();
|
|
|
|
imported = parseNonComputedProperty();
|
|
if (matchContextualKeyword('as')) {
|
|
lex();
|
|
local = parseVariableIdentifier();
|
|
}
|
|
|
|
return node.finishImportSpecifier(local, imported);
|
|
}
|
|
|
|
function parseNamedImports() {
|
|
var specifiers = [];
|
|
// {foo, bar as bas}
|
|
expect('{');
|
|
while (!match('}')) {
|
|
specifiers.push(parseImportSpecifier());
|
|
if (!match('}')) {
|
|
expect(',');
|
|
if (match('}')) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
expect('}');
|
|
return specifiers;
|
|
}
|
|
|
|
function parseImportDefaultSpecifier() {
|
|
// import <foo> ...;
|
|
var local, node = new Node();
|
|
|
|
local = parseNonComputedProperty();
|
|
|
|
return node.finishImportDefaultSpecifier(local);
|
|
}
|
|
|
|
function parseImportNamespaceSpecifier() {
|
|
// import <* as foo> ...;
|
|
var local, node = new Node();
|
|
|
|
expect('*');
|
|
if (!matchContextualKeyword('as')) {
|
|
throwError(Messages.NoAsAfterImportNamespace);
|
|
}
|
|
lex();
|
|
local = parseNonComputedProperty();
|
|
|
|
return node.finishImportNamespaceSpecifier(local);
|
|
}
|
|
|
|
function parseImportDeclaration() {
|
|
var specifiers = [], src, node = new Node();
|
|
|
|
if (state.inFunctionBody) {
|
|
throwError(Messages.IllegalImportDeclaration);
|
|
}
|
|
|
|
expectKeyword('import');
|
|
|
|
if (lookahead.type === Token.StringLiteral) {
|
|
// import 'foo';
|
|
src = parseModuleSpecifier();
|
|
} else {
|
|
|
|
if (match('{')) {
|
|
// import {bar}
|
|
specifiers = specifiers.concat(parseNamedImports());
|
|
} else if (match('*')) {
|
|
// import * as foo
|
|
specifiers.push(parseImportNamespaceSpecifier());
|
|
} else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
|
|
// import foo
|
|
specifiers.push(parseImportDefaultSpecifier());
|
|
if (match(',')) {
|
|
lex();
|
|
if (match('*')) {
|
|
// import foo, * as foo
|
|
specifiers.push(parseImportNamespaceSpecifier());
|
|
} else if (match('{')) {
|
|
// import foo, {bar}
|
|
specifiers = specifiers.concat(parseNamedImports());
|
|
} else {
|
|
throwUnexpectedToken(lookahead);
|
|
}
|
|
}
|
|
} else {
|
|
throwUnexpectedToken(lex());
|
|
}
|
|
|
|
if (!matchContextualKeyword('from')) {
|
|
throwError(lookahead.value ?
|
|
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
|
|
}
|
|
lex();
|
|
src = parseModuleSpecifier();
|
|
}
|
|
|
|
consumeSemicolon();
|
|
return node.finishImportDeclaration(specifiers, src);
|
|
}
|
|
|
|
// ECMA-262 15.1 Scripts
|
|
|
|
function parseScriptBody() {
|
|
var statement, body = [], token, directive, firstRestricted;
|
|
|
|
while (startIndex < length) {
|
|
token = lookahead;
|
|
if (token.type !== Token.StringLiteral) {
|
|
break;
|
|
}
|
|
|
|
statement = parseStatementListItem();
|
|
body.push(statement);
|
|
if (statement.expression.type !== Syntax.Literal) {
|
|
// this is not directive
|
|
break;
|
|
}
|
|
directive = source.slice(token.start + 1, token.end - 1);
|
|
if (directive === 'use strict') {
|
|
strict = true;
|
|
if (firstRestricted) {
|
|
tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
|
|
}
|
|
} else {
|
|
if (!firstRestricted && token.octal) {
|
|
firstRestricted = token;
|
|
}
|
|
}
|
|
}
|
|
|
|
while (startIndex < length) {
|
|
statement = parseStatementListItem();
|
|
/* istanbul ignore if */
|
|
if (typeof statement === 'undefined') {
|
|
break;
|
|
}
|
|
body.push(statement);
|
|
}
|
|
return body;
|
|
}
|
|
|
|
function parseProgram() {
|
|
var body, node;
|
|
|
|
peek();
|
|
node = new Node();
|
|
|
|
body = parseScriptBody();
|
|
return node.finishProgram(body, state.sourceType);
|
|
}
|
|
|
|
function filterTokenLocation() {
|
|
var i, entry, token, tokens = [];
|
|
|
|
for (i = 0; i < extra.tokens.length; ++i) {
|
|
entry = extra.tokens[i];
|
|
token = {
|
|
type: entry.type,
|
|
value: entry.value
|
|
};
|
|
if (entry.regex) {
|
|
token.regex = {
|
|
pattern: entry.regex.pattern,
|
|
flags: entry.regex.flags
|
|
};
|
|
}
|
|
if (extra.range) {
|
|
token.range = entry.range;
|
|
}
|
|
if (extra.loc) {
|
|
token.loc = entry.loc;
|
|
}
|
|
tokens.push(token);
|
|
}
|
|
|
|
extra.tokens = tokens;
|
|
}
|
|
|
|
function tokenize(code, options, delegate) {
|
|
var toString,
|
|
tokens;
|
|
|
|
toString = String;
|
|
if (typeof code !== 'string' && !(code instanceof String)) {
|
|
code = toString(code);
|
|
}
|
|
|
|
source = code;
|
|
index = 0;
|
|
lineNumber = (source.length > 0) ? 1 : 0;
|
|
lineStart = 0;
|
|
startIndex = index;
|
|
startLineNumber = lineNumber;
|
|
startLineStart = lineStart;
|
|
length = source.length;
|
|
lookahead = null;
|
|
state = {
|
|
allowIn: true,
|
|
allowYield: true,
|
|
labelSet: {},
|
|
inFunctionBody: false,
|
|
inIteration: false,
|
|
inSwitch: false,
|
|
lastCommentStart: -1,
|
|
curlyStack: []
|
|
};
|
|
|
|
extra = {};
|
|
|
|
// Options matching.
|
|
options = options || {};
|
|
|
|
// Of course we collect tokens here.
|
|
options.tokens = true;
|
|
extra.tokens = [];
|
|
extra.tokenValues = [];
|
|
extra.tokenize = true;
|
|
extra.delegate = delegate;
|
|
|
|
// The following two fields are necessary to compute the Regex tokens.
|
|
extra.openParenToken = -1;
|
|
extra.openCurlyToken = -1;
|
|
|
|
extra.range = (typeof options.range === 'boolean') && options.range;
|
|
extra.loc = (typeof options.loc === 'boolean') && options.loc;
|
|
|
|
if (typeof options.comment === 'boolean' && options.comment) {
|
|
extra.comments = [];
|
|
}
|
|
if (typeof options.tolerant === 'boolean' && options.tolerant) {
|
|
extra.errors = [];
|
|
}
|
|
|
|
try {
|
|
peek();
|
|
if (lookahead.type === Token.EOF) {
|
|
return extra.tokens;
|
|
}
|
|
|
|
lex();
|
|
while (lookahead.type !== Token.EOF) {
|
|
try {
|
|
lex();
|
|
} catch (lexError) {
|
|
if (extra.errors) {
|
|
recordError(lexError);
|
|
// We have to break on the first error
|
|
// to avoid infinite loops.
|
|
break;
|
|
} else {
|
|
throw lexError;
|
|
}
|
|
}
|
|
}
|
|
|
|
tokens = extra.tokens;
|
|
if (typeof extra.errors !== 'undefined') {
|
|
tokens.errors = extra.errors;
|
|
}
|
|
} catch (e) {
|
|
throw e;
|
|
} finally {
|
|
extra = {};
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
function parse(code, options) {
|
|
var program, toString;
|
|
|
|
toString = String;
|
|
if (typeof code !== 'string' && !(code instanceof String)) {
|
|
code = toString(code);
|
|
}
|
|
|
|
source = code;
|
|
index = 0;
|
|
lineNumber = (source.length > 0) ? 1 : 0;
|
|
lineStart = 0;
|
|
startIndex = index;
|
|
startLineNumber = lineNumber;
|
|
startLineStart = lineStart;
|
|
length = source.length;
|
|
lookahead = null;
|
|
state = {
|
|
allowIn: true,
|
|
allowYield: true,
|
|
labelSet: {},
|
|
inFunctionBody: false,
|
|
inIteration: false,
|
|
inSwitch: false,
|
|
lastCommentStart: -1,
|
|
curlyStack: [],
|
|
sourceType: 'script'
|
|
};
|
|
strict = false;
|
|
|
|
extra = {};
|
|
if (typeof options !== 'undefined') {
|
|
extra.range = (typeof options.range === 'boolean') && options.range;
|
|
extra.loc = (typeof options.loc === 'boolean') && options.loc;
|
|
extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
|
|
|
|
if (extra.loc && options.source !== null && options.source !== undefined) {
|
|
extra.source = toString(options.source);
|
|
}
|
|
|
|
if (typeof options.tokens === 'boolean' && options.tokens) {
|
|
extra.tokens = [];
|
|
}
|
|
if (typeof options.comment === 'boolean' && options.comment) {
|
|
extra.comments = [];
|
|
}
|
|
if (typeof options.tolerant === 'boolean' && options.tolerant) {
|
|
extra.errors = [];
|
|
}
|
|
if (extra.attachComment) {
|
|
extra.range = true;
|
|
extra.comments = [];
|
|
extra.bottomRightStack = [];
|
|
extra.trailingComments = [];
|
|
extra.leadingComments = [];
|
|
}
|
|
if (options.sourceType === 'module') {
|
|
// very restrictive condition for now
|
|
state.sourceType = options.sourceType;
|
|
strict = true;
|
|
}
|
|
}
|
|
|
|
try {
|
|
program = parseProgram();
|
|
if (typeof extra.comments !== 'undefined') {
|
|
program.comments = extra.comments;
|
|
}
|
|
if (typeof extra.tokens !== 'undefined') {
|
|
filterTokenLocation();
|
|
program.tokens = extra.tokens;
|
|
}
|
|
if (typeof extra.errors !== 'undefined') {
|
|
program.errors = extra.errors;
|
|
}
|
|
} catch (e) {
|
|
throw e;
|
|
} finally {
|
|
extra = {};
|
|
}
|
|
|
|
return program;
|
|
}
|
|
|
|
// Sync with *.json manifests.
|
|
exports.version = '2.7.3';
|
|
|
|
exports.tokenize = tokenize;
|
|
|
|
exports.parse = parse;
|
|
|
|
// Deep copy.
|
|
/* istanbul ignore next */
|
|
exports.Syntax = (function () {
|
|
var name, types = {};
|
|
|
|
if (typeof Object.create === 'function') {
|
|
types = Object.create(null);
|
|
}
|
|
|
|
for (name in Syntax) {
|
|
if (Syntax.hasOwnProperty(name)) {
|
|
types[name] = Syntax[name];
|
|
}
|
|
}
|
|
|
|
if (typeof Object.freeze === 'function') {
|
|
Object.freeze(types);
|
|
}
|
|
|
|
return types;
|
|
}());
|
|
|
|
}));
|
|
/* vim: set sw=4 ts=4 et tw=80 : */
|
|
|
|
|
|
/***/ }),
|
|
/* 205 */
|
|
/***/ (function(module, exports) {
|
|
|
|
// Taken from https://github.com/toolness/slowmo-js.
|
|
"use strict";
|
|
function defaultInserter(name) {
|
|
return function (node) {
|
|
return name + '();';
|
|
};
|
|
}
|
|
var LOOP_CHECK_FUNC_NAME = '__loopCheck';
|
|
function LoopInserter(fn) {
|
|
return function (node) {
|
|
if (node.type === 'ForStatement' ||
|
|
node.type === 'WhileStatement' ||
|
|
node.type === 'DoWhileStatement') {
|
|
var loopCheckCode = {
|
|
type: 'ExpressionStatement',
|
|
expression: {
|
|
type: 'CallExpression',
|
|
callee: {
|
|
type: 'Identifier',
|
|
name: LOOP_CHECK_FUNC_NAME
|
|
},
|
|
arguments: [
|
|
{
|
|
type: 'Literal',
|
|
value: JSON.stringify(node.range)
|
|
}
|
|
]
|
|
}
|
|
};
|
|
if (node.body.type === 'BlockStatement') {
|
|
// Insert the loop check at the beginning of the block
|
|
node.body.body.unshift(loopCheckCode);
|
|
}
|
|
else {
|
|
// Wrap the single statement body in a block and insert the loop check
|
|
node.body = {
|
|
type: 'BlockStatement',
|
|
body: [loopCheckCode, node.body]
|
|
};
|
|
}
|
|
}
|
|
return '';
|
|
};
|
|
}
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = LoopInserter;
|
|
|
|
|
|
/***/ }),
|
|
/* 206 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
"use strict";
|
|
var esprima = __webpack_require__(204);
|
|
function makeImplicitSketch(code) {
|
|
var ast;
|
|
try {
|
|
ast = esprima.parse(code);
|
|
}
|
|
catch (e) {
|
|
return code;
|
|
}
|
|
for (var i = 0; i < ast.body.length; i++) {
|
|
var statement = ast.body[i];
|
|
if (statement.type === esprima.Syntax.FunctionDeclaration) {
|
|
var funcDecl = statement;
|
|
if (funcDecl.id.name === "setup" || funcDecl.id.name === "draw") {
|
|
return code;
|
|
}
|
|
}
|
|
if (statement.type === esprima.Syntax.VariableDeclaration) {
|
|
var varDecl = statement;
|
|
for (var j = 0; j < varDecl.declarations.length; j++) {
|
|
// This is a bit odd because our ESTree typings indicate
|
|
// that a VariableDeclarator.id is a Pattern, but it
|
|
// seems to actually be an Identifier, so we'll forcibly
|
|
// typecast it as such.
|
|
var id = varDecl.declarations[j].id;
|
|
if (id.name === "setup" || id.name === "draw") {
|
|
return code;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return "function setup() { " + code + " }";
|
|
}
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = makeImplicitSketch;
|
|
|
|
|
|
/***/ }),
|
|
/* 207 */
|
|
/***/ (function(module, exports) {
|
|
|
|
module.exports = "function setup() {\r\n createCanvas(100, 100);\r\n}\r\n\r\nfunction draw() {\r\n background(255, 0, 200);\r\n}\r\n"
|
|
|
|
/***/ }),
|
|
/* 208 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// style-loader: Adds some css to the DOM by adding a <style> tag
|
|
|
|
// load the styles
|
|
var content = __webpack_require__(209);
|
|
if(typeof content === 'string') content = [[module.id, content, '']];
|
|
// add the styles to the DOM
|
|
var update = __webpack_require__(211)(content, {});
|
|
if(content.locals) module.exports = content.locals;
|
|
// Hot Module Replacement
|
|
if(false) {
|
|
// When the styles change, update the <style> tags
|
|
if(!content.locals) {
|
|
module.hot.accept("!!../../../../[email protected]/node_modules/css-loader/index.js?sourceMap!../../../../[email protected]/node_modules/postcss-loader/index.js?sourceMap!./codemirror.css", function() {
|
|
var newContent = require("!!../../../../[email protected]/node_modules/css-loader/index.js?sourceMap!../../../../[email protected]/node_modules/postcss-loader/index.js?sourceMap!./codemirror.css");
|
|
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
|
|
update(newContent);
|
|
});
|
|
}
|
|
// When the module is disposed, remove the <style> tags
|
|
module.hot.dispose(function() { update(); });
|
|
}
|
|
|
|
/***/ }),
|
|
/* 209 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
exports = module.exports = __webpack_require__(210)();
|
|
// imports
|
|
|
|
|
|
// module
|
|
exports.push([module.id, "/* BASICS */\n\n.CodeMirror {\n /* Set height, width, borders, and global font properties here */\n font-family: monospace;\n height: 300px;\n color: black;\n direction: ltr;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre.CodeMirror-line,\n.CodeMirror pre.CodeMirror-line-like {\n padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n border-right: 1px solid #ddd;\n background-color: #f7f7f7;\n white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n padding: 0 3px 0 5px;\n min-width: 20px;\n text-align: right;\n color: #999;\n white-space: nowrap;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror-cursor {\n border-left: 1px solid black;\n border-right: none;\n width: 0;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n border-left: 1px solid silver;\n}\n.cm-fat-cursor .CodeMirror-cursor {\n width: auto;\n border: 0 !important;\n background: #7e7;\n}\n.cm-fat-cursor div.CodeMirror-cursors {\n z-index: 1;\n}\n.cm-fat-cursor .CodeMirror-line::-moz-selection,\n.cm-fat-cursor .CodeMirror-line > span::-moz-selection, \n.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; }\n.cm-fat-cursor .CodeMirror-line::selection,\n.cm-fat-cursor .CodeMirror-line > span::selection, \n.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; }\n.cm-fat-cursor .CodeMirror-line::-moz-selection,\n.cm-fat-cursor .CodeMirror-line > span::-moz-selection,\n.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; }\n.cm-fat-cursor { caret-color: transparent; }\n@keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\n.CodeMirror-overwrite .CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; text-decoration: inherit; }\n\n.CodeMirror-rulers {\n position: absolute;\n left: 0; right: 0; top: -50px; bottom: 0;\n overflow: hidden;\n}\n.CodeMirror-ruler {\n border-left: 1px solid #ccc;\n top: 0; bottom: 0;\n position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n.CodeMirror-composing { border-bottom: 2px solid; }\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n position: relative;\n overflow: hidden;\n background: white;\n}\n\n.CodeMirror-scroll {\n overflow: scroll !important; /* Things will break if this is overridden */\n /* 50px is the magic margin used to hide the element's real scrollbars */\n /* See overflow: hidden in .CodeMirror */\n margin-bottom: -50px; margin-right: -50px;\n padding-bottom: 50px;\n height: 100%;\n outline: none; /* Prevent dragging from highlighting the element */\n position: relative;\n z-index: 0;\n}\n.CodeMirror-sizer {\n position: relative;\n border-right: 50px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n before actual scrolling happens, thus preventing shaking and\n flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n position: absolute;\n z-index: 6;\n display: none;\n outline: none;\n}\n.CodeMirror-vscrollbar {\n right: 0; top: 0;\n overflow-x: hidden;\n overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n bottom: 0; left: 0;\n overflow-y: hidden;\n overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n position: absolute; left: 0; top: 0;\n min-height: 100%;\n z-index: 3;\n}\n.CodeMirror-gutter {\n white-space: normal;\n height: 100%;\n display: inline-block;\n vertical-align: top;\n margin-bottom: -50px;\n}\n.CodeMirror-gutter-wrapper {\n position: absolute;\n z-index: 4;\n background: none !important;\n border: none !important;\n}\n.CodeMirror-gutter-background {\n position: absolute;\n top: 0; bottom: 0;\n z-index: 4;\n}\n.CodeMirror-gutter-elt {\n position: absolute;\n cursor: default;\n z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n cursor: text;\n min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre.CodeMirror-line,\n.CodeMirror pre.CodeMirror-line-like {\n /* Reset some styles that the rest of the page might have set */ border-radius: 0;\n border-width: 0;\n background: transparent;\n font-family: inherit;\n font-size: inherit;\n margin: 0;\n white-space: pre;\n word-wrap: normal;\n line-height: inherit;\n color: inherit;\n z-index: 2;\n position: relative;\n overflow: visible;\n -webkit-tap-highlight-color: transparent;\n font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre.CodeMirror-line,\n.CodeMirror-wrap pre.CodeMirror-line-like {\n word-wrap: break-word;\n white-space: pre-wrap;\n word-break: normal;\n}\n\n.CodeMirror-linebackground {\n position: absolute;\n left: 0; right: 0; top: 0; bottom: 0;\n z-index: 0;\n}\n\n.CodeMirror-linewidget {\n position: relative;\n z-index: 2;\n padding: 0.1px; /* Force widget margins to stay inside of the container */\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n position: absolute;\n width: 100%;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n}\n\n.CodeMirror-cursor {\n position: absolute;\n pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n visibility: hidden;\n position: relative;\n z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n\n.cm-searching {\n background-color: #ffa;\n background-color: rgba(255, 255, 0, .4);\n}\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n /* Hide the cursor when printing */\n .CodeMirror div.CodeMirror-cursors {\n visibility: hidden;\n }\n}\n\n/* See issue #2901 */\n.cm-tab-wrap-hack:after { content: ''; }\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n", "", {"version":3,"sources":["/./node_modules/.store/[email protected]/node_modules/codemirror/lib/codemirror.css"],"names":[],"mappings":"AAAA,YAAY;;AAEZ;EACE,iEAAiE;EACjE,uBAAuB;EACvB,cAAc;EACd,aAAa;EACb,eAAe;CAChB;;AAED,aAAa;;AAEb;EACE,eAAe,CAAC,qCAAqC;CACtD;AACD;;EAEE,eAAe,CAAC,mCAAmC;CACpD;;AAED;EACE,wBAAwB,CAAC,kDAAkD;CAC5E;;AAED,YAAY;;AAEZ;EACE,6BAA6B;EAC7B,0BAA0B;EAC1B,oBAAoB;CACrB;AACD,0BAA0B;AAC1B;EACE,qBAAqB;EACrB,gBAAgB;EAChB,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;CACrB;;AAED,2BAA2B,aAAa,EAAE;AAC1C,kCAAkC,YAAY,EAAE;;AAEhD,YAAY;;AAEZ;EACE,6BAA6B;EAC7B,mBAAmB;EACnB,SAAS;CACV;AACD,8CAA8C;AAC9C;EACE,8BAA8B;CAC/B;AACD;EACE,YAAY;EACZ,qBAAqB;EACrB,iBAAiB;CAClB;AACD;EACE,WAAW;CACZ;AACD;;gEAE2D,wBAAwB,EAAE;AAFrF;;2DAE2D,wBAAwB,EAAE;AACrF;;gEAEgE,wBAAwB,EAAE;AAC1F,iBAAiB,yBAAyB,EAAE;AAW5C;EACE,KAAK;EACL,MAAM,8BAA8B,EAAE;EACtC,OAAO;CACR;;AAED,+DAA+D;AAC/D,2CAA2C;;AAE3C,UAAU,sBAAsB,CAAC,yBAAyB,EAAE;;AAE5D;EACE,mBAAmB;EACnB,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,UAAU;EACzC,iBAAiB;CAClB;AACD;EACE,4BAA4B;EAC5B,OAAO,CAAC,UAAU;EAClB,mBAAmB;CACpB;;AAED,mBAAmB;;AAEnB,0BAA0B,YAAY,CAAC;AACvC,yBAAyB,YAAY,CAAC;AACtC,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,wBAAwB,kBAAkB,CAAC;AAC3C,QAAQ,mBAAmB,CAAC;AAC5B,UAAU,2BAA2B,CAAC;AACtC,mBAAmB,8BAA8B,CAAC;;AAElD,2BAA2B,YAAY,CAAC;AACxC,wBAAwB,YAAY,CAAC;AACrC,0BAA0B,YAAY,CAAC;AACvC,uBAAuB,YAAY,CAAC;AACpC;;;6BAG6B;AAC7B,8BAA8B,YAAY,CAAC;AAC3C,sDAAsD,YAAY,CAAC;AACnE,2BAA2B,YAAY,CAAC;AACxC,0BAA0B,YAAY,CAAC;AACvC,4BAA4B,YAAY,CAAC;AACzC,wBAAwB,YAAY,CAAC;AACrC,6BAA6B,YAAY,CAAC;AAC1C,2BAA2B,YAAY,CAAC;AACxC,2BAA2B,YAAY,CAAC;AACxC,uBAAuB,YAAY,CAAC;AACpC,6BAA6B,YAAY,CAAC;AAC1C,sBAAsB,YAAY,CAAC;AACnC,wBAAwB,YAAY,CAAC;;AAErC,yBAAyB,YAAY,CAAC;AACtC,iBAAiB,YAAY,CAAC;;AAE9B,wBAAwB,yBAAyB,EAAE;;AAEnD,sCAAsC;;AAEtC,gDAAgD,YAAY,CAAC;AAC7D,mDAAmD,YAAY,CAAC;AAChE,0BAA0B,kCAAkC,EAAE;AAC9D,mCAAmC,oBAAoB,CAAC;;AAExD,UAAU;;AAEV;oDACoD;;AAEpD;EACE,mBAAmB;EACnB,iBAAiB;EACjB,kBAAkB;CACnB;;AAED;EACE,4BAA4B,CAAC,6CAA6C;EAC1E,yEAAyE;EACzE,yCAAyC;EACzC,qBAAqB,CAAC,oBAAoB;EAC1C,qBAAqB;EACrB,aAAa;EACb,cAAc,CAAC,oDAAoD;EACnE,mBAAmB;EACnB,WAAW;CACZ;AACD;EACE,mBAAmB;EACnB,qCAAqC;CACtC;;AAED;;2BAE2B;AAC3B;EACE,mBAAmB;EACnB,WAAW;EACX,cAAc;EACd,cAAc;CACf;AACD;EACE,SAAS,CAAC,OAAO;EACjB,mBAAmB;EACnB,mBAAmB;CACpB;AACD;EACE,UAAU,CAAC,QAAQ;EACnB,mBAAmB;EACnB,mBAAmB;CACpB;AACD;EACE,SAAS,CAAC,UAAU;CACrB;AACD;EACE,QAAQ,CAAC,UAAU;CACpB;;AAED;EACE,mBAAmB,CAAC,QAAQ,CAAC,OAAO;EACpC,iBAAiB;EACjB,WAAW;CACZ;AACD;EACE,oBAAoB;EACpB,aAAa;EACb,sBAAsB;EACtB,oBAAoB;EACpB,qBAAqB;CACtB;AACD;EACE,mBAAmB;EACnB,WAAW;EACX,4BAA4B;EAC5B,wBAAwB;CACzB;AACD;EACE,mBAAmB;EACnB,OAAO,CAAC,UAAU;EAClB,WAAW;CACZ;AACD;EACE,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;CACZ;AACD,8CAAyC,6BAA6B,EAAE;AAAxE,yCAAyC,6BAA6B,EAAE;AACxE,8CAA8C,6BAA6B,EAAE;;AAE7E;EACE,aAAa;EACb,gBAAgB,CAAC,2CAA2C;CAC7D;AACD;;EAEE,gEAAgE,CACf,iBAAiB;EAClE,gBAAgB;EAChB,wBAAwB;EACxB,qBAAqB;EACrB,mBAAmB;EACnB,UAAU;EACV,iBAAiB;EACjB,kBAAkB;EAClB,qBAAqB;EACrB,eAAe;EACf,WAAW;EACX,mBAAmB;EACnB,kBAAkB;EAClB,yCAAyC;EAEzC,mCAAmC;CACpC;AACD;;EAEE,sBAAsB;EACtB,sBAAsB;EACtB,mBAAmB;CACpB;;AAED;EACE,mBAAmB;EACnB,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU;EACrC,WAAW;CACZ;;AAED;EACE,mBAAmB;EACnB,WAAW;EACX,eAAe,CAAC,0DAA0D;CAC3E;;AAED,qBAAqB;;AAErB,sBAAsB,eAAe,EAAE;;AAEvC;EACE,cAAc;CACf;;AAED,kEAAkE;AAClE;;;;;EAME,wBAAwB;CACzB;;AAED;EACE,mBAAmB;EACnB,YAAY;EACZ,UAAU;EACV,iBAAiB;EACjB,mBAAmB;CACpB;;AAED;EACE,mBAAmB;EACnB,qBAAqB;CACtB;AACD,0BAA0B,iBAAiB,EAAE;;AAE7C;EACE,mBAAmB;EACnB,mBAAmB;EACnB,WAAW;CACZ;AACD;EACE,oBAAoB;CACrB;;AAED;EACE,oBAAoB;CACrB;;AAED,uBAAuB,oBAAoB,EAAE;AAC7C,2CAA2C,oBAAoB,EAAE;AACjE,wBAAwB,kBAAkB,EAAE;AAC5C,4HAA6G,oBAAoB,EAAE;AAAnI,6GAA6G,oBAAoB,EAAE;AACnI,4HAA4H,oBAAoB,EAAE;;AAElJ;EACE,uBAAuB;EACvB,wCAAwC;CACzC;;AAED,6CAA6C;AAC7C,mBAAmB,oBAAoB,EAAE;;AAEzC;EACE,mCAAmC;EACnC;IACE,mBAAmB;GACpB;CACF;;AAED,qBAAqB;AACrB,0BAA0B,YAAY,EAAE;;AAExC,kEAAkE;AAClE,+BAA+B,iBAAiB,EAAE","file":"codemirror.css","sourcesContent":["/* BASICS */\n\n.CodeMirror {\n /* Set height, width, borders, and global font properties here */\n font-family: monospace;\n height: 300px;\n color: black;\n direction: ltr;\n}\n\n/* PADDING */\n\n.CodeMirror-lines {\n padding: 4px 0; /* Vertical padding around content */\n}\n.CodeMirror pre.CodeMirror-line,\n.CodeMirror pre.CodeMirror-line-like {\n padding: 0 4px; /* Horizontal padding of content */\n}\n\n.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n background-color: white; /* The little square between H and V scrollbars */\n}\n\n/* GUTTER */\n\n.CodeMirror-gutters {\n border-right: 1px solid #ddd;\n background-color: #f7f7f7;\n white-space: nowrap;\n}\n.CodeMirror-linenumbers {}\n.CodeMirror-linenumber {\n padding: 0 3px 0 5px;\n min-width: 20px;\n text-align: right;\n color: #999;\n white-space: nowrap;\n}\n\n.CodeMirror-guttermarker { color: black; }\n.CodeMirror-guttermarker-subtle { color: #999; }\n\n/* CURSOR */\n\n.CodeMirror-cursor {\n border-left: 1px solid black;\n border-right: none;\n width: 0;\n}\n/* Shown when moving in bi-directional text */\n.CodeMirror div.CodeMirror-secondarycursor {\n border-left: 1px solid silver;\n}\n.cm-fat-cursor .CodeMirror-cursor {\n width: auto;\n border: 0 !important;\n background: #7e7;\n}\n.cm-fat-cursor div.CodeMirror-cursors {\n z-index: 1;\n}\n.cm-fat-cursor .CodeMirror-line::selection,\n.cm-fat-cursor .CodeMirror-line > span::selection, \n.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; }\n.cm-fat-cursor .CodeMirror-line::-moz-selection,\n.cm-fat-cursor .CodeMirror-line > span::-moz-selection,\n.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; }\n.cm-fat-cursor { caret-color: transparent; }\n@-moz-keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n@-webkit-keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n@keyframes blink {\n 0% {}\n 50% { background-color: transparent; }\n 100% {}\n}\n\n/* Can style cursor different in overwrite (non-insert) mode */\n.CodeMirror-overwrite .CodeMirror-cursor {}\n\n.cm-tab { display: inline-block; text-decoration: inherit; }\n\n.CodeMirror-rulers {\n position: absolute;\n left: 0; right: 0; top: -50px; bottom: 0;\n overflow: hidden;\n}\n.CodeMirror-ruler {\n border-left: 1px solid #ccc;\n top: 0; bottom: 0;\n position: absolute;\n}\n\n/* DEFAULT THEME */\n\n.cm-s-default .cm-header {color: blue;}\n.cm-s-default .cm-quote {color: #090;}\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-s-default .cm-keyword {color: #708;}\n.cm-s-default .cm-atom {color: #219;}\n.cm-s-default .cm-number {color: #164;}\n.cm-s-default .cm-def {color: #00f;}\n.cm-s-default .cm-variable,\n.cm-s-default .cm-punctuation,\n.cm-s-default .cm-property,\n.cm-s-default .cm-operator {}\n.cm-s-default .cm-variable-2 {color: #05a;}\n.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}\n.cm-s-default .cm-comment {color: #a50;}\n.cm-s-default .cm-string {color: #a11;}\n.cm-s-default .cm-string-2 {color: #f50;}\n.cm-s-default .cm-meta {color: #555;}\n.cm-s-default .cm-qualifier {color: #555;}\n.cm-s-default .cm-builtin {color: #30a;}\n.cm-s-default .cm-bracket {color: #997;}\n.cm-s-default .cm-tag {color: #170;}\n.cm-s-default .cm-attribute {color: #00c;}\n.cm-s-default .cm-hr {color: #999;}\n.cm-s-default .cm-link {color: #00c;}\n\n.cm-s-default .cm-error {color: #f00;}\n.cm-invalidchar {color: #f00;}\n\n.CodeMirror-composing { border-bottom: 2px solid; }\n\n/* Default styles for common addons */\n\ndiv.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}\ndiv.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}\n.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }\n.CodeMirror-activeline-background {background: #e8f2ff;}\n\n/* STOP */\n\n/* The rest of this file contains styles related to the mechanics of\n the editor. You probably shouldn't touch them. */\n\n.CodeMirror {\n position: relative;\n overflow: hidden;\n background: white;\n}\n\n.CodeMirror-scroll {\n overflow: scroll !important; /* Things will break if this is overridden */\n /* 50px is the magic margin used to hide the element's real scrollbars */\n /* See overflow: hidden in .CodeMirror */\n margin-bottom: -50px; margin-right: -50px;\n padding-bottom: 50px;\n height: 100%;\n outline: none; /* Prevent dragging from highlighting the element */\n position: relative;\n z-index: 0;\n}\n.CodeMirror-sizer {\n position: relative;\n border-right: 50px solid transparent;\n}\n\n/* The fake, visible scrollbars. Used to force redraw during scrolling\n before actual scrolling happens, thus preventing shaking and\n flickering artifacts. */\n.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {\n position: absolute;\n z-index: 6;\n display: none;\n outline: none;\n}\n.CodeMirror-vscrollbar {\n right: 0; top: 0;\n overflow-x: hidden;\n overflow-y: scroll;\n}\n.CodeMirror-hscrollbar {\n bottom: 0; left: 0;\n overflow-y: hidden;\n overflow-x: scroll;\n}\n.CodeMirror-scrollbar-filler {\n right: 0; bottom: 0;\n}\n.CodeMirror-gutter-filler {\n left: 0; bottom: 0;\n}\n\n.CodeMirror-gutters {\n position: absolute; left: 0; top: 0;\n min-height: 100%;\n z-index: 3;\n}\n.CodeMirror-gutter {\n white-space: normal;\n height: 100%;\n display: inline-block;\n vertical-align: top;\n margin-bottom: -50px;\n}\n.CodeMirror-gutter-wrapper {\n position: absolute;\n z-index: 4;\n background: none !important;\n border: none !important;\n}\n.CodeMirror-gutter-background {\n position: absolute;\n top: 0; bottom: 0;\n z-index: 4;\n}\n.CodeMirror-gutter-elt {\n position: absolute;\n cursor: default;\n z-index: 4;\n}\n.CodeMirror-gutter-wrapper ::selection { background-color: transparent }\n.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }\n\n.CodeMirror-lines {\n cursor: text;\n min-height: 1px; /* prevents collapsing before first draw */\n}\n.CodeMirror pre.CodeMirror-line,\n.CodeMirror pre.CodeMirror-line-like {\n /* Reset some styles that the rest of the page might have set */\n -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;\n border-width: 0;\n background: transparent;\n font-family: inherit;\n font-size: inherit;\n margin: 0;\n white-space: pre;\n word-wrap: normal;\n line-height: inherit;\n color: inherit;\n z-index: 2;\n position: relative;\n overflow: visible;\n -webkit-tap-highlight-color: transparent;\n -webkit-font-variant-ligatures: contextual;\n font-variant-ligatures: contextual;\n}\n.CodeMirror-wrap pre.CodeMirror-line,\n.CodeMirror-wrap pre.CodeMirror-line-like {\n word-wrap: break-word;\n white-space: pre-wrap;\n word-break: normal;\n}\n\n.CodeMirror-linebackground {\n position: absolute;\n left: 0; right: 0; top: 0; bottom: 0;\n z-index: 0;\n}\n\n.CodeMirror-linewidget {\n position: relative;\n z-index: 2;\n padding: 0.1px; /* Force widget margins to stay inside of the container */\n}\n\n.CodeMirror-widget {}\n\n.CodeMirror-rtl pre { direction: rtl; }\n\n.CodeMirror-code {\n outline: none;\n}\n\n/* Force content-box sizing for the elements where we expect it */\n.CodeMirror-scroll,\n.CodeMirror-sizer,\n.CodeMirror-gutter,\n.CodeMirror-gutters,\n.CodeMirror-linenumber {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n}\n\n.CodeMirror-measure {\n position: absolute;\n width: 100%;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n}\n\n.CodeMirror-cursor {\n position: absolute;\n pointer-events: none;\n}\n.CodeMirror-measure pre { position: static; }\n\ndiv.CodeMirror-cursors {\n visibility: hidden;\n position: relative;\n z-index: 3;\n}\ndiv.CodeMirror-dragcursors {\n visibility: visible;\n}\n\n.CodeMirror-focused div.CodeMirror-cursors {\n visibility: visible;\n}\n\n.CodeMirror-selected { background: #d9d9d9; }\n.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }\n.CodeMirror-crosshair { cursor: crosshair; }\n.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }\n.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }\n\n.cm-searching {\n background-color: #ffa;\n background-color: rgba(255, 255, 0, .4);\n}\n\n/* Used to force a border model for a node */\n.cm-force-border { padding-right: .1px; }\n\n@media print {\n /* Hide the cursor when printing */\n .CodeMirror div.CodeMirror-cursors {\n visibility: hidden;\n }\n}\n\n/* See issue #2901 */\n.cm-tab-wrap-hack:after { content: ''; }\n\n/* Help users use markselection to safely style text background */\nspan.CodeMirror-selectedtext { background: none; }\n"],"sourceRoot":"webpack://"}]);
|
|
|
|
// exports
|
|
|
|
|
|
/***/ }),
|
|
/* 210 */
|
|
/***/ (function(module, exports) {
|
|
|
|
/*
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
Author Tobias Koppers @sokra
|
|
*/
|
|
// css base code, injected by the css-loader
|
|
module.exports = function() {
|
|
var list = [];
|
|
|
|
// return the list of modules as css string
|
|
list.toString = function toString() {
|
|
var result = [];
|
|
for(var i = 0; i < this.length; i++) {
|
|
var item = this[i];
|
|
if(item[2]) {
|
|
result.push("@media " + item[2] + "{" + item[1] + "}");
|
|
} else {
|
|
result.push(item[1]);
|
|
}
|
|
}
|
|
return result.join("");
|
|
};
|
|
|
|
// import a list of modules into the list
|
|
list.i = function(modules, mediaQuery) {
|
|
if(typeof modules === "string")
|
|
modules = [[null, modules, ""]];
|
|
var alreadyImportedModules = {};
|
|
for(var i = 0; i < this.length; i++) {
|
|
var id = this[i][0];
|
|
if(typeof id === "number")
|
|
alreadyImportedModules[id] = true;
|
|
}
|
|
for(i = 0; i < modules.length; i++) {
|
|
var item = modules[i];
|
|
// skip already imported module
|
|
// this implementation is not 100% perfect for weird media query combinations
|
|
// when a module is imported multiple times with different media queries.
|
|
// I hope this will never occur (Hey this way we have smaller bundles)
|
|
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
|
|
if(mediaQuery && !item[2]) {
|
|
item[2] = mediaQuery;
|
|
} else if(mediaQuery) {
|
|
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
|
|
}
|
|
list.push(item);
|
|
}
|
|
}
|
|
};
|
|
return list;
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
/* 211 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
/*
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
Author Tobias Koppers @sokra
|
|
*/
|
|
var stylesInDom = {},
|
|
memoize = function(fn) {
|
|
var memo;
|
|
return function () {
|
|
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
|
|
return memo;
|
|
};
|
|
},
|
|
isOldIE = memoize(function() {
|
|
return /msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase());
|
|
}),
|
|
getHeadElement = memoize(function () {
|
|
return document.head || document.getElementsByTagName("head")[0];
|
|
}),
|
|
singletonElement = null,
|
|
singletonCounter = 0,
|
|
styleElementsInsertedAtTop = [];
|
|
|
|
module.exports = function(list, options) {
|
|
if(false) {
|
|
if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
|
|
}
|
|
|
|
options = options || {};
|
|
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
|
|
// tags it will allow on a page
|
|
if (typeof options.singleton === "undefined") options.singleton = isOldIE();
|
|
|
|
// By default, add <style> tags to the bottom of <head>.
|
|
if (typeof options.insertAt === "undefined") options.insertAt = "bottom";
|
|
|
|
var styles = listToStyles(list);
|
|
addStylesToDom(styles, options);
|
|
|
|
return function update(newList) {
|
|
var mayRemove = [];
|
|
for(var i = 0; i < styles.length; i++) {
|
|
var item = styles[i];
|
|
var domStyle = stylesInDom[item.id];
|
|
domStyle.refs--;
|
|
mayRemove.push(domStyle);
|
|
}
|
|
if(newList) {
|
|
var newStyles = listToStyles(newList);
|
|
addStylesToDom(newStyles, options);
|
|
}
|
|
for(var i = 0; i < mayRemove.length; i++) {
|
|
var domStyle = mayRemove[i];
|
|
if(domStyle.refs === 0) {
|
|
for(var j = 0; j < domStyle.parts.length; j++)
|
|
domStyle.parts[j]();
|
|
delete stylesInDom[domStyle.id];
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function addStylesToDom(styles, options) {
|
|
for(var i = 0; i < styles.length; i++) {
|
|
var item = styles[i];
|
|
var domStyle = stylesInDom[item.id];
|
|
if(domStyle) {
|
|
domStyle.refs++;
|
|
for(var j = 0; j < domStyle.parts.length; j++) {
|
|
domStyle.parts[j](item.parts[j]);
|
|
}
|
|
for(; j < item.parts.length; j++) {
|
|
domStyle.parts.push(addStyle(item.parts[j], options));
|
|
}
|
|
} else {
|
|
var parts = [];
|
|
for(var j = 0; j < item.parts.length; j++) {
|
|
parts.push(addStyle(item.parts[j], options));
|
|
}
|
|
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
|
|
}
|
|
}
|
|
}
|
|
|
|
function listToStyles(list) {
|
|
var styles = [];
|
|
var newStyles = {};
|
|
for(var i = 0; i < list.length; i++) {
|
|
var item = list[i];
|
|
var id = item[0];
|
|
var css = item[1];
|
|
var media = item[2];
|
|
var sourceMap = item[3];
|
|
var part = {css: css, media: media, sourceMap: sourceMap};
|
|
if(!newStyles[id])
|
|
styles.push(newStyles[id] = {id: id, parts: [part]});
|
|
else
|
|
newStyles[id].parts.push(part);
|
|
}
|
|
return styles;
|
|
}
|
|
|
|
function insertStyleElement(options, styleElement) {
|
|
var head = getHeadElement();
|
|
var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
|
|
if (options.insertAt === "top") {
|
|
if(!lastStyleElementInsertedAtTop) {
|
|
head.insertBefore(styleElement, head.firstChild);
|
|
} else if(lastStyleElementInsertedAtTop.nextSibling) {
|
|
head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
|
|
} else {
|
|
head.appendChild(styleElement);
|
|
}
|
|
styleElementsInsertedAtTop.push(styleElement);
|
|
} else if (options.insertAt === "bottom") {
|
|
head.appendChild(styleElement);
|
|
} else {
|
|
throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
|
|
}
|
|
}
|
|
|
|
function removeStyleElement(styleElement) {
|
|
styleElement.parentNode.removeChild(styleElement);
|
|
var idx = styleElementsInsertedAtTop.indexOf(styleElement);
|
|
if(idx >= 0) {
|
|
styleElementsInsertedAtTop.splice(idx, 1);
|
|
}
|
|
}
|
|
|
|
function createStyleElement(options) {
|
|
var styleElement = document.createElement("style");
|
|
styleElement.type = "text/css";
|
|
insertStyleElement(options, styleElement);
|
|
return styleElement;
|
|
}
|
|
|
|
function createLinkElement(options) {
|
|
var linkElement = document.createElement("link");
|
|
linkElement.rel = "stylesheet";
|
|
insertStyleElement(options, linkElement);
|
|
return linkElement;
|
|
}
|
|
|
|
function addStyle(obj, options) {
|
|
var styleElement, update, remove;
|
|
|
|
if (options.singleton) {
|
|
var styleIndex = singletonCounter++;
|
|
styleElement = singletonElement || (singletonElement = createStyleElement(options));
|
|
update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
|
|
remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
|
|
} else if(obj.sourceMap &&
|
|
typeof URL === "function" &&
|
|
typeof URL.createObjectURL === "function" &&
|
|
typeof URL.revokeObjectURL === "function" &&
|
|
typeof Blob === "function" &&
|
|
typeof btoa === "function") {
|
|
styleElement = createLinkElement(options);
|
|
update = updateLink.bind(null, styleElement);
|
|
remove = function() {
|
|
removeStyleElement(styleElement);
|
|
if(styleElement.href)
|
|
URL.revokeObjectURL(styleElement.href);
|
|
};
|
|
} else {
|
|
styleElement = createStyleElement(options);
|
|
update = applyToTag.bind(null, styleElement);
|
|
remove = function() {
|
|
removeStyleElement(styleElement);
|
|
};
|
|
}
|
|
|
|
update(obj);
|
|
|
|
return function updateStyle(newObj) {
|
|
if(newObj) {
|
|
if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
|
|
return;
|
|
update(obj = newObj);
|
|
} else {
|
|
remove();
|
|
}
|
|
};
|
|
}
|
|
|
|
var replaceText = (function () {
|
|
var textStore = [];
|
|
|
|
return function (index, replacement) {
|
|
textStore[index] = replacement;
|
|
return textStore.filter(Boolean).join('\n');
|
|
};
|
|
})();
|
|
|
|
function applyToSingletonTag(styleElement, index, remove, obj) {
|
|
var css = remove ? "" : obj.css;
|
|
|
|
if (styleElement.styleSheet) {
|
|
styleElement.styleSheet.cssText = replaceText(index, css);
|
|
} else {
|
|
var cssNode = document.createTextNode(css);
|
|
var childNodes = styleElement.childNodes;
|
|
if (childNodes[index]) styleElement.removeChild(childNodes[index]);
|
|
if (childNodes.length) {
|
|
styleElement.insertBefore(cssNode, childNodes[index]);
|
|
} else {
|
|
styleElement.appendChild(cssNode);
|
|
}
|
|
}
|
|
}
|
|
|
|
function applyToTag(styleElement, obj) {
|
|
var css = obj.css;
|
|
var media = obj.media;
|
|
|
|
if(media) {
|
|
styleElement.setAttribute("media", media)
|
|
}
|
|
|
|
if(styleElement.styleSheet) {
|
|
styleElement.styleSheet.cssText = css;
|
|
} else {
|
|
while(styleElement.firstChild) {
|
|
styleElement.removeChild(styleElement.firstChild);
|
|
}
|
|
styleElement.appendChild(document.createTextNode(css));
|
|
}
|
|
}
|
|
|
|
function updateLink(linkElement, obj) {
|
|
var css = obj.css;
|
|
var sourceMap = obj.sourceMap;
|
|
|
|
if(sourceMap) {
|
|
// http://stackoverflow.com/a/26603875
|
|
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
|
|
}
|
|
|
|
var blob = new Blob([css], { type: "text/css" });
|
|
|
|
var oldSrc = linkElement.href;
|
|
|
|
linkElement.href = URL.createObjectURL(blob);
|
|
|
|
if(oldSrc)
|
|
URL.revokeObjectURL(oldSrc);
|
|
}
|
|
|
|
|
|
/***/ }),
|
|
/* 212 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// style-loader: Adds some css to the DOM by adding a <style> tag
|
|
|
|
// load the styles
|
|
var content = __webpack_require__(213);
|
|
if(typeof content === 'string') content = [[module.id, content, '']];
|
|
// add the styles to the DOM
|
|
var update = __webpack_require__(211)(content, {});
|
|
if(content.locals) module.exports = content.locals;
|
|
// Hot Module Replacement
|
|
if(false) {
|
|
// When the styles change, update the <style> tags
|
|
if(!content.locals) {
|
|
module.hot.accept("!!../node_modules/.store/[email protected]/node_modules/css-loader/index.js?sourceMap!../node_modules/.store/[email protected]/node_modules/postcss-loader/index.js?sourceMap!./style.css", function() {
|
|
var newContent = require("!!../node_modules/.store/[email protected]/node_modules/css-loader/index.js?sourceMap!../node_modules/.store/[email protected]/node_modules/postcss-loader/index.js?sourceMap!./style.css");
|
|
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
|
|
update(newContent);
|
|
});
|
|
}
|
|
// When the module is disposed, remove the <style> tags
|
|
module.hot.dispose(function() { update(); });
|
|
}
|
|
|
|
/***/ }),
|
|
/* 213 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
exports = module.exports = __webpack_require__(210)();
|
|
// imports
|
|
|
|
|
|
// module
|
|
exports.push([module.id, "html,\r\nbody,\r\n#app-holder,\r\n.app {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n margin: 0;\r\n}\r\n\r\nbutton {\r\n font-size: 14px;\r\n font-family: Montserrat, sans-serif;\r\n font-weight: normal;\r\n color: black;\r\n border: 1px solid #ec245e;\r\n background: inherit;\r\n color: #ec245e;\r\n border-radius: 2px;\r\n padding: 2px 12px;\r\n cursor: pointer;\r\n}\r\n\r\nbutton:hover,\r\nbutton:hover .open-iconic {\r\n fill: #30b8e6;\r\n color: #30b8e6;\r\n border-color: #30b8e6;\r\n}\r\n\r\na.p5-logo {\r\n margin-left: 10px;\r\n margin-right: 25px;\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-direction: column;\r\n flex-direction: column;\r\n -ms-flex-pack: center;\r\n justify-content: center;\r\n}\r\n\r\na.p5-logo img {\r\n height: 25px;\r\n}\r\n\r\n.open-iconic {\r\n fill: #ec245e;\r\n height: 16px;\r\n width: 16px;\r\n vertical-align: -10%;\r\n margin-right: 5px;\r\n}\r\n\r\n.app {\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-direction: column;\r\n flex-direction: column;\r\n}\r\n\r\n.status-bar {\r\n border-top: 1px solid #ec245e;\r\n background: #f0f0f0;\r\n min-height: 1em;\r\n font-family: \"Monaco\", \"Menlo\", \"Ubuntu Mono\", \"Consolas\",\r\n \"source-code-pro\", monospace;\r\n padding: 8px;\r\n}\r\n\r\n.error-message .error-message-line {\r\n font-family: Montserrat, sans-serif;\r\n font-weight: normal;\r\n color: red;\r\n}\r\n\r\n.toolbar {\r\n display: -ms-flexbox;\r\n display: flex;\r\n}\r\n\r\n.toolbar button {\r\n margin: 10px;\r\n}\r\n\r\n.panes {\r\n -ms-flex: 1;\r\n flex: 1;\r\n display: -ms-flexbox;\r\n display: flex;\r\n border-top: 1px solid #ec245e;\r\n}\r\n\r\n\r\n.panes .editor-holder {\r\n -ms-flex: 1;\r\n flex: 1;\r\n\r\n /* We need this for horizontal scrolling to work properly.\r\n * Very weird. */\r\n overflow-x: hidden;\r\n}\r\n\r\n.panes .preview-holder-wrapper {\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-direction: column;\r\n flex-direction: column;\r\n}\r\n\r\n.panes .preview-holder {\r\n -ms-flex: 1;\r\n flex: 1;\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-direction: column;\r\n flex-direction: column;\r\n border-left: 16px solid #f0f0f0;\r\n}\r\n\r\n.panes .preview-holder-wrapper iframe {\r\n -ms-flex: 1;\r\n flex: 1;\r\n border: none;\r\n}\r\n\r\n.CodeMirror {\r\n font-family: \"Monaco\", \"Menlo\", \"Ubuntu Mono\", \"Consolas\",\r\n \"source-code-pro\", monospace;\r\n\r\n /* If we don't add this, the final characters on some lines aren't\r\n * visible if the editor has a horizontal scrollbar. Weird. */\r\n padding-right: 1em;\r\n}\r\n\r\n.CodeMirror-gutters {\r\n border-right: none;\r\n background: #f0f0f0;\r\n}\r\n\r\n.error-line {\r\n background: #ffe5ea;\r\n}\r\n", "", {"version":3,"sources":["/./css/style.css"],"names":[],"mappings":"AAUA;;;;EAIE,aAAa;CACd;;AAED;EACE,UAAU;CACX;;AAED;EACE,gBAAgB;EAChB,oCAA4B;EAC5B,oBAAoB;EACpB,aAAa;EACb,0BAAmC;EACnC,oBAAoB;EACpB,eAAwB;EACxB,mBAAmB;EACnB,kBAAkB;EAClB,gBAAgB;CACjB;;AAED;;EAEE,cAAqB;EACrB,eAAsB;EACtB,sBAA6B;CAC9B;;AAED;EACE,kBAAkB;EAClB,mBAAmB;EACnB,qBAAc;EAAd,cAAc;EACd,2BAAuB;MAAvB,uBAAuB;EACvB,sBAAwB;MAAxB,wBAAwB;CACzB;;AAED;EACE,aAAa;CACd;;AAED;EACE,cAAuB;EACvB,aAAa;EACb,YAAY;EACZ,qBAAqB;EACrB,kBAAkB;CACnB;;AAED;EACE,qBAAc;EAAd,cAAc;EACd,2BAAuB;MAAvB,uBAAuB;CACxB;;AAED;EACE,8BAAuC;EACvC,oBAAmC;EACnC,gBAAgB;EAChB;4CAA8B;EAC9B,aAAa;CACd;;AAED;EACE,oCAA4B;EAC5B,oBAAoB;EACpB,WAAW;CACZ;;AAED;EACE,qBAAc;EAAd,cAAc;CACf;;AAED;EACE,aAAa;CACd;;AAED;EACE,YAAQ;MAAR,QAAQ;EACR,qBAAc;EAAd,cAAc;EACd,8BAAuC;CACxC;;;AAGD;EACE,YAAQ;MAAR,QAAQ;;EAER;mBACiB;EACjB,mBAAmB;CACpB;;AAED;EACE,qBAAc;EAAd,cAAc;EACd,2BAAuB;MAAvB,uBAAuB;CACxB;;AAED;EACE,YAAQ;MAAR,QAAQ;EACR,qBAAc;EAAd,cAAc;EACd,2BAAuB;MAAvB,uBAAuB;EACvB,gCAA+C;CAChD;;AAED;EACE,YAAQ;MAAR,QAAQ;EACR,aAAa;CACd;;AAED;EACE;4CAA8B;;EAE9B;gEAC8D;EAC9D,mBAAmB;CACpB;;AAED;EACE,mBAAmB;EACnB,oBAAmC;CACpC;;AAED;EACE,oBAA8B;CAC/B","file":"style.css","sourcesContent":[":root {\r\n --very-light-gray: #f0f0f0;\r\n --light-pink: #ffe5ea;\r\n --dark-pink: #ec245e;\r\n --blueish: #30b8e6;\r\n --ui-font: Montserrat, sans-serif;\r\n --code-font: \"Monaco\", \"Menlo\", \"Ubuntu Mono\", \"Consolas\",\r\n \"source-code-pro\", monospace;\r\n}\r\n\r\nhtml,\r\nbody,\r\n#app-holder,\r\n.app {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n margin: 0;\r\n}\r\n\r\nbutton {\r\n font-size: 14px;\r\n font-family: var(--ui-font);\r\n font-weight: normal;\r\n color: black;\r\n border: 1px solid var(--dark-pink);\r\n background: inherit;\r\n color: var(--dark-pink);\r\n border-radius: 2px;\r\n padding: 2px 12px;\r\n cursor: pointer;\r\n}\r\n\r\nbutton:hover,\r\nbutton:hover .open-iconic {\r\n fill: var(--blueish);\r\n color: var(--blueish);\r\n border-color: var(--blueish);\r\n}\r\n\r\na.p5-logo {\r\n margin-left: 10px;\r\n margin-right: 25px;\r\n display: flex;\r\n flex-direction: column;\r\n justify-content: center;\r\n}\r\n\r\na.p5-logo img {\r\n height: 25px;\r\n}\r\n\r\n.open-iconic {\r\n fill: var(--dark-pink);\r\n height: 16px;\r\n width: 16px;\r\n vertical-align: -10%;\r\n margin-right: 5px;\r\n}\r\n\r\n.app {\r\n display: flex;\r\n flex-direction: column;\r\n}\r\n\r\n.status-bar {\r\n border-top: 1px solid var(--dark-pink);\r\n background: var(--very-light-gray);\r\n min-height: 1em;\r\n font-family: var(--code-font);\r\n padding: 8px;\r\n}\r\n\r\n.error-message .error-message-line {\r\n font-family: var(--ui-font);\r\n font-weight: normal;\r\n color: red;\r\n}\r\n\r\n.toolbar {\r\n display: flex;\r\n}\r\n\r\n.toolbar button {\r\n margin: 10px;\r\n}\r\n\r\n.panes {\r\n flex: 1;\r\n display: flex;\r\n border-top: 1px solid var(--dark-pink);\r\n}\r\n\r\n\r\n.panes .editor-holder {\r\n flex: 1;\r\n\r\n /* We need this for horizontal scrolling to work properly.\r\n * Very weird. */\r\n overflow-x: hidden;\r\n}\r\n\r\n.panes .preview-holder-wrapper {\r\n display: flex;\r\n flex-direction: column;\r\n}\r\n\r\n.panes .preview-holder {\r\n flex: 1;\r\n display: flex;\r\n flex-direction: column;\r\n border-left: 16px solid var(--very-light-gray);\r\n}\r\n\r\n.panes .preview-holder-wrapper iframe {\r\n flex: 1;\r\n border: none;\r\n}\r\n\r\n.CodeMirror {\r\n font-family: var(--code-font);\r\n\r\n /* If we don't add this, the final characters on some lines aren't\r\n * visible if the editor has a horizontal scrollbar. Weird. */\r\n padding-right: 1em;\r\n}\r\n\r\n.CodeMirror-gutters {\r\n border-right: none;\r\n background: var(--very-light-gray);\r\n}\r\n\r\n.error-line {\r\n background: var(--light-pink);\r\n}\r\n"],"sourceRoot":"webpack://"}]);
|
|
|
|
// exports
|
|
|
|
|
|
/***/ }),
|
|
/* 214 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
// style-loader: Adds some css to the DOM by adding a <style> tag
|
|
|
|
// load the styles
|
|
var content = __webpack_require__(215);
|
|
if(typeof content === 'string') content = [[module.id, content, '']];
|
|
// add the styles to the DOM
|
|
var update = __webpack_require__(211)(content, {});
|
|
if(content.locals) module.exports = content.locals;
|
|
// Hot Module Replacement
|
|
if(false) {
|
|
// When the styles change, update the <style> tags
|
|
if(!content.locals) {
|
|
module.hot.accept("!!../node_modules/.store/[email protected]/node_modules/css-loader/index.js?sourceMap!../node_modules/.store/[email protected]/node_modules/postcss-loader/index.js?sourceMap!./p5-widget-codemirror-theme.css", function() {
|
|
var newContent = require("!!../node_modules/.store/[email protected]/node_modules/css-loader/index.js?sourceMap!../node_modules/.store/[email protected]/node_modules/postcss-loader/index.js?sourceMap!./p5-widget-codemirror-theme.css");
|
|
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
|
|
update(newContent);
|
|
});
|
|
}
|
|
// When the module is disposed, remove the <style> tags
|
|
module.hot.dispose(function() { update(); });
|
|
}
|
|
|
|
/***/ }),
|
|
/* 215 */
|
|
/***/ (function(module, exports, __webpack_require__) {
|
|
|
|
exports = module.exports = __webpack_require__(210)();
|
|
// imports
|
|
|
|
|
|
// module
|
|
exports.push([module.id, ":root { /* not p5 pink, but related */\r\n}\r\n\r\n.cm-s-p5-widget span { color: #666; }\r\n\r\n.cm-s-p5-widget span.cm-meta { color: #666; }\r\n.cm-s-p5-widget span.cm-keyword { line-height: 1em; color: #704F21; }\r\n.cm-s-p5-widget span.cm-atom { color: #DC3787; }\r\n.cm-s-p5-widget span.cm-number { color: #DC3787; }\r\n.cm-s-p5-widget span.cm-def { color: #00A1D3; }\r\n.cm-s-p5-widget span.cm-variable { color: #00A1D3; }\r\n.cm-s-p5-widget span.cm-variable-2 { color: #222; }\r\n.cm-s-p5-widget span.cm-variable-3 { color: #222; }\r\n.cm-s-p5-widget span.cm-property { color: #222; }\r\n.cm-s-p5-widget span.cm-operator { color: #a67f59; }\r\n.cm-s-p5-widget span.cm-comment { color: #A0A0A0; }\r\n.cm-s-p5-widget span.cm-string { color: #00A1D3; }\r\n.cm-s-p5-widget span.cm-string-2 { color: #00A1D3; }\r\n\r\n.cm-s-p5-widget span.cm-error { color: #f00; }\r\n\r\n.cm-s-p5-widget .CodeMirror-activeline-background { background: #e8f2ff; }\r\n.cm-s-p5-widget .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\r\n\r\n/* These styles don't seem to be set by CodeMirror's javascript mode. */\r\n\r\n.cm-s-p5-widget span.cm-qualifier { color: #555; }\r\n.cm-s-p5-widget span.cm-builtin { color: #30a; }\r\n.cm-s-p5-widget span.cm-bracket { color: #cc7; }\r\n.cm-s-p5-widget span.cm-tag { color: #170; }\r\n.cm-s-p5-widget span.cm-attribute { color: #00c; }\r\n.cm-s-p5-widget span.cm-link { color: #219; }\r\n", "", {"version":3,"sources":["/./css/p5-widget-codemirror-theme.css"],"names":[],"mappings":"AAAA,QAMsB,8BAA8B;CAEnD;;AAED,uBAAuB,YAAwB,EAAE;;AAEjD,+BAA+B,YAAwB,EAAE;AACzD,kCAAkC,iBAAiB,CAAC,eAAyB,EAAE;AAC/E,+BAA+B,eAAsB,EAAE;AACvD,iCAAiC,eAAsB,EAAE;AACzD,8BAA8B,eAA2B,EAAE;AAC3D,mCAAmC,eAA2B,EAAE;AAChE,qCAAqC,YAA2B,EAAE;AAClE,qCAAqC,YAA2B,EAAE;AAClE,mCAAmC,YAA2B,EAAE;AAChE,mCAAmC,eAA0B,EAAE;AAC/D,kCAAkC,eAAyB,EAAE;AAC7D,iCAAiC,eAA2B,EAAE;AAC9D,mCAAmC,eAA2B,EAAE;;AAEhE,gCAAgC,YAAY,EAAE;;AAE9C,oDAAoD,oBAAoB,EAAE;AAC1E,8CAA8C,uBAAuB,CAAC,uBAAuB,EAAE;;AAE/F,wEAAwE;;AAExE,oCAAoC,YAAY,EAAE;AAClD,kCAAkC,YAAY,EAAE;AAChD,kCAAkC,YAAY,EAAE;AAChD,8BAA8B,YAAY,EAAE;AAC5C,oCAAoC,YAAY,EAAE;AAClD,+BAA+B,YAAY,EAAE","file":"p5-widget-codemirror-theme.css","sourcesContent":[":root {\r\n --light-gray: #A0A0A0;\r\n --dark-gray: #666;\r\n --almost-black: #222;\r\n --dark-brown: #704F21;\r\n --light-brown: #a67f59;\r\n --pinkish: #DC3787; /* not p5 pink, but related */\r\n --dark-blueish: #00A1D3;\r\n}\r\n\r\n.cm-s-p5-widget span { color: var(--dark-gray); }\r\n\r\n.cm-s-p5-widget span.cm-meta { color: var(--dark-gray); }\r\n.cm-s-p5-widget span.cm-keyword { line-height: 1em; color: var(--dark-brown); }\r\n.cm-s-p5-widget span.cm-atom { color: var(--pinkish); }\r\n.cm-s-p5-widget span.cm-number { color: var(--pinkish); }\r\n.cm-s-p5-widget span.cm-def { color: var(--dark-blueish); }\r\n.cm-s-p5-widget span.cm-variable { color: var(--dark-blueish); }\r\n.cm-s-p5-widget span.cm-variable-2 { color: var(--almost-black); }\r\n.cm-s-p5-widget span.cm-variable-3 { color: var(--almost-black); }\r\n.cm-s-p5-widget span.cm-property { color: var(--almost-black); }\r\n.cm-s-p5-widget span.cm-operator { color: var(--light-brown); }\r\n.cm-s-p5-widget span.cm-comment { color: var(--light-gray); }\r\n.cm-s-p5-widget span.cm-string { color: var(--dark-blueish); }\r\n.cm-s-p5-widget span.cm-string-2 { color: var(--dark-blueish); }\r\n\r\n.cm-s-p5-widget span.cm-error { color: #f00; }\r\n\r\n.cm-s-p5-widget .CodeMirror-activeline-background { background: #e8f2ff; }\r\n.cm-s-p5-widget .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; }\r\n\r\n/* These styles don't seem to be set by CodeMirror's javascript mode. */\r\n\r\n.cm-s-p5-widget span.cm-qualifier { color: #555; }\r\n.cm-s-p5-widget span.cm-builtin { color: #30a; }\r\n.cm-s-p5-widget span.cm-bracket { color: #cc7; }\r\n.cm-s-p5-widget span.cm-tag { color: #170; }\r\n.cm-s-p5-widget span.cm-attribute { color: #00c; }\r\n.cm-s-p5-widget span.cm-link { color: #219; }\r\n"],"sourceRoot":"webpack://"}]);
|
|
|
|
// exports
|
|
|
|
|
|
/***/ })
|
|
/******/ ]);
|
|
//# sourceMappingURL=main.bundle.js.map |