Skip to content

Instantly share code, notes, and snippets.

@tlvenn
Last active February 27, 2017 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlvenn/da721376f5fd2b1835e953adf441cb0b to your computer and use it in GitHub Desktop.
Save tlvenn/da721376f5fd2b1835e953adf441cb0b to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.graphiqlWorkspace = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphiQLTab = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _GraphiQL = require('graphiql/dist/components/GraphiQL');
var _GraphiQLToolbar = require('./GraphiQLToolbar');
var _HeaderEditor = require('./HeaderEditor');
var _QuerySelectionButton = require('./QuerySelectionButton');
var _Form = require('react-bootstrap/lib/Form');
var _Form2 = _interopRequireDefault(_Form);
var _FormGroup = require('react-bootstrap/lib/FormGroup');
var _FormGroup2 = _interopRequireDefault(_FormGroup);
var _InputGroup = require('react-bootstrap/lib/InputGroup');
var _InputGroup2 = _interopRequireDefault(_InputGroup);
var _FormControl = require('react-bootstrap/lib/FormControl');
var _FormControl2 = _interopRequireDefault(_FormControl);
var _Glyphicon = require('react-bootstrap/lib/Glyphicon');
var _Glyphicon2 = _interopRequireDefault(_Glyphicon);
var _Button = require('react-bootstrap/lib/Button');
var _Button2 = _interopRequireDefault(_Button);
var _ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup);
var _DropdownButton = require('react-bootstrap/lib/DropdownButton');
var _DropdownButton2 = _interopRequireDefault(_DropdownButton);
var _MenuItem = require('react-bootstrap/lib/MenuItem');
var _MenuItem2 = _interopRequireDefault(_MenuItem);
var _Col = require('react-bootstrap/lib/Col');
var _Col2 = _interopRequireDefault(_Col);
var _ControlLabel = require('react-bootstrap/lib/ControlLabel');
var _ControlLabel2 = _interopRequireDefault(_ControlLabel);
var _Checkbox = require('react-bootstrap/lib/Checkbox');
var _Checkbox2 = _interopRequireDefault(_Checkbox);
var _Table = require('react-bootstrap/lib/Table');
var _Table2 = _interopRequireDefault(_Table);
var _introspectionQueries = require('./utility/introspectionQueries');
var _graphql = require('graphql');
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var GraphiQLTab = exports.GraphiQLTab = function (_React$Component) {
_inherits(GraphiQLTab, _React$Component);
function GraphiQLTab(props) {
_classCallCheck(this, GraphiQLTab);
var _this = _possibleConstructorReturn(this, (GraphiQLTab.__proto__ || Object.getPrototypeOf(GraphiQLTab)).call(this));
_this.graphiql = null;
_this.state = {
config: props.tab,
appConfig: props.app,
header: null,
headerIdx: null,
editedQuery: { query: props.tab.getQuery(), variables: props.tab.getVariables() }
};
return _this;
}
_createClass(GraphiQLTab, [{
key: 'runQueryAtCursor',
value: function runQueryAtCursor() {
if (this.graphiql) this.graphiql._runQueryAtCursor();
}
}, {
key: 'persistState',
value: function persistState() {
if (this.graphiql) this.graphiql.componentWillUnmount();
}
}, {
key: 'render',
value: function render() {
if (this.state.config.state.collapsed) return this.renderCollapsed();else return this.renderExpanded();
}
}, {
key: 'renderCollapsed',
value: function renderCollapsed() {
var _this2 = this;
var tab = this.state.config;
var headers = _react2.default.createElement('span', null);
if (tab.state.headers.length > 0) {
var headerList = tab.state.headers.map(function (h) {
return h.name + ": " + _this2.headerValue(h);
}).join(", ");
headers = _react2.default.createElement(
'span',
null,
'\xA0\xA0\xA0',
_react2.default.createElement(
'strong',
null,
'Headers:'
),
' ',
headerList
);
}
return _react2.default.createElement(
'div',
{ className: 'graphiql-tool-cont' },
_react2.default.createElement(
'div',
{ className: 'tab-top', style: { flexDirection: "row" } },
_react2.default.createElement(
'div',
{ className: 'graphiql-collapsed-tab', onClick: this.expand.bind(this) },
_react2.default.createElement(
'strong',
null,
'URL:'
),
' ',
tab.state.url,
tab.state.proxy ? " (proxied)" : "",
' ',
headers
),
_react2.default.createElement(
'div',
null,
_react2.default.createElement(_GraphiQLToolbar.GraphiQLToolbar, { hirizontal: true, onToolbar: this.toolbar.bind(this), hasClosed: this.props.hasClosed })
)
),
this.renderGraphiql(tab)
);
}
}, {
key: 'renderExpanded',
value: function renderExpanded() {
var _this3 = this;
var tab = this.state.config;
var url = _react2.default.createElement(_FormControl2.default, {
placeholder: 'GraphQL endpoint URL',
bsSize: 'small',
value: tab.state.url,
onChange: this.urlChange.bind(this) });
var urlInput = url;
if (this.state.appConfig.state.usedUrls.length > 0) {
var items = this.state.appConfig.state.usedUrls.map(function (url) {
return _react2.default.createElement(
_MenuItem2.default,
{ key: url, onClick: _this3.setUrl.bind(_this3, url) },
url
);
});
urlInput = _react2.default.createElement(
_InputGroup2.default,
null,
url,
_react2.default.createElement(
_DropdownButton2.default,
{ componentClass: _InputGroup2.default.Button, id: 'used-url', title: 'Recent' },
items
)
);
}
var recentHeaders = '';
if (this.state.appConfig.state.recentHeaders.length > 0) {
var _items = this.state.appConfig.state.recentHeaders.map(function (header) {
var label = header.name + ": " + header.value;
var labelo = header.name + ": " + _this3.headerValue(header, true);
return _react2.default.createElement(
_MenuItem2.default,
{ key: label, onClick: _this3.addHeader.bind(_this3, header, false) },
labelo
);
});
recentHeaders = _react2.default.createElement(
_DropdownButton2.default,
{ id: 'recent-header', title: 'Recent' },
_items
);
}
var headers = _react2.default.createElement('div', null);
if (this.state.config.state.headers.length > 0) {
var values = this.state.config.state.headers.map(function (header, idx) {
return _react2.default.createElement(
'tr',
{ key: header.name + header.value },
_react2.default.createElement(
'td',
null,
_this3.truncateHeaderValue(header.name)
),
_react2.default.createElement(
'td',
null,
_this3.truncateHeaderValue(_this3.headerValue(header))
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', onClick: _this3.editHeader.bind(_this3, header, idx) },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'edit', bsSize: 'small' })
),
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', onClick: _this3.removeHeader.bind(_this3, header, idx) },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'remove', bsSize: 'small' })
)
)
);
});
headers = _react2.default.createElement(
_Table2.default,
null,
_react2.default.createElement(
'thead',
null,
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'th',
null,
'Header Name'
),
_react2.default.createElement(
'th',
null,
'Header Value'
),
_react2.default.createElement('th', { width: '100px' })
)
),
_react2.default.createElement(
'tbody',
null,
values
)
);
}
return _react2.default.createElement(
'div',
{ className: 'graphiql-tool-cont' },
_react2.default.createElement(
'div',
{ className: 'tab-top' },
_react2.default.createElement(
'div',
{ className: 'tab-form' },
_react2.default.createElement(
_Form2.default,
{ horizontal: true },
_react2.default.createElement(
_FormGroup2.default,
{ controlId: 'name-input' },
_react2.default.createElement(
_Col2.default,
{ componentClass: _ControlLabel2.default, sm: 2 },
'Name'
),
_react2.default.createElement(
_Col2.default,
{ sm: 10 },
_react2.default.createElement(_FormControl2.default, { placeholder: 'Query name', bsSize: 'small', value: tab.state.name, onChange: this.nameChange.bind(this) })
)
),
_react2.default.createElement(
_FormGroup2.default,
{ controlId: 'url-input', validationState: this.state.schemaError ? "error" : null },
_react2.default.createElement(
_Col2.default,
{ componentClass: _ControlLabel2.default, sm: 2 },
'URL'
),
_react2.default.createElement(
_Col2.default,
{ sm: 10 },
urlInput
)
),
this.props.proxyUrl && _react2.default.createElement(
_FormGroup2.default,
null,
_react2.default.createElement(
_Col2.default,
{ smOffset: 2, sm: 10 },
_react2.default.createElement(
_Checkbox2.default,
{ checked: this.state.config.state.proxy, onChange: this.proxyChange.bind(this) },
'Proxy requests'
)
)
),
_react2.default.createElement(
_FormGroup2.default,
{ controlId: 'headers-input' },
_react2.default.createElement(
_Col2.default,
{ componentClass: _ControlLabel2.default, sm: 2 },
'Headers'
),
_react2.default.createElement(
_Col2.default,
{ sm: 10 },
_react2.default.createElement(
_ButtonGroup2.default,
null,
_react2.default.createElement(
_Button2.default,
{ bsSize: 'small', className: 'header-add', onClick: this.addHeader.bind(this, null) },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'plus' }),
' Add'
),
_react2.default.createElement(
_DropdownButton2.default,
{ id: 'std-header', title: 'Standard' },
_react2.default.createElement(
_MenuItem2.default,
{ key: 'oauth-bearer', onClick: this.addHeader.bind(this, { name: "Authorization", value: "Bearer " }, true) },
'OAuth 2 Bearer Token'
)
),
recentHeaders
)
)
)
)
),
_react2.default.createElement(
'div',
{ className: 'headers' },
headers,
_react2.default.createElement(_HeaderEditor.HeaderEditor, { headerIdx: this.state.headerIdx, header: this.state.header, onFinish: this.headerFinish.bind(this) })
),
_react2.default.createElement(
'div',
null,
_react2.default.createElement(_GraphiQLToolbar.GraphiQLToolbar, { onToolbar: this.toolbar.bind(this), hasClosed: this.props.hasClosed })
)
),
this.renderGraphiql(tab)
);
}
}, {
key: 'collapse',
value: function collapse() {
this.state.config.state.setState({ collapsed: true });
this.setState({ config: this.state.config });
}
}, {
key: 'expand',
value: function expand() {
this.state.config.state.setState({ collapsed: false });
this.setState({ config: this.state.config });
}
}, {
key: 'renderGraphiql',
value: function renderGraphiql(tab) {
var _this4 = this;
var addButton = _react2.default.createElement(_GraphiQL.GraphiQL.ToolbarButton, { title: 'Save Query', label: 'Save', onClick: this.saveQuery.bind(this) });
if (this.state.appConfig.hasSavedQuery(this.state.editedQuery)) {
addButton = _react2.default.createElement(_GraphiQL.GraphiQL.ToolbarButton, { title: 'Remove Query', label: 'Remove', onClick: this.removeQuery.bind(this) });
}
return _react2.default.createElement(
'div',
{ className: 'graphiql-tool-cont1' },
_react2.default.createElement(
_GraphiQL.GraphiQL,
{
ref: function ref(cmp) {
return _this4.graphiql = cmp;
},
storage: tab.getState(),
query: this.state.queryUpdate ? this.state.queryUpdate.query : undefined,
variables: this.state.queryUpdate ? this.state.queryUpdate.variables : undefined,
schema: this.state.schema,
fetcher: this.fetcher.bind(this),
onEditQuery: this.queryEdited.bind(this),
onEditVariables: this.variablesEdited.bind(this) },
_react2.default.createElement(
_GraphiQL.GraphiQL.Toolbar,
null,
_react2.default.createElement(_QuerySelectionButton.QuerySelectionButton, { name: 'History', list: tab.getHistory(), onQuery: this.onSelectedQuery.bind(this) }),
_react2.default.createElement(_QuerySelectionButton.QuerySelectionButton, { name: 'Saved Queries', list: this.state.appConfig.getSavedQueries(), onQuery: this.onSelectedQuery.bind(this) }),
addButton
)
)
);
}
}, {
key: 'saveQuery',
value: function saveQuery() {
this.state.appConfig.addSavedQuery(this.state.editedQuery);
this.setState({ appConfig: this.state.appConfig });
}
}, {
key: 'removeQuery',
value: function removeQuery() {
this.state.appConfig.removeSavedQuery(this.state.editedQuery);
this.setState({ appConfig: this.state.appConfig });
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (this.state.queryUpdate) {
this.setState({ queryUpdate: undefined });
}
}
}, {
key: 'onSelectedQuery',
value: function onSelectedQuery(item) {
var query = { query: item.query, variables: item.variables ? item.variables : "" };
this.setState({ editedQuery: query, queryUpdate: query });
}
}, {
key: 'queryEdited',
value: function queryEdited(query) {
this.setState({ editedQuery: { query: query, variables: this.state.editedQuery.variables } });
}
}, {
key: 'variablesEdited',
value: function variablesEdited(variables) {
this.setState({ editedQuery: { query: this.state.editedQuery.query, variables: variables } });
}
}, {
key: 'headerValue',
value: function headerValue(h, partial) {
function replace(s) {
if (partial) {
var first = s.substring(0, s.length - 4);
var last = s.substring(s.length - 4);
return _lodash2.default.replace(first, /./g, '\u2022') + last;
} else {
return _lodash2.default.replace(s, /./g, '\u2022');
}
}
if (_lodash2.default.toLower(h.name) == "authorization") {
var prefix = "Bearer ";
if (h.value.startsWith(prefix)) {
var token = h.value.substring(prefix.length);
return prefix + replace(token);
} else {
return replace(h.value);
}
} else {
return h.value;
}
}
}, {
key: 'truncateHeaderValue',
value: function truncateHeaderValue(s) {
return _lodash2.default.truncate(s, { length: 70 });
}
}, {
key: 'addHeader',
value: function addHeader(h, edit) {
if (h) {
if (edit) {
this.setState({ header: h, headerIdx: null });
} else {
this.headerFinish(h, null);
}
} else {
this.setState({ header: { name: "", value: "" }, headerIdx: null });
}
}
}, {
key: 'editHeader',
value: function editHeader(h, idx) {
this.setState({ header: h, headerIdx: idx });
}
}, {
key: 'removeHeader',
value: function removeHeader(h, idx) {
this.state.config.state.headers.splice(idx, 1);
this.state.config.state.setState({ headers: this.state.config.state.headers });
this.setState({ config: this.state.config, appConfig: this.state.appConfig });
}
}, {
key: 'headerFinish',
value: function headerFinish(h, idx) {
if (h) {
if (idx == null) {
this.state.config.state.setState({ headers: [].concat(_toConsumableArray(this.state.config.state.headers), [h]) });
} else {
this.state.config.state.setState({ headers: this.state.config.state.headers.map(function (header, i) {
if (i == idx) {
return h;
} else {
return header;
}
}) });
}
this.state.appConfig.rememberHeader(h);
}
this.setState({ header: null, headerIdx: null });
}
}, {
key: 'nameChange',
value: function nameChange(e) {
this.state.config.state.setState({
name: e.target.value
});
this.setState({ config: this.state.config });
if (this.props.onNameChange) this.props.onNameChange(e.target.value);
}
}, {
key: 'proxyChange',
value: function proxyChange(e) {
this.state.config.state.setState({
proxy: e.target.checked
});
this.setState({ config: this.state.config, schemaError: false });
this.updateSchema();
}
}, {
key: 'setUrl',
value: function setUrl(url) {
this.state.config.state.setState({
url: url
});
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (url.match(regex)) {
this.setState({ config: this.state.config, schemaError: false });
this.updateSchema();
} else {
this.setState({ config: this.state.config, schemaError: true });
}
}
}, {
key: 'urlChange',
value: function urlChange(e) {
this.setUrl(e.target.value);
}
}, {
key: 'updateSchema',
value: function updateSchema() {
var _this5 = this;
var fetch = this.fetcher({ query: _introspectionQueries.introspectionQuery });
return fetch.then(function (result) {
if (result && result.data) {
_this5.setState({ schema: (0, _graphql.buildClientSchema)(result.data), schemaError: false });
} else {
_this5.setState({ schemaError: true });
}
}).catch(function (error) {
_this5.setState({ schemaError: true });
});
}
}, {
key: 'toolbar',
value: function toolbar(action) {
if (action == 'collapse') {
this.collapse();
} else if (action == 'expand') {
this.expand();
}
if (this.props.onToolbar) {
this.props.onToolbar.apply(this, arguments);
}
}
}, {
key: 'fetcher',
value: function fetcher(params) {
var _this6 = this;
if (this.state.config.state.proxy) {
params.url = this.state.config.state.url;
params.headers = this.state.config.state.headers;
}
var url = this.state.config.state.proxy && this.props.proxyUrl ? this.props.proxyUrl : this.state.config.state.url;
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
if (!this.state.config.state.proxy) {
this.state.config.state.headers.forEach(function (h) {
return headers.append(h.name, h.value);
});
}
console.log("Fetching...");
return fetch(url, {
method: 'post',
headers: headers,
body: JSON.stringify(params),
credentials: 'include'
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
var json = JSON.parse(responseBody);
if (_this6.state.appConfig.rememberUrl(_this6.state.config.state.url)) _this6.setState({ appConfig: _this6.state.appConfig });
if (_this6.state.config.rememberQuery({ query: params.query, variables: params.variables })) _this6.setState({ config: _this6.state.config });
return json;
} catch (error) {
return responseBody;
}
});
}
}]);
return GraphiQLTab;
}(_react2.default.Component);
GraphiQLTab.propTypes = {
tab: _react.PropTypes.object.isRequired,
app: _react.PropTypes.object.isRequired,
hasClosed: _react.PropTypes.bool.isRequired,
onToolbar: _react.PropTypes.func,
onNameChange: _react.PropTypes.func,
proxyUrl: _react.PropTypes.string
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./GraphiQLToolbar":2,"./HeaderEditor":4,"./QuerySelectionButton":6,"./utility/introspectionQueries":9,"graphiql/dist/components/GraphiQL":118,"graphql":144,"lodash":286,"react-bootstrap/lib/Button":290,"react-bootstrap/lib/ButtonGroup":291,"react-bootstrap/lib/Checkbox":292,"react-bootstrap/lib/Col":293,"react-bootstrap/lib/ControlLabel":294,"react-bootstrap/lib/DropdownButton":296,"react-bootstrap/lib/Form":300,"react-bootstrap/lib/FormControl":301,"react-bootstrap/lib/FormGroup":304,"react-bootstrap/lib/Glyphicon":305,"react-bootstrap/lib/InputGroup":306,"react-bootstrap/lib/MenuItem":309,"react-bootstrap/lib/Table":326}],2:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphiQLToolbar = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _Button = require('react-bootstrap/lib/Button');
var _Button2 = _interopRequireDefault(_Button);
var _Glyphicon = require('react-bootstrap/lib/Glyphicon');
var _Glyphicon2 = _interopRequireDefault(_Glyphicon);
var _OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger');
var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger);
var _Tooltip = require('react-bootstrap/lib/Tooltip');
var _Tooltip2 = _interopRequireDefault(_Tooltip);
var _reactDropzone = require('react-dropzone');
var _reactDropzone2 = _interopRequireDefault(_reactDropzone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var GraphiQLToolbar = function (_React$Component) {
_inherits(GraphiQLToolbar, _React$Component);
function GraphiQLToolbar() {
_classCallCheck(this, GraphiQLToolbar);
return _possibleConstructorReturn(this, (GraphiQLToolbar.__proto__ || Object.getPrototypeOf(GraphiQLToolbar)).apply(this, arguments));
}
_createClass(GraphiQLToolbar, [{
key: 'render',
value: function render() {
var reopenTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Reopen closed tab'
)
);
var collapseTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Collapse the tab config'
)
);
var expandTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Expand the tab config'
)
);
var exportTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Save workspace'
)
);
var restoreTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Open workspace'
),
' (drag&drop file here or just click the icon)'
);
var cleanTooltip = _react2.default.createElement(
_Tooltip2.default,
{ id: 'tooltip' },
_react2.default.createElement(
'strong',
null,
'Cleanup the workspace and start from scratch'
)
);
var placement = "left";
var sep = !this.props.hirizontal ? _react2.default.createElement('br', null) : _react2.default.createElement('span', null);
return _react2.default.createElement(
'div',
{ className: 'graphiql-toolbar' },
this.props.hasClosed && _react2.default.createElement(
'span',
null,
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: reopenTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large', onClick: this.action.bind(this, "reopen") },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'share-alt' })
)
),
sep
),
!this.props.hirizontal && _react2.default.createElement(
'span',
null,
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: collapseTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large', onClick: this.action.bind(this, "collapse") },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'resize-small' })
)
),
sep
),
this.props.hirizontal && _react2.default.createElement(
'span',
null,
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: expandTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large', onClick: this.action.bind(this, "expand") },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'resize-full' })
)
),
sep
),
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: exportTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large', onClick: this.action.bind(this, "export") },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'save' })
)
),
sep,
_react2.default.createElement(
_reactDropzone2.default,
{ onDrop: this.onDrop.bind(this), multiple: false, className: 'dropzone', activeClassName: 'dropzone-active' },
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: restoreTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large' },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'open' })
)
)
),
sep,
_react2.default.createElement(
'span',
null,
_react2.default.createElement(
_OverlayTrigger2.default,
{ placement: placement, overlay: cleanTooltip },
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'large', onClick: this.action.bind(this, "clean") },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'trash' })
)
)
)
);
}
}, {
key: 'onDrop',
value: function onDrop(files) {
var _this2 = this;
var file = files[0];
var reader = new FileReader();
reader.onload = function (e) {
_this2.action("restore", JSON.parse(e.target.result));
};
reader.readAsText(file);
}
}, {
key: 'action',
value: function action(_action, arg) {
if (this.props.onToolbar) this.props.onToolbar(_action, arg);
}
}]);
return GraphiQLToolbar;
}(_react2.default.Component);
exports.GraphiQLToolbar = GraphiQLToolbar;
GraphiQLToolbar.propTypes = {
onToolbar: _react.PropTypes.func,
hasClosed: _react.PropTypes.bool.isRequired,
hirizontal: _react.PropTypes.bool
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"react-bootstrap/lib/Button":290,"react-bootstrap/lib/Glyphicon":305,"react-bootstrap/lib/OverlayTrigger":319,"react-bootstrap/lib/Tooltip":328,"react-dropzone":337}],3:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphiQLWorkspace = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _moment = require('moment');
var _moment2 = _interopRequireDefault(_moment);
var _GraphiQLTab = require('./GraphiQLTab');
var _config = require('./config');
var _Tabs = require('react-bootstrap/lib/Tabs');
var _Tabs2 = _interopRequireDefault(_Tabs);
var _Tab = require('react-bootstrap/lib/Tab');
var _Tab2 = _interopRequireDefault(_Tab);
var _Button = require('react-bootstrap/lib/Button');
var _Button2 = _interopRequireDefault(_Button);
var _Glyphicon = require('react-bootstrap/lib/Glyphicon');
var _Glyphicon2 = _interopRequireDefault(_Glyphicon);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var GraphiQLWorkspace = exports.GraphiQLWorkspace = function (_React$Component) {
_inherits(GraphiQLWorkspace, _React$Component);
function GraphiQLWorkspace(props) {
_classCallCheck(this, GraphiQLWorkspace);
var _this = _possibleConstructorReturn(this, (GraphiQLWorkspace.__proto__ || Object.getPrototypeOf(GraphiQLWorkspace)).call(this));
_this.graphiql = {};
_this.state = {
config: props.config,
visited: [props.config.getActiveId()]
};
var orig = document.addEventListener;
document.addEventListener = function (name, fn) {
// please don't look here... it's terrible and very very fragile
if (name === 'keydown' && fn.toString().indexOf('_runQueryAtCursor') != -1) {
console.info("Ignoring GraphiQL keydown event handler!");
} else {
orig.apply(document, arguments);
}
};
return _this;
}
_createClass(GraphiQLWorkspace, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener('keydown', this.keyHandler.bind(this), true);
}
}, {
key: 'keyHandler',
value: function keyHandler(event) {
if ((event.metaKey || event.ctrlKey) && event.keyCode === 13) {
event.preventDefault();
var comp = this.graphiql[this.state.config.getActiveId()];
if (comp) {
comp.runQueryAtCursor();
}
return false;
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (this.state.aboutToPrepare) {
this.setState({
aboutToPrepare: undefined,
visited: this.visited(this.state.aboutToPrepare) ? this.state.visited : [].concat(_toConsumableArray(this.state.visited), [this.state.aboutToPrepare])
});
}
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var tabs = this.state.config.getTabs().map(function (tab) {
var label = _react2.default.createElement(
'div',
null,
_lodash2.default.truncate(tab.state.name),
' ',
_react2.default.createElement(
_Button2.default,
{ bsStyle: 'link', bsSize: 'xsmall', className: 'close-button', onClick: _this2.closeTab.bind(_this2, tab.getId()) },
_react2.default.createElement(_Glyphicon2.default, { glyph: 'remove' })
)
);
if (_this2.visited(tab.getId())) {
return _react2.default.createElement(
_Tab2.default,
{ key: tab.getId(), eventKey: tab.getId(), title: label },
_react2.default.createElement(_GraphiQLTab.GraphiQLTab, {
ref: function ref(cmp) {
return _this2.graphiql[tab.getId()] = cmp;
},
onToolbar: _this2.toolbar.bind(_this2),
hasClosed: _this2.state.config.state.closedTabs.length > 0,
onNameChange: _this2.refresh.bind(_this2),
proxyUrl: _this2.props.proxyUrl,
tab: tab,
app: _this2.state.config })
);
} else {
return _react2.default.createElement(
_Tab2.default,
{ key: tab.getId(), eventKey: tab.getId(), title: label },
_react2.default.createElement('div', null)
);
}
});
return _react2.default.createElement(
_Tabs2.default,
{ id: 'main-tabs', animation: false, className: 'tabs', activeKey: this.state.config.getActiveId(), onSelect: this.handleSelect.bind(this) },
tabs,
_react2.default.createElement(
_Tab2.default,
{ key: 'new', eventKey: 'new', title: '+ New Query', className: 'new-tab' },
_react2.default.createElement('a', { id: 'downloadAnchorElem', style: { display: "none" } })
)
);
}
}, {
key: 'refresh',
value: function refresh() {
this.setState({ config: this.state.config });
}
}, {
key: 'formatDate',
value: function formatDate(d) {
return (0, _moment2.default)(d).format("YYYY-MM-DD-HH-mm-ss");
}
}, {
key: 'toolbar',
value: function toolbar(action, arg) {
var _this3 = this;
if (action === "reopen") {
this.state.config.reopenTab();
this.setState({ config: this.state.config, aboutToPrepare: this.state.config.getActiveId() });
} else if (action === "export") {
this.state.config.state.tabIds.forEach(function (id) {
var comp = _this3.graphiql[id];
if (comp) {
comp.persistState();
}
});
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(this.state.config.export(), null, 2));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", 'graphiql-workspace-' + this.formatDate(new Date()) + '.json');
dlAnchorElem.click();
} else if (action == "restore") {
this.state.config.cleanup();
var newConfig = new _config.AppConfig(arg);
this.setState({
config: newConfig,
visited: [],
aboutToPrepare: newConfig.getActiveId()
});
} else if (action == "clean") {
this.state.config.cleanup();
var _newConfig = new _config.AppConfig("graphiql", graphiql.bootstrapOptions);
this.setState({
config: _newConfig,
visited: [],
aboutToPrepare: _newConfig.getActiveId()
});
}
if (this.props.onToolbar) this.props.onToolbar.apply(this, arguments);
}
}, {
key: 'closeTab',
value: function closeTab(id, e) {
e.preventDefault();
e.stopPropagation();
var comp = this.graphiql[id];
if (comp) {
comp.persistState();
}
this.state.config.removeTab(id);
var newVisited = this.state.visited.filter(function (v) {
return v != id;
});
this.setState({ config: this.state.config, visited: newVisited, aboutToPrepare: this.state.config.getActiveId() });
}
}, {
key: 'handleSelect',
value: function handleSelect(key) {
if (key == "new") {
var tab = this.state.config.addTab();
this.setState({ config: this.state.config, aboutToPrepare: tab.getId() });
} else if (key) {
this.state.config.state.setState({ activeId: key });
this.setState({ config: this.state.config, aboutToPrepare: key });
}
}
}, {
key: 'visited',
value: function visited(idx) {
return this.state.visited.indexOf(idx) != -1;
}
}]);
return GraphiQLWorkspace;
}(_react2.default.Component);
GraphiQLWorkspace.propTypes = {
config: _react.PropTypes.object.isRequired,
onToolbar: _react.PropTypes.func,
proxyUrl: _react.PropTypes.string
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./GraphiQLTab":1,"./config":7,"lodash":286,"moment":288,"react-bootstrap/lib/Button":290,"react-bootstrap/lib/Glyphicon":305,"react-bootstrap/lib/Tab":322,"react-bootstrap/lib/Tabs":327}],4:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HeaderEditor = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _Form = require('react-bootstrap/lib/Form');
var _Form2 = _interopRequireDefault(_Form);
var _FormGroup = require('react-bootstrap/lib/FormGroup');
var _FormGroup2 = _interopRequireDefault(_FormGroup);
var _FormControl = require('react-bootstrap/lib/FormControl');
var _FormControl2 = _interopRequireDefault(_FormControl);
var _Button = require('react-bootstrap/lib/Button');
var _Button2 = _interopRequireDefault(_Button);
var _Col = require('react-bootstrap/lib/Col');
var _Col2 = _interopRequireDefault(_Col);
var _ControlLabel = require('react-bootstrap/lib/ControlLabel');
var _ControlLabel2 = _interopRequireDefault(_ControlLabel);
var _Modal = require('react-bootstrap/lib/Modal');
var _Modal2 = _interopRequireDefault(_Modal);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var HeaderEditor = exports.HeaderEditor = function (_React$Component) {
_inherits(HeaderEditor, _React$Component);
function HeaderEditor(props) {
_classCallCheck(this, HeaderEditor);
var _this = _possibleConstructorReturn(this, (HeaderEditor.__proto__ || Object.getPrototypeOf(HeaderEditor)).call(this));
_this.state = { header: props.header ? _this.copy(props.header) : null };
return _this;
}
_createClass(HeaderEditor, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.setState({ header: props.header ? this.copy(props.header) : null });
}
}, {
key: 'copy',
value: function copy(h) {
return { name: h.name, value: h.value };
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
_Modal2.default,
{ show: !!this.state.header, onHide: this.hide.bind(this), bsSize: 'large', 'aria-labelledby': 'contained-modal-title-base' },
_react2.default.createElement(
_Modal2.default.Header,
{ closeButton: true },
_react2.default.createElement(
_Modal2.default.Title,
{ id: 'contained-modal-title-base' },
this.props.headerIdx == null ? 'Add' : 'Edit',
' Header'
)
),
_react2.default.createElement(
_Modal2.default.Body,
null,
_react2.default.createElement(
_Form2.default,
{ horizontal: true },
_react2.default.createElement(
_FormGroup2.default,
{ controlId: 'name-input' },
_react2.default.createElement(
_Col2.default,
{ componentClass: _ControlLabel2.default, sm: 2 },
'Name'
),
_react2.default.createElement(
_Col2.default,
{ sm: 10 },
_react2.default.createElement(_FormControl2.default, { placeholder: 'Header name', bsSize: 'small', value: this.state.header ? this.state.header.name : '', onChange: this.nameChange.bind(this) })
)
),
_react2.default.createElement(
_FormGroup2.default,
{ controlId: 'value-input' },
_react2.default.createElement(
_Col2.default,
{ componentClass: _ControlLabel2.default, sm: 2 },
'Value'
),
_react2.default.createElement(
_Col2.default,
{ sm: 10 },
_react2.default.createElement(_FormControl2.default, { placeholder: 'Header value', bsSize: 'small', value: this.state.header ? this.state.header.value : '', onChange: this.valueChange.bind(this) })
)
)
)
),
_react2.default.createElement(
_Modal2.default.Footer,
null,
_react2.default.createElement(
_Button2.default,
{ onClick: this.ok.bind(this), bsStyle: 'primary' },
'Ok'
),
_react2.default.createElement(
_Button2.default,
{ onClick: this.hide.bind(this) },
'Close'
)
)
);
}
}, {
key: 'nameChange',
value: function nameChange(e) {
this.state.header.name = e.target.value;
this.setState({ header: this.state.header });
}
}, {
key: 'valueChange',
value: function valueChange(e) {
this.state.header.value = e.target.value;
this.setState({ header: this.state.header });
}
}, {
key: 'hide',
value: function hide() {
if (this.props.onFinish) this.props.onFinish();
}
}, {
key: 'ok',
value: function ok() {
if (this.props.onFinish) this.props.onFinish(this.state.header, this.props.headerIdx);
}
}]);
return HeaderEditor;
}(_react2.default.Component);
HeaderEditor.propTypes = {
headerIdx: _react.PropTypes.number,
header: _react.PropTypes.object,
onFinish: _react.PropTypes.func
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"lodash":286,"react-bootstrap/lib/Button":290,"react-bootstrap/lib/Col":293,"react-bootstrap/lib/ControlLabel":294,"react-bootstrap/lib/Form":300,"react-bootstrap/lib/FormControl":301,"react-bootstrap/lib/FormGroup":304,"react-bootstrap/lib/Modal":310}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var KeepLastTaskQueue = exports.KeepLastTaskQueue = function () {
function KeepLastTaskQueue() {
_classCallCheck(this, KeepLastTaskQueue);
this.next = null;
this.curr = null;
}
_createClass(KeepLastTaskQueue, [{
key: "add",
value: function add(taskFn) {
this.next = taskFn;
this.run();
}
}, {
key: "run",
value: function run() {
var _this = this;
if (!this.curr && this.next) {
this.curr = this.next;
this.curr().then(function (v) {
_this.curr = null;
_this.run();
v;
}, function (error) {
_this.curr = null;
_this.run();
});
this.next = null;
}
}
}]);
return KeepLastTaskQueue;
}();
},{}],6:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.QuerySelectionButton = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _MenuItem = require('react-bootstrap/lib/MenuItem');
var _MenuItem2 = _interopRequireDefault(_MenuItem);
var _OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger');
var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger);
var _DropdownButton = require('react-bootstrap/lib/DropdownButton');
var _DropdownButton2 = _interopRequireDefault(_DropdownButton);
var _Popover = require('react-bootstrap/lib/Popover');
var _Popover2 = _interopRequireDefault(_Popover);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var QuerySelectionButton = exports.QuerySelectionButton = function (_React$Component) {
_inherits(QuerySelectionButton, _React$Component);
function QuerySelectionButton() {
_classCallCheck(this, QuerySelectionButton);
return _possibleConstructorReturn(this, (QuerySelectionButton.__proto__ || Object.getPrototypeOf(QuerySelectionButton)).apply(this, arguments));
}
_createClass(QuerySelectionButton, [{
key: 'render',
value: function render() {
var _this2 = this;
if (this.getList().length > 0) {
var items = this.getList().map(function (item, idx) {
var popover = _react2.default.createElement(
_Popover2.default,
{ id: 'popover-trigger-hover-focus', className: 'code-pop' },
_react2.default.createElement(
'pre',
null,
item.query
),
item.variables && item.variables != "" && _react2.default.createElement(
'span',
null,
_react2.default.createElement(
'strong',
null,
'Variables'
),
_react2.default.createElement(
'pre',
null,
_this2.renderVars(item.variables)
)
)
);
return _react2.default.createElement(
_MenuItem2.default,
{ eventKey: idx, onClick: _this2.itemClick.bind(_this2, item), key: idx },
_react2.default.createElement(
_OverlayTrigger2.default,
{ trigger: ['focus', 'hover'], placement: 'right', overlay: popover, onClick: _this2.itemClick.bind(_this2, item) },
_react2.default.createElement(
'span',
null,
_this2.renderQueryLabel(item)
)
)
);
});
return _react2.default.createElement(
_DropdownButton2.default,
{ id: this.props.name + "Button", bsSize: 'small', title: this.props.name, className: 'toolbar-button bs-toolbar-button' },
items
);
} else {
return _react2.default.createElement('span', null);
}
}
}, {
key: 'getList',
value: function getList() {
return this.props.list;
}
}, {
key: 'itemClick',
value: function itemClick(item) {
if (this.props.onQuery) {
this.props.onQuery(item);
}
}
}, {
key: 'renderVars',
value: function renderVars(vars) {
return vars;
}
}, {
key: 'renderQueryLabel',
value: function renderQueryLabel(query) {
return _lodash2.default.truncate(_lodash2.default.replace(query.query, /\n/, " "), { length: 50 });
}
}]);
return QuerySelectionButton;
}(_react2.default.Component);
QuerySelectionButton.propTypes = {
name: _react.PropTypes.string.isRequired,
list: _react.PropTypes.array.isRequired,
onQuery: _react.PropTypes.func
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"lodash":286,"react-bootstrap/lib/DropdownButton":296,"react-bootstrap/lib/MenuItem":309,"react-bootstrap/lib/OverlayTrigger":319,"react-bootstrap/lib/Popover":320}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TabConfig = exports.AppConfig = exports.State = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _lodash = require("lodash");
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var State = exports.State = function () {
function State(key, initial) {
_classCallCheck(this, State);
this.key = key;
this.state = {};
var restored = this.restoreState();
this.setState(initial);
this.setState(restored);
}
_createClass(State, [{
key: "setState",
value: function setState(s) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(s)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
this.state[key] = s[key];
this[key] = s[key];
this.setItem(key, s[key]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return this;
}
}, {
key: "restoreState",
value: function restoreState() {
var res = {};
for (var key in localStorage) {
if (key.startsWith(this.prefix())) {
var name = key.substring(this.prefix().length);
res[name] = this.getItem(name);
}
}
return res;
}
}, {
key: "cleanupState",
value: function cleanupState() {
for (var key in localStorage) {
if (key.startsWith(this.prefix())) {
localStorage.removeItem(key);
}
}
this.freeze = true;
}
}, {
key: "prefix",
value: function prefix() {
return this.key + "-";
}
}, {
key: "setItem",
value: function setItem(key, val) {
if (!this.freeze) {
this.state[key] = val;
this[key] = val;
return localStorage.setItem(this.prefix() + key, JSON.stringify({ data: val }));
}
}
}, {
key: "getItem",
value: function getItem(key) {
var value = localStorage.getItem(this.prefix() + key);
if (value) return JSON.parse(value).data;else return undefined;
}
}]);
return State;
}();
function sameQuery(q1, q2) {
return q1.query == q2.query && q1.variables == q2.variables;
}
var AppConfig = exports.AppConfig = function () {
function AppConfig(key) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, AppConfig);
if (typeof key === "string") {
(function () {
var _options$defaultUrl = options.defaultUrl,
defaultUrl = _options$defaultUrl === undefined ? 'http://try.sangria-graphql.org/graphql' : _options$defaultUrl,
_options$defaultQuery = options.defaultQuery,
defaultQuery = _options$defaultQuery === undefined ? '{\n hero {\n id\n name\n \n friends {\n name\n }\n }\n}' : _options$defaultQuery,
_options$defaultVaria = options.defaultVariables,
defaultVariables = _options$defaultVaria === undefined ? '' : _options$defaultVaria,
_options$defaultHeade = options.defaultHeaders,
defaultHeaders = _options$defaultHeade === undefined ? [] : _options$defaultHeade;
_this.state = new State(key, {
key: key,
lastId: 0,
tabIds: [],
closedTabs: [],
defaultUrl: defaultUrl,
defaultQuery: defaultQuery,
defaultVariables: defaultVariables,
defaultProxy: false,
defaultHeaders: defaultHeaders,
usedUrls: [],
recentHeaders: [],
maxTabHistory: 20,
maxUrlHistory: 20,
maxHistory: 20,
savedQueries: []
});
_this.tabInfo = _this.state.tabIds.map(function (id) {
return new TabConfig(id, { defaultQuery: defaultQuery, defaultVariables: defaultVariables });
});
if (_this.getTabs().length == 0) {
_this.addTab();
}
})();
} else {
var tabs = key.tabs;
var doc = _lodash2.default.omit(key, ["tabs"]);
this.state = new State(doc.key, doc);
this.tabInfo = tabs.map(function (t) {
return new TabConfig(t);
});
}
}
_createClass(AppConfig, [{
key: "getSavedQueries",
value: function getSavedQueries() {
return this.state.savedQueries || [];
}
}, {
key: "addSavedQuery",
value: function addSavedQuery(query) {
this.state.setState({ savedQueries: [query].concat(_toConsumableArray(this.getSavedQueries())) });
}
}, {
key: "hasSavedQuery",
value: function hasSavedQuery(query) {
return !!_lodash2.default.find(this.getSavedQueries(), function (q) {
return sameQuery(q, query);
});
}
}, {
key: "removeSavedQuery",
value: function removeSavedQuery(query) {
this.state.setState({ savedQueries: this.getSavedQueries().filter(function (q) {
return !sameQuery(q, query);
}) });
}
}, {
key: "export",
value: function _export() {
var ownState = this.state.state;
ownState.tabs = this.tabInfo.map(function (t) {
return t.state.state;
});
return ownState;
}
}, {
key: "rememberUrl",
value: function rememberUrl(url) {
if (this.state.usedUrls.indexOf(url) < 0) {
if (this.state.usedUrls.length >= this.state.maxUrlHistory) this.state.setState({ usedUrls: _lodash2.default.dropRight(this.state.usedUrls) });
this.state.setState({
usedUrls: [url].concat(_toConsumableArray(this.state.usedUrls))
});
return true;
} else {
return false;
}
}
}, {
key: "rememberHeader",
value: function rememberHeader(header) {
var simplified = this.state.recentHeaders.map(function (h) {
return h.name + h.value;
});
if (simplified.indexOf(header.name + header.value) < 0) {
if (this.state.recentHeaders.length >= 20) this.state.setState({ recentHeaders: _lodash2.default.dropRight(this.state.recentHeaders) });
this.state.setState({
recentHeaders: [header].concat(_toConsumableArray(this.state.recentHeaders))
});
return true;
} else {
return false;
}
}
}, {
key: "addTab",
value: function addTab() {
var id = this.genId();
var key = "tab" + id;
var _state = this.state,
tabIds = _state.tabIds,
defaultUrl = _state.defaultUrl,
defaultProxy = _state.defaultProxy,
defaultHeaders = _state.defaultHeaders,
maxHistory = _state.maxHistory,
defaultQuery = _state.defaultQuery,
defaultVariables = _state.defaultVariables;
var tab = new TabConfig(key, {
name: "Query " + (tabIds.length + 1),
url: defaultUrl,
proxy: defaultProxy,
headers: defaultHeaders,
maxHistory: maxHistory || 20,
query: defaultQuery,
variables: defaultVariables
});
this.tabInfo.push(tab);
this.state.setState({
tabIds: [].concat(_toConsumableArray(tabIds), [key]),
activeId: key
});
return tab;
}
}, {
key: "getActiveId",
value: function getActiveId() {
return this.state.activeId;
}
}, {
key: "removeTab",
value: function removeTab(id) {
var _this2 = this;
var idx = -1;
this.tabInfo.forEach(function (e, i) {
if (e.getId() === id) {
_this2.rememberTab(e);
e.cleanup();
idx = i;
}
});
this.tabInfo.splice(idx, 1);
this.state.tabIds.splice(idx, 1);
this.state.setState({ tabIds: this.state.tabIds });
var newTab = null;
if (this.tabInfo.length == 0) {
newTab = this.addTab();
} else {
if (this.getActiveId() == id) {
var activeIdx = idx == this.tabInfo.length ? idx - 1 : idx;
this.state.setState({ activeId: this.tabInfo[activeIdx].getId() });
}
}
return newTab;
}
}, {
key: "rememberTab",
value: function rememberTab(tab) {
if (this.state.closedTabs.length >= this.state.maxTabHistory) this.state.setState({ closedTabs: _lodash2.default.dropRight(this.state.closedTabs) });
this.state.setState({ closedTabs: [tab.state.state].concat(_toConsumableArray(this.state.closedTabs)) });
}
}, {
key: "reopenTab",
value: function reopenTab() {
if (this.state.closedTabs.length > 0) {
var tabConf = this.state.closedTabs.shift();
var tab = new TabConfig(tabConf);
this.tabInfo.push(tab);
this.state.setState({
tabIds: [].concat(_toConsumableArray(this.state.tabIds), [tab.getId()]),
activeId: tab.getId()
});
this.state.setState({ closedTabs: this.state.closedTabs });
return tab;
}
}
}, {
key: "getTabs",
value: function getTabs() {
return this.tabInfo;
}
}, {
key: "genId",
value: function genId() {
this.state.setState({ lastId: this.state.lastId + 1 });
return "" + this.state.lastId;
}
}, {
key: "getState",
value: function getState() {
return this.state;
}
}, {
key: "cleanup",
value: function cleanup() {
this.tabInfo.forEach(function (t) {
return t.cleanup();
});
this.state.cleanupState();
}
}]);
return AppConfig;
}();
var TabConfig = exports.TabConfig = function () {
function TabConfig(key) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, TabConfig);
if (typeof key === "string") {
var name = options.name,
url = options.url,
proxy = options.proxy,
headers = options.headers,
maxHistory = options.maxHistory,
query = options.query,
variables = options.variables;
this.state = new State(key, {
id: key,
name: name,
url: url,
proxy: proxy,
headers: headers,
collapsed: false,
maxHistory: maxHistory,
history: [],
"graphiql:query": query,
"graphiql:variables": variables
});
} else {
// restoring
this.state = new State(key.id, key);
}
}
_createClass(TabConfig, [{
key: "getMaxHistory",
value: function getMaxHistory() {
return this.state.maxHistory || 20;
}
}, {
key: "getHistory",
value: function getHistory() {
return this.state.history || [];
}
}, {
key: "getQuery",
value: function getQuery() {
return this.state["graphiql:query"] || "";
}
}, {
key: "getVariables",
value: function getVariables() {
return this.state["graphiql:variables"] || "";
}
}, {
key: "rememberQuery",
value: function rememberQuery(query) {
var same = this.getHistory().length > 0 ? sameQuery(this.getHistory()[0], query) : false;
var introspection = query.query.indexOf("query IntrospectionQuery") >= 0;
if (!same && !introspection) {
if (this.getHistory().length >= this.getMaxHistory()) this.state.setState({ history: _lodash2.default.dropRight(this.getHistory()) });
this.state.setState({
history: [query].concat(_toConsumableArray(this.getHistory()))
});
return true;
} else {
return false;
}
}
}, {
key: "getId",
value: function getId() {
return this.state.id;
}
}, {
key: "cleanup",
value: function cleanup() {
this.state.cleanupState();
}
}, {
key: "getState",
value: function getState() {
return this.state;
}
}]);
return TabConfig;
}();
},{"lodash":286}],8:[function(require,module,exports){
'use strict';
var GraphiQLTab = require('./GraphiQLTab');
var GraphiQLToolbar = require('./GraphiQLToolbar');
var GraphiQLWorkspace = require('./GraphiQLWorkspace');
var HeaderEditor = require('./HeaderEditor');
var KeepLastTaskQueue = require('./KeepLastTaskQueue');
var QuerySelectionButton = require('./QuerySelectionButton');
var config = require('./config');
module.exports = {
GraphiQLTab: GraphiQLTab.GraphiQLTab,
GraphiQLToolbar: GraphiQLToolbar.GraphiQLToolbar,
GraphiQLWorkspace: GraphiQLWorkspace.GraphiQLWorkspace,
HeaderEditor: HeaderEditor.HeaderEditor,
KeepLastTaskQueue: KeepLastTaskQueue.KeepLastTaskQueue,
QuerySelectionButton: QuerySelectionButton.QuerySelectionButton,
State: config.State,
sameQuery: config.sameQuery,
AppConfig: config.AppConfig,
TabConfig: config.TabConfig
};
},{"./GraphiQLTab":1,"./GraphiQLToolbar":2,"./GraphiQLWorkspace":3,"./HeaderEditor":4,"./KeepLastTaskQueue":5,"./QuerySelectionButton":6,"./config":7}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _graphql = require('graphql');
Object.defineProperty(exports, 'introspectionQuery', {
enumerable: true,
get: function get() {
return _graphql.introspectionQuery;
}
});
// Some GraphQL services do not support subscriptions and fail an introspection
// query which includes the `subscriptionType` field as the stock introspection
// query does. This backup query removes that field.
var introspectionQuerySansSubscriptions = exports.introspectionQuerySansSubscriptions = '\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n';
},{"graphql":144}],10:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true };
},{"core-js/library/fn/object/assign":56}],11:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":57}],12:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":58}],13:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/set-prototype-of":59}],14:[function(require,module,exports){
"use strict";
exports["default"] = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
exports.__esModule = true;
},{}],15:[function(require,module,exports){
"use strict";
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
exports["default"] = _Object$assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
exports.__esModule = true;
},{"babel-runtime/core-js/object/assign":10}],16:[function(require,module,exports){
"use strict";
var _Object$create = require("babel-runtime/core-js/object/create")["default"];
var _Object$setPrototypeOf = require("babel-runtime/core-js/object/set-prototype-of")["default"];
exports["default"] = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = _Object$create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _Object$setPrototypeOf ? _Object$setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
exports.__esModule = true;
},{"babel-runtime/core-js/object/create":11,"babel-runtime/core-js/object/set-prototype-of":13}],17:[function(require,module,exports){
"use strict";
exports["default"] = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
exports.__esModule = true;
},{}],18:[function(require,module,exports){
"use strict";
exports["default"] = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
exports.__esModule = true;
},{}],19:[function(require,module,exports){
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// register as 'classnames', consistent with npm package name
define('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
},{}],20:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _getHintsAtPosition = require('./utils/getHintsAtPosition');
var _getHintsAtPosition2 = _interopRequireDefault(_getHintsAtPosition);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers a "hint" helper for CodeMirror.
*
* Using CodeMirror's "hint" addon: https://codemirror.net/demo/complete.html
* Given an editor, this helper will take the token at the cursor and return a
* list of suggested tokens.
*
* Options:
*
* - schema: GraphQLSchema provides the hinter with positionally relevant info
*
* Additional Events:
*
* - hasCompletion (codemirror, data, token) - signaled when the hinter has a
* new list of completion suggestions.
*
*/
/**
* Copyright (c) 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.
*/
_codemirror2.default.registerHelper('hint', 'graphql', function (editor, options) {
var schema = options.schema;
if (!schema) {
return;
}
var cur = editor.getCursor();
var token = editor.getTokenAt(cur);
var results = (0, _getHintsAtPosition2.default)(schema, editor.getValue(), cur, token);
if (results && results.list && results.list.length > 0) {
results.from = _codemirror2.default.Pos(results.from.line, results.from.column);
results.to = _codemirror2.default.Pos(results.to.line, results.to.column);
_codemirror2.default.signal(editor, 'hasCompletion', editor, results, token);
}
return results;
});
},{"./utils/getHintsAtPosition":31,"codemirror":55}],21:[function(require,module,exports){
'use strict';
var _graphql = require('graphql');
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _getTypeInfo = require('./utils/getTypeInfo');
var _getTypeInfo2 = _interopRequireDefault(_getTypeInfo);
var _SchemaReference = require('./utils/SchemaReference');
require('./utils/info-addon');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers GraphQL "info" tooltips for CodeMirror.
*
* When hovering over a token, this presents a tooltip explaining it.
*
* Options:
*
* - schema: GraphQLSchema provides positionally relevant info.
* - hoverTime: The number of ms to wait before showing info. (Default 500)
* - renderDescription: Convert a description to some HTML, Useful since
* descriptions are often Markdown formatted.
* - onClick: A function called when a named thing is clicked.
*
*/
_codemirror2.default.registerHelper('info', 'graphql', function (token, options) {
if (!options.schema || !token.state) {
return;
}
var state = token.state;
var kind = state.kind;
var step = state.step;
var typeInfo = (0, _getTypeInfo2.default)(options.schema, token.state);
// Given a Schema and a Token, produce the contents of an info tooltip.
// To do this, create a div element that we will render "into" and then pass
// it to various rendering functions.
if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef) {
var into = document.createElement('div');
renderField(into, typeInfo, options);
renderDescription(into, options, typeInfo.fieldDef);
return into;
} else if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) {
var _into = document.createElement('div');
renderDirective(_into, typeInfo, options);
renderDescription(_into, options, typeInfo.directiveDef);
return _into;
} else if (kind === 'Argument' && step === 0 && typeInfo.argDef) {
var _into2 = document.createElement('div');
renderArg(_into2, typeInfo, options);
renderDescription(_into2, options, typeInfo.argDef);
return _into2;
} else if (kind === 'EnumValue' && typeInfo.enumValue && typeInfo.enumValue.description) {
var _into3 = document.createElement('div');
renderEnumValue(_into3, typeInfo, options);
renderDescription(_into3, options, typeInfo.enumValue);
return _into3;
} else if (kind === 'NamedType' && typeInfo.type && typeInfo.type.description) {
var _into4 = document.createElement('div');
renderType(_into4, typeInfo, options, typeInfo.type);
renderDescription(_into4, options, typeInfo.type);
return _into4;
}
});
/**
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function renderField(into, typeInfo, options) {
renderQualifiedField(into, typeInfo, options);
renderTypeAnnotation(into, typeInfo, options, typeInfo.type);
}
function renderQualifiedField(into, typeInfo, options) {
var fieldName = typeInfo.fieldDef.name;
if (fieldName.slice(0, 2) !== '__') {
renderType(into, typeInfo, options, typeInfo.parentType);
text(into, '.');
}
text(into, fieldName, 'field-name', options, (0, _SchemaReference.getFieldReference)(typeInfo));
}
function renderDirective(into, typeInfo, options) {
var name = '@' + typeInfo.directiveDef.name;
text(into, name, 'directive-name', options, (0, _SchemaReference.getDirectiveReference)(typeInfo));
}
function renderArg(into, typeInfo, options) {
if (typeInfo.directiveDef) {
renderDirective(into, typeInfo, options);
} else if (typeInfo.fieldDef) {
renderQualifiedField(into, typeInfo, options);
}
var name = typeInfo.argDef.name;
text(into, '(');
text(into, name, 'arg-name', options, (0, _SchemaReference.getArgumentReference)(typeInfo));
renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType);
text(into, ')');
}
function renderTypeAnnotation(into, typeInfo, options, t) {
text(into, ': ');
renderType(into, typeInfo, options, t);
}
function renderEnumValue(into, typeInfo, options) {
var name = typeInfo.enumValue.name;
renderType(into, typeInfo, options, typeInfo.inputType);
text(into, '.');
text(into, name, 'enum-value', options, (0, _SchemaReference.getEnumValueReference)(typeInfo));
}
function renderType(into, typeInfo, options, t) {
if (t instanceof _graphql.GraphQLNonNull) {
renderType(into, typeInfo, options, t.ofType);
text(into, '!');
} else if (t instanceof _graphql.GraphQLList) {
text(into, '[');
renderType(into, typeInfo, options, t.ofType);
text(into, ']');
} else {
text(into, t.name, 'type-name', options, (0, _SchemaReference.getTypeReference)(typeInfo, t));
}
}
function renderDescription(into, options, def) {
var description = def.description;
if (description) {
var descriptionDiv = document.createElement('div');
descriptionDiv.className = 'info-description';
if (options.renderDescription) {
descriptionDiv.innerHTML = options.renderDescription(description);
} else {
descriptionDiv.appendChild(document.createTextNode(description));
}
into.appendChild(descriptionDiv);
}
renderDeprecation(into, options, def);
}
function renderDeprecation(into, options, def) {
var reason = def.deprecationReason;
if (reason) {
var deprecationDiv = document.createElement('div');
deprecationDiv.className = 'info-deprecation';
if (options.renderDescription) {
deprecationDiv.innerHTML = options.renderDescription(reason);
} else {
deprecationDiv.appendChild(document.createTextNode(reason));
}
var label = document.createElement('span');
label.className = 'info-deprecation-label';
label.appendChild(document.createTextNode('Deprecated: '));
deprecationDiv.insertBefore(label, deprecationDiv.firstChild);
into.appendChild(deprecationDiv);
}
}
function text(into, content, className, options, ref) {
if (className) {
(function () {
var onClick = options.onClick;
var node = document.createElement(onClick ? 'a' : 'span');
if (onClick) {
// Providing a href forces proper a tag behavior, though we don't actually
// want clicking the node to navigate anywhere.
node.href = 'javascript:void 0'; // eslint-disable-line no-script-url
node.addEventListener('click', function (e) {
onClick(ref, e);
});
}
node.className = className;
node.appendChild(document.createTextNode(content));
into.appendChild(node);
})();
} else {
into.appendChild(document.createTextNode(content));
}
}
},{"./utils/SchemaReference":29,"./utils/getTypeInfo":32,"./utils/info-addon":34,"codemirror":55,"graphql":144}],22:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _getTypeInfo = require('./utils/getTypeInfo');
var _getTypeInfo2 = _interopRequireDefault(_getTypeInfo);
var _SchemaReference = require('./utils/SchemaReference');
require('./utils/jump-addon');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers GraphQL "jump" links for CodeMirror.
*
* When command-hovering over a token, this converts it to a link, which when
* pressed will call the provided onClick handler.
*
* Options:
*
* - schema: GraphQLSchema provides positionally relevant info.
* - onClick: A function called when a named thing is clicked.
*
*/
/**
* Copyright (c) 2017, 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.
*/
_codemirror2.default.registerHelper('jump', 'graphql', function (token, options) {
if (!options.schema || !options.onClick || !token.state) {
return;
}
// Given a Schema and a Token, produce a "SchemaReference" which refers to
// the particular artifact from the schema (such as a type, field, argument,
// or directive) that token references.
var state = token.state;
var kind = state.kind;
var step = state.step;
var typeInfo = (0, _getTypeInfo2.default)(options.schema, state);
if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef) {
return (0, _SchemaReference.getFieldReference)(typeInfo);
} else if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) {
return (0, _SchemaReference.getDirectiveReference)(typeInfo);
} else if (kind === 'Argument' && step === 0 && typeInfo.argDef) {
return (0, _SchemaReference.getArgumentReference)(typeInfo);
} else if (kind === 'EnumValue' && typeInfo.enumValue) {
return (0, _SchemaReference.getEnumValueReference)(typeInfo);
} else if (kind === 'NamedType' && typeInfo.type) {
return (0, _SchemaReference.getTypeReference)(typeInfo);
}
});
},{"./utils/SchemaReference":29,"./utils/getTypeInfo":32,"./utils/jump-addon":36,"codemirror":55}],23:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphql = require('graphql');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers a "lint" helper for CodeMirror.
*
* Using CodeMirror's "lint" addon: https://codemirror.net/demo/lint.html
* Given the text within an editor, this helper will take that text and return
* a list of linter issues, derived from GraphQL's parse and validate steps.
*
* Options:
*
* - schema: GraphQLSchema provides the linter with positionally relevant info
*
*/
/**
* Copyright (c) 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.
*/
_codemirror2.default.registerHelper('lint', 'graphql', function (text, options, editor) {
var schema = options.schema;
if (!schema) {
return [];
}
try {
var ast = (0, _graphql.parse)(text);
var validationErrorAnnotations = mapCat((0, _graphql.validate)(schema, ast), function (error) {
return annotations(editor, error, 'error', 'validation');
});
// Note: findDeprecatedUsages was added in graphql@0.9.0, but we want to
// support older versions of graphql-js.
var deprecationWarningAnnotations = !_graphql.findDeprecatedUsages ? [] : mapCat((0, _graphql.findDeprecatedUsages)(schema, ast), function (error) {
return annotations(editor, error, 'warning', 'deprecation');
});
return validationErrorAnnotations.concat(deprecationWarningAnnotations);
} catch (error) {
var location = error.locations[0];
var pos = _codemirror2.default.Pos(location.line - 1, location.column);
var token = editor.getTokenAt(pos);
return [{
message: error.message,
severity: 'error',
type: 'syntax',
from: _codemirror2.default.Pos(location.line - 1, token.start),
to: _codemirror2.default.Pos(location.line - 1, token.end)
}];
}
});
function annotations(editor, error, severity, type) {
return error.nodes.map(function (node) {
var highlightNode = node.kind !== 'Variable' && node.name ? node.name : node.variable ? node.variable : node;
return {
message: error.message,
severity: severity,
type: type,
from: editor.posFromIndex(highlightNode.loc.start),
to: editor.posFromIndex(highlightNode.loc.end)
};
});
}
// General utility for map-cating (aka flat-mapping).
function mapCat(array, mapper) {
return Array.prototype.concat.apply([], array.map(mapper));
}
},{"codemirror":55,"graphql":144}],24:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _onlineParser = require('./utils/onlineParser');
var _onlineParser2 = _interopRequireDefault(_onlineParser);
var _Rules = require('./utils/Rules');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The GraphQL mode is defined as a tokenizer along with a list of rules, each
* of which is either a function or an array.
*
* * Function: Provided a token and the stream, returns an expected next step.
* * Array: A list of steps to take in order.
*
* A step is either another rule, or a terminal description of a token. If it
* is a rule, that rule is pushed onto the stack and the parsing continues from
* that point.
*
* If it is a terminal description, the token is checked against it using a
* `match` function. If the match is successful, the token is colored and the
* rule is stepped forward. If the match is unsuccessful, the remainder of the
* rule is skipped and the previous rule is advanced.
*
* This parsing algorithm allows for incremental online parsing within various
* levels of the syntax tree and results in a structured `state` linked-list
* which contains the relevant information to produce valuable typeaheads.
*/
_codemirror2.default.defineMode('graphql', function (config) {
var parser = (0, _onlineParser2.default)({
eatWhitespace: function eatWhitespace(stream) {
return stream.eatWhile(_Rules.isIgnored);
},
LexRules: _Rules.LexRules,
ParseRules: _Rules.ParseRules,
editorConfig: { tabSize: config.tabSize }
});
return {
config: config,
startState: parser.startState,
token: parser.token,
indent: indent,
electricInput: /^\s*[})\]]/,
fold: 'brace',
lineComment: '#',
closeBrackets: {
pairs: '()[]{}""',
explode: '()[]{}'
}
};
}); /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function indent(state, textAfter) {
var levels = state.levels;
// If there is no stack of levels, use the current level.
// Otherwise, use the top level, pre-emptively dedenting for close braces.
var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
return level * this.config.indentUnit;
}
},{"./utils/Rules":28,"./utils/onlineParser":38,"codemirror":55}],25:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _onlineParser = require('../utils/onlineParser');
var _onlineParser2 = _interopRequireDefault(_onlineParser);
var _RuleHelpers = require('../utils/RuleHelpers');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This mode defines JSON, but provides a data-laden parser state to enable
* better code intelligence.
*/
_codemirror2.default.defineMode('graphql-results', function (config) {
var parser = (0, _onlineParser2.default)({
eatWhitespace: function eatWhitespace(stream) {
return stream.eatSpace();
},
LexRules: LexRules,
ParseRules: ParseRules,
editorConfig: { tabSize: config.tabSize }
});
return {
config: config,
startState: parser.startState,
token: parser.token,
indent: indent,
electricInput: /^\s*[}\]]/,
fold: 'brace',
closeBrackets: {
pairs: '[]{}""',
explode: '[]{}'
}
};
}); /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function indent(state, textAfter) {
var levels = state.levels;
// If there is no stack of levels, use the current level.
// Otherwise, use the top level, pre-emptively dedenting for close braces.
var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
return level * this.config.indentUnit;
}
/**
* The lexer rules. These are exactly as described by the spec.
*/
var LexRules = {
// All Punctuation used in JSON.
Punctuation: /^\[|]|\{|\}|:|,/,
// JSON Number.
Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
// JSON String.
String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,
// JSON literal keywords.
Keyword: /^true|false|null/
};
/**
* The parser rules for JSON.
*/
var ParseRules = {
Document: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Entry', (0, _RuleHelpers.p)(',')), (0, _RuleHelpers.p)('}')],
Entry: [(0, _RuleHelpers.t)('String', 'def'), (0, _RuleHelpers.p)(':'), 'Value'],
Value: function Value(token) {
switch (token.kind) {
case 'Number':
return 'NumberValue';
case 'String':
return 'StringValue';
case 'Punctuation':
switch (token.value) {
case '[':
return 'ListValue';
case '{':
return 'ObjectValue';
}
return null;
case 'Keyword':
switch (token.value) {
case 'true':case 'false':
return 'BooleanValue';
case 'null':
return 'NullValue';
}
return null;
}
},
NumberValue: [(0, _RuleHelpers.t)('Number', 'number')],
StringValue: [(0, _RuleHelpers.t)('String', 'string')],
BooleanValue: [(0, _RuleHelpers.t)('Keyword', 'builtin')],
NullValue: [(0, _RuleHelpers.t)('Keyword', 'keyword')],
ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value', (0, _RuleHelpers.p)(',')), (0, _RuleHelpers.p)(']')],
ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField', (0, _RuleHelpers.p)(',')), (0, _RuleHelpers.p)('}')],
ObjectField: [(0, _RuleHelpers.t)('String', 'property'), (0, _RuleHelpers.p)(':'), 'Value']
};
},{"../utils/RuleHelpers":27,"../utils/onlineParser":38,"codemirror":55}],26:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) 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.
*/
/**
* CharacterStream implements a stream of character tokens given a source text.
* The API design follows that of CodeMirror.StringStream.
*
* Required:
*
* sourceText: (string), A raw GraphQL source text. Works best if a line
* is supplied.
*
*/
var CharacterStream = function () {
function CharacterStream(sourceText) {
_classCallCheck(this, CharacterStream);
this._start = 0;
this._pos = 0;
this._sourceText = sourceText;
}
CharacterStream.prototype.getStartOfToken = function getStartOfToken() {
return this._start;
};
CharacterStream.prototype.getCurrentPosition = function getCurrentPosition() {
return this._pos;
};
CharacterStream.prototype._testNextCharacter = function _testNextCharacter(pattern) {
var character = this._sourceText.charAt(this._pos);
return typeof pattern === 'string' ? character === pattern : pattern.test ? pattern.test(character) : pattern(character);
};
CharacterStream.prototype.eol = function eol() {
return this._sourceText.length === this._pos;
};
CharacterStream.prototype.sol = function sol() {
return this._pos === 0;
};
CharacterStream.prototype.peek = function peek() {
return this._sourceText.charAt(this._pos) ? this._sourceText.charAt(this._pos) : null;
};
CharacterStream.prototype.next = function next() {
var char = this._sourceText.charAt(this._pos);
this._pos++;
return char;
};
CharacterStream.prototype.eat = function eat(pattern) {
var isMatched = this._testNextCharacter(pattern);
if (isMatched) {
this._start = this._pos;
this._pos++;
return this._sourceText.charAt(this._pos - 1);
}
return undefined;
};
CharacterStream.prototype.eatWhile = function eatWhile(match) {
var isMatched = this._testNextCharacter(match);
var didEat = false;
// If a match, treat the total upcoming matches as one token
if (isMatched) {
didEat = isMatched;
this._start = this._pos;
}
while (isMatched) {
this._pos++;
isMatched = this._testNextCharacter(match);
didEat = true;
}
return didEat;
};
CharacterStream.prototype.eatSpace = function eatSpace() {
return this.eatWhile(/[\s\u00a0]/);
};
CharacterStream.prototype.skipToEnd = function skipToEnd() {
this._pos = this._sourceText.length;
};
CharacterStream.prototype.skipTo = function skipTo(position) {
this._pos = position;
};
CharacterStream.prototype.match = function match(pattern) {
var consume = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var caseFold = arguments[2];
var token = null;
var match = null;
switch (typeof pattern) {
case 'string':
var regex = new RegExp(pattern, caseFold ? 'i' : '');
match = regex.test(this._sourceText.substr(this._pos, pattern.length));
token = pattern;
break;
case 'object': // RegExp
case 'function':
match = this._sourceText.slice(this._pos).match(pattern);
token = match && match[0];
break;
}
if (match && (typeof pattern === 'string' || match.index === 0)) {
if (consume) {
this._start = this._pos;
this._pos += token.length;
}
return match;
}
// No match available.
return false;
};
CharacterStream.prototype.backUp = function backUp(num) {
this._pos -= num;
};
CharacterStream.prototype.column = function column() {
return this._pos;
};
CharacterStream.prototype.indentation = function indentation() {
var match = this._sourceText.match(/\s*/);
var indent = 0;
if (match && match.index === 0) {
var whitespaces = match[0];
var pos = 0;
while (whitespaces.length > pos) {
if (whitespaces.charCodeAt(pos) === 9) {
indent += 2;
} else {
indent++;
}
pos++;
}
}
return indent;
};
CharacterStream.prototype.current = function current() {
return this._sourceText.slice(this._start, this._pos);
};
return CharacterStream;
}();
exports.default = CharacterStream;
},{}],27:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.opt = opt;
exports.list = list;
exports.butNot = butNot;
exports.t = t;
exports.p = p;
/**
* Copyright (c) 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.
*/
// These functions help build matching rules for ParseRules.
// An optional rule.
function opt(ofRule) {
return { ofRule: ofRule };
}
// A list of another rule.
function list(ofRule, separator) {
return { ofRule: ofRule, isList: true, separator: separator };
}
// An constraint described as `but not` in the GraphQL spec.
function butNot(rule, exclusions) {
var ruleMatch = rule.match;
rule.match = function (token) {
return ruleMatch(token) && exclusions.every(function (exclusion) {
return !exclusion.match(token);
});
};
return rule;
}
// Token of a kind
function t(kind, style) {
return { style: style, match: function match(token) {
return token.kind === kind;
} };
}
// Punctuator
function p(value, style) {
return {
style: style || 'punctuation',
match: function match(token) {
return token.kind === 'Punctuation' && token.value === value;
}
};
}
},{}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ParseRules = exports.LexRules = exports.isIgnored = undefined;
var _RuleHelpers = require('../utils/RuleHelpers');
/**
* Whitespace tokens defined in GraphQL spec.
*/
var isIgnored = exports.isIgnored = function isIgnored(ch) {
return ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF';
};
/**
* The lexer rules. These are exactly as described by the spec.
*/
/**
* Copyright (c) 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.
*/
var LexRules = exports.LexRules = {
// The Name token.
Name: /^[_A-Za-z][_0-9A-Za-z]*/,
// All Punctuation used in GraphQL
Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|@|\[|]|\{|\||\})/,
// Combines the IntValue and FloatValue tokens.
Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
// Note the closing quote is made optional as an IDE experience improvment.
String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,
// Comments consume entire lines.
Comment: /^#.*/
};
/**
* The parser rules. These are very close to, but not exactly the same as the
* spec. Minor deviations allow for a simpler implementation. The resulting
* parser can parse everything the spec declares possible.
*/
var ParseRules = exports.ParseRules = {
Document: [(0, _RuleHelpers.list)('Definition')],
Definition: function Definition(token) {
switch (token.value) {
case '{':
return 'ShortQuery';
case 'query':
return 'Query';
case 'mutation':
return 'Mutation';
case 'subscription':
return 'Subscription';
case 'fragment':
return 'FragmentDefinition';
case 'schema':
return 'SchemaDef';
case 'scalar':
return 'ScalarDef';
case 'type':
return 'ObjectTypeDef';
case 'interface':
return 'InterfaceDef';
case 'union':
return 'UnionDef';
case 'enum':
return 'EnumDef';
case 'input':
return 'InputDef';
case 'extend':
return 'ExtendDef';
case 'directive':
return 'DirectiveDef';
}
},
// Note: instead of "Operation", these rules have been separated out.
ShortQuery: ['SelectionSet'],
Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')],
VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')],
Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')],
DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'],
SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')],
Selection: function Selection(token, stream) {
return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field';
},
// Note: this minor deviation of "AliasedField" simplifies the lookahead.
AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')],
Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')],
Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')],
Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'],
FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')],
InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
TypeCondition: [word('on'), 'NamedType'],
// Variables could be parsed in cases where only Const is expected by spec.
Value: function Value(token) {
switch (token.kind) {
case 'Number':
return 'NumberValue';
case 'String':
return 'StringValue';
case 'Punctuation':
switch (token.value) {
case '[':
return 'ListValue';
case '{':
return 'ObjectValue';
case '$':
return 'Variable';
}
return null;
case 'Name':
switch (token.value) {
case 'true':case 'false':
return 'BooleanValue';
}
if (token.value === 'null') {
return 'NullValue';
}
return 'EnumValue';
}
},
NumberValue: [(0, _RuleHelpers.t)('Number', 'number')],
StringValue: [(0, _RuleHelpers.t)('String', 'string')],
BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')],
NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')],
EnumValue: [name('string-2')],
ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')],
ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')],
ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'],
Type: function Type(token) {
return token.value === '[' ? 'ListType' : 'NonNullType';
},
// NonNullType has been merged into ListType to simplify.
ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))],
NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))],
NamedType: [type('atom')],
Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')],
// GraphQL schema language
SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')],
OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')],
ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')],
ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')],
Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType')],
FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')],
ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')],
InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')],
InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')],
UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))],
UnionMember: ['NamedType'],
EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')],
EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')],
InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')],
ExtendDef: [word('extend'), 'ObjectTypeDef'],
DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))],
DirectiveLocation: [name('string-2')]
};
// A keyword Token.
function word(value) {
return {
style: 'keyword',
match: function match(token) {
return token.kind === 'Name' && token.value === value;
}
};
}
// A Name Token which will decorate the state with a `name`.
function name(style) {
return {
style: style,
match: function match(token) {
return token.kind === 'Name';
},
update: function update(state, token) {
state.name = token.value;
}
};
}
// A Name Token which will decorate the previous state with a `type`.
function type(style) {
return {
style: style,
match: function match(token) {
return token.kind === 'Name';
},
update: function update(state, token) {
state.name = token.value;
state.prevState.prevState.type = token.value;
}
};
}
},{"../utils/RuleHelpers":27}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getFieldReference = getFieldReference;
exports.getDirectiveReference = getDirectiveReference;
exports.getArgumentReference = getArgumentReference;
exports.getEnumValueReference = getEnumValueReference;
exports.getTypeReference = getTypeReference;
var _graphql = require('graphql');
function getFieldReference(typeInfo) {
return {
kind: 'Field',
schema: typeInfo.schema,
field: typeInfo.fieldDef,
type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType
};
}
/**
* Copyright (c), Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getDirectiveReference(typeInfo) {
return {
kind: 'Directive',
schema: typeInfo.schema,
directive: typeInfo.directiveDef
};
}
function getArgumentReference(typeInfo) {
return typeInfo.directiveDef ? {
kind: 'Argument',
schema: typeInfo.schema,
argument: typeInfo.argDef,
directive: typeInfo.directiveDef
} : {
kind: 'Argument',
schema: typeInfo.schema,
argument: typeInfo.argDef,
field: typeInfo.fieldDef,
type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType
};
}
function getEnumValueReference(typeInfo) {
return {
kind: 'EnumValue',
value: typeInfo.enumValue,
type: (0, _graphql.getNamedType)(typeInfo.inputType)
};
}
// Note: for reusability, getTypeReference can produce a reference to any type,
// though it defaults to the current type.
function getTypeReference(typeInfo, type) {
return {
kind: 'Type',
schema: typeInfo.schema,
type: type || typeInfo.type
};
}
function isMetaField(fieldDef) {
return fieldDef.name.slice(0, 2) === '__';
}
},{"graphql":144}],30:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = forEachState;
/**
* Copyright (c) 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.
*/
// Utility for iterating through a CodeMirror parse state stack bottom-up.
function forEachState(stack, fn) {
var reverseStateStack = [];
var state = stack;
while (state && state.kind) {
reverseStateStack.push(state);
state = state.prevState;
}
for (var i = reverseStateStack.length - 1; i >= 0; i--) {
fn(reverseStateStack[i]);
}
}
},{}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getHintsAtPosition;
var _graphql = require('graphql');
var _introspection = require('graphql/type/introspection');
var _forEachState = require('./forEachState');
var _forEachState2 = _interopRequireDefault(_forEachState);
var _getTypeInfo = require('./getTypeInfo');
var _getTypeInfo2 = _interopRequireDefault(_getTypeInfo);
var _hintList = require('./hintList');
var _hintList2 = _interopRequireDefault(_hintList);
var _objectValues = require('./objectValues');
var _objectValues2 = _interopRequireDefault(_objectValues);
var _runParser = require('./runParser');
var _runParser2 = _interopRequireDefault(_runParser);
var _Rules = require('./Rules');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Given GraphQLSchema, sourceText, and context of the current position within
* the source text, provide a list of typeahead entries.
*
* Options:
* - schema: GraphQLSchema
* - sourceText: string. A raw source text used to get fragmentDefinitions
* in a source.
* - cursor: { line: Number, column: Number }. A current cursor position.
* - token: ContextToken. Includes a context for the current cursor position.
* Includes the token string/style (type), the start/end position, and the
* state at the end of the token.
*
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getHintsAtPosition(schema, sourceText, cursor, token) {
// Get the current state, however if the current state is an invalid token,
// then use the previous state to determine which hints to generate.
var state = token.state.kind === 'Invalid' ? token.state.prevState : token.state;
var kind = state.kind;
var step = state.step;
var typeInfo = (0, _getTypeInfo2.default)(schema, state);
// Definition kinds
if (kind === 'Document') {
return (0, _hintList2.default)(cursor, token, [{ text: 'query' }, { text: 'mutation' }, { text: 'subscription' }, { text: 'fragment' }, { text: '{' }]);
}
// Field names
if (kind === 'SelectionSet' || kind === 'Field' || kind === 'AliasedField') {
if (typeInfo.parentType) {
var fields = typeInfo.parentType.getFields ? (0, _objectValues2.default)(typeInfo.parentType.getFields()) : [];
if ((0, _graphql.isAbstractType)(typeInfo.parentType)) {
fields.push(_introspection.TypeNameMetaFieldDef);
}
if (typeInfo.parentType === schema.getQueryType()) {
fields.push(_introspection.SchemaMetaFieldDef, _introspection.TypeMetaFieldDef);
}
return (0, _hintList2.default)(cursor, token, fields.map(function (field) {
return {
text: field.name,
type: field.type,
description: field.description,
isDeprecated: field.isDeprecated,
deprecationReason: field.deprecationReason
};
}));
}
}
// Argument names
if (kind === 'Arguments' || kind === 'Argument' && step === 0) {
var argDefs = typeInfo.argDefs;
if (argDefs) {
return (0, _hintList2.default)(cursor, token, argDefs.map(function (argDef) {
return {
text: argDef.name,
type: argDef.type,
description: argDef.description
};
}));
}
}
// Input Object fields
if (kind === 'ObjectValue' || kind === 'ObjectField' && step === 0) {
if (typeInfo.objectFieldDefs) {
var objectFields = (0, _objectValues2.default)(typeInfo.objectFieldDefs);
return (0, _hintList2.default)(cursor, token, objectFields.map(function (field) {
return {
text: field.name,
type: field.type,
description: field.description
};
}));
}
}
// Input values: Enum and Boolean
if (kind === 'EnumValue' || kind === 'ListValue' && step === 1 || kind === 'ObjectField' && step === 2 || kind === 'Argument' && step === 2) {
var _ret = function () {
var namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType);
if (namedInputType instanceof _graphql.GraphQLEnumType) {
var valueMap = namedInputType.getValues();
var values = (0, _objectValues2.default)(valueMap);
return {
v: (0, _hintList2.default)(cursor, token, values.map(function (value) {
return {
text: value.name,
type: namedInputType,
description: value.description,
isDeprecated: value.isDeprecated,
deprecationReason: value.deprecationReason
};
}))
};
} else if (namedInputType === _graphql.GraphQLBoolean) {
return {
v: (0, _hintList2.default)(cursor, token, [{ text: 'true', type: _graphql.GraphQLBoolean, description: 'Not false.' }, { text: 'false', type: _graphql.GraphQLBoolean, description: 'Not true.' }])
};
}
}();
if (typeof _ret === "object") return _ret.v;
}
// Fragment type conditions
if (kind === 'TypeCondition' && step === 1 || kind === 'NamedType' && state.prevState.kind === 'TypeCondition') {
var possibleTypes = void 0;
if (typeInfo.parentType) {
if ((0, _graphql.isAbstractType)(typeInfo.parentType)) {
(function () {
// Collect both the possible Object types as well as the interfaces
// they implement.
var possibleObjTypes = schema.getPossibleTypes(typeInfo.parentType);
var possibleIfaceMap = Object.create(null);
possibleObjTypes.forEach(function (type) {
type.getInterfaces().forEach(function (iface) {
possibleIfaceMap[iface.name] = iface;
});
});
possibleTypes = possibleObjTypes.concat((0, _objectValues2.default)(possibleIfaceMap));
})();
} else {
// The parent type is a non-abstract Object type, so the only possible
// type that can be used is that same type.
possibleTypes = [typeInfo.parentType];
}
} else {
var typeMap = schema.getTypeMap();
possibleTypes = (0, _objectValues2.default)(typeMap).filter(_graphql.isCompositeType);
}
return (0, _hintList2.default)(cursor, token, possibleTypes.map(function (type) {
return {
text: type.name,
description: type.description
};
}));
}
// Fragment spread names
if (kind === 'FragmentSpread' && step === 1) {
var _ret3 = function () {
var typeMap = schema.getTypeMap();
var defState = getDefinitionState(token.state);
var fragments = getFragmentDefinitions(sourceText);
// Filter down to only the fragments which may exist here.
var relevantFrags = fragments.filter(function (frag) {
return (
// Only include fragments with known types.
typeMap[frag.typeCondition.name.value] &&
// Only include fragments which are not cyclic.
!(defState && defState.kind === 'FragmentDefinition' && defState.name === frag.name.value) &&
// Only include fragments which could possibly be spread here.
(0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])
);
});
return {
v: (0, _hintList2.default)(cursor, token, relevantFrags.map(function (frag) {
return {
text: frag.name.value,
type: typeMap[frag.typeCondition.name.value],
description: 'fragment ' + frag.name.value + ' on ' + frag.typeCondition.name.value
};
}))
};
}();
if (typeof _ret3 === "object") return _ret3.v;
}
// Variable definition types
if (kind === 'VariableDefinition' && step === 2 || kind === 'ListType' && step === 1 || kind === 'NamedType' && (state.prevState.kind === 'VariableDefinition' || state.prevState.kind === 'ListType')) {
var inputTypeMap = schema.getTypeMap();
var inputTypes = (0, _objectValues2.default)(inputTypeMap).filter(_graphql.isInputType);
return (0, _hintList2.default)(cursor, token, inputTypes.map(function (type) {
return {
text: type.name,
description: type.description
};
}));
}
// Directive names
if (kind === 'Directive') {
var directives = schema.getDirectives().filter(function (directive) {
return canUseDirective(state.prevState.kind, directive);
});
return (0, _hintList2.default)(cursor, token, directives.map(function (directive) {
return {
text: directive.name,
description: directive.description
};
}));
}
}
function canUseDirective(kind, directive) {
var locations = directive.locations;
switch (kind) {
case 'Query':
return locations.indexOf('QUERY') !== -1;
case 'Mutation':
return locations.indexOf('MUTATION') !== -1;
case 'Subscription':
return locations.indexOf('SUBSCRIPTION') !== -1;
case 'Field':
case 'AliasedField':
return locations.indexOf('FIELD') !== -1;
case 'FragmentDefinition':
return locations.indexOf('FRAGMENT_DEFINITION') !== -1;
case 'FragmentSpread':
return locations.indexOf('FRAGMENT_SPREAD') !== -1;
case 'InlineFragment':
return locations.indexOf('INLINE_FRAGMENT') !== -1;
}
return false;
}
// Finds all fragment definition ASTs in a source.
function getFragmentDefinitions(sourceText) {
var fragmentDefs = [];
(0, _runParser2.default)(sourceText, {
eatWhitespace: function eatWhitespace(stream) {
return stream.eatWhile(_Rules.isIgnored);
},
LexRules: _Rules.LexRules,
ParseRules: _Rules.ParseRules
}, function (stream, state) {
if (state.kind === 'FragmentDefinition' && state.name && state.type) {
fragmentDefs.push({
kind: 'FragmentDefinition',
name: {
kind: 'Name',
value: state.name
},
typeCondition: {
kind: 'NamedType',
name: {
kind: 'Name',
value: state.type
}
}
});
}
});
return fragmentDefs;
}
// Utility for returning the state representing the Definition this token state
// is within, if any.
function getDefinitionState(tokenState) {
var definitionState = void 0;
(0, _forEachState2.default)(tokenState, function (state) {
switch (state.kind) {
case 'Query':
case 'ShortQuery':
case 'Mutation':
case 'Subscription':
case 'FragmentDefinition':
definitionState = state;
break;
}
});
return definitionState;
}
},{"./Rules":28,"./forEachState":30,"./getTypeInfo":32,"./hintList":33,"./objectValues":37,"./runParser":39,"graphql":144,"graphql/type/introspection":164}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getTypeInfo;
var _graphql = require('graphql');
var _introspection = require('graphql/type/introspection');
var _forEachState = require('./forEachState');
var _forEachState2 = _interopRequireDefault(_forEachState);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Utility for collecting rich type information given any token's state
* from the graphql-mode parser.
*/
function getTypeInfo(schema, tokenState) {
var info = {
schema: schema,
type: null,
parentType: null,
inputType: null,
directiveDef: null,
fieldDef: null,
argDef: null,
argDefs: null,
objectFieldDefs: null
};
(0, _forEachState2.default)(tokenState, function (state) {
switch (state.kind) {
case 'Query':
case 'ShortQuery':
info.type = schema.getQueryType();
break;
case 'Mutation':
info.type = schema.getMutationType();
break;
case 'Subscription':
info.type = schema.getSubscriptionType();
break;
case 'InlineFragment':
case 'FragmentDefinition':
if (state.type) {
info.type = schema.getType(state.type);
}
break;
case 'Field':
case 'AliasedField':
info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null;
info.type = info.fieldDef && info.fieldDef.type;
break;
case 'SelectionSet':
info.parentType = (0, _graphql.getNamedType)(info.type);
break;
case 'Directive':
info.directiveDef = state.name && schema.getDirective(state.name);
break;
case 'Arguments':
var parentDef = state.prevState.kind === 'Field' ? info.fieldDef : state.prevState.kind === 'Directive' ? info.directiveDef : state.prevState.kind === 'AliasedField' ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null;
info.argDefs = parentDef && parentDef.args;
break;
case 'Argument':
info.argDef = null;
if (info.argDefs) {
for (var i = 0; i < info.argDefs.length; i++) {
if (info.argDefs[i].name === state.name) {
info.argDef = info.argDefs[i];
break;
}
}
}
info.inputType = info.argDef && info.argDef.type;
break;
case 'EnumValue':
var enumType = (0, _graphql.getNamedType)(info.inputType);
info.enumValue = enumType instanceof _graphql.GraphQLEnumType ? find(enumType.getValues(), function (val) {
return val.value === state.name;
}) : null;
break;
case 'ListValue':
var nullableType = (0, _graphql.getNullableType)(info.inputType);
info.inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null;
break;
case 'ObjectValue':
var objectType = (0, _graphql.getNamedType)(info.inputType);
info.objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null;
break;
case 'ObjectField':
var objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null;
info.inputType = objectField && objectField.type;
break;
case 'NamedType':
info.type = schema.getType(state.name);
break;
}
});
return info;
}
// Gets the field definition given a type and field name
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getFieldDef(schema, type, fieldName) {
if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === type) {
return _introspection.SchemaMetaFieldDef;
}
if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === type) {
return _introspection.TypeMetaFieldDef;
}
if (fieldName === _introspection.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) {
return _introspection.TypeNameMetaFieldDef;
}
if (type.getFields) {
return type.getFields()[fieldName];
}
}
// Returns the first item in the array which causes predicate to return truthy.
function find(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array[i];
}
}
}
},{"./forEachState":30,"graphql":144,"graphql/type/introspection":164}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = hintList;
/**
* Copyright (c) 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.
*/
// Create the expected hint response given a possible list and a token
function hintList(cursor, token, list) {
var hints = filterAndSortList(list, normalizeText(token.string));
if (!hints) {
return;
}
var tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end;
return {
list: hints,
from: { line: cursor.line, column: tokenStart },
to: { line: cursor.line, column: token.end }
};
}
// Given a list of hint entries and currently typed text, sort and filter to
// provide a concise list.
function filterAndSortList(list, text) {
if (!text) {
return filterNonEmpty(list, function (entry) {
return !entry.isDeprecated;
});
}
var byProximity = list.map(function (entry) {
return {
proximity: getProximity(normalizeText(entry.text), text),
entry: entry
};
});
var conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, function (pair) {
return pair.proximity <= 2;
}), function (pair) {
return !pair.entry.isDeprecated;
});
var sortedMatches = conciseMatches.sort(function (a, b) {
return (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length;
});
return sortedMatches.map(function (pair) {
return pair.entry;
});
}
// Filters the array by the predicate, unless it results in an empty array,
// in which case return the original array.
function filterNonEmpty(array, predicate) {
var filtered = array.filter(predicate);
return filtered.length === 0 ? array : filtered;
}
function normalizeText(text) {
return text.toLowerCase().replace(/\W/g, '');
}
// Determine a numeric proximity for a suggestion based on current text.
function getProximity(suggestion, text) {
// start with lexical distance
var proximity = lexicalDistance(text, suggestion);
if (suggestion.length > text.length) {
// do not penalize long suggestions.
proximity -= suggestion.length - text.length - 1;
// penalize suggestions not starting with this phrase
proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5;
}
return proximity;
}
/**
* Computes the lexical distance between strings A and B.
*
* The "distance" between two strings is given by counting the minimum number
* of edits needed to transform string A into string B. An edit can be an
* insertion, deletion, or substitution of a single character, or a swap of two
* adjacent characters.
*
* This distance can be useful for detecting typos in input or sorting
*
* @param {string} a
* @param {string} b
* @return {int} distance in number of edits
*/
function lexicalDistance(a, b) {
var i = void 0;
var j = void 0;
var d = [];
var aLength = a.length;
var bLength = b.length;
for (i = 0; i <= aLength; i++) {
d[i] = [i];
}
for (j = 1; j <= bLength; j++) {
d[0][j] = j;
}
for (i = 1; i <= aLength; i++) {
for (j = 1; j <= bLength; j++) {
var cost = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
return d[aLength][bLength];
}
},{}],34:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_codemirror2.default.defineOption('info', false, function (cm, options, old) {
if (old && old !== _codemirror2.default.Init) {
var oldOnMouseOver = cm.state.info.onMouseOver;
_codemirror2.default.off(cm.getWrapperElement(), 'mouseover', oldOnMouseOver);
clearTimeout(cm.state.info.hoverTimeout);
delete cm.state.info;
}
if (options) {
var state = cm.state.info = createState(options);
state.onMouseOver = onMouseOver.bind(null, cm);
_codemirror2.default.on(cm.getWrapperElement(), 'mouseover', state.onMouseOver);
}
}); /**
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function createState(options) {
return {
options: options instanceof Function ? { render: options } : options === true ? {} : options
};
}
function getHoverTime(cm) {
var options = cm.state.info.options;
return options && options.hoverTime || 500;
}
function onMouseOver(cm, e) {
var state = cm.state.info;
var target = e.target || e.srcElement;
if (target.nodeName !== 'SPAN' || state.hoverTimeout !== undefined) {
return;
}
var box = target.getBoundingClientRect();
var hoverTime = getHoverTime(cm);
state.hoverTimeout = setTimeout(onHover, hoverTime);
var onMouseMove = function onMouseMove() {
clearTimeout(state.hoverTimeout);
state.hoverTimeout = setTimeout(onHover, hoverTime);
};
var onMouseOut = function onMouseOut() {
_codemirror2.default.off(document, 'mousemove', onMouseMove);
_codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
clearTimeout(state.hoverTimeout);
state.hoverTimeout = undefined;
};
var onHover = function onHover() {
_codemirror2.default.off(document, 'mousemove', onMouseMove);
_codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
state.hoverTimeout = undefined;
onMouseHover(cm, box);
};
_codemirror2.default.on(document, 'mousemove', onMouseMove);
_codemirror2.default.on(cm.getWrapperElement(), 'mouseout', onMouseOut);
}
function onMouseHover(cm, box) {
var pos = cm.coordsChar({
left: (box.left + box.right) / 2,
top: (box.top + box.bottom) / 2
});
var state = cm.state.info;
var options = state.options;
var render = options.render || cm.getHelper(pos, 'info');
if (render) {
var token = cm.getTokenAt(pos, true);
if (token) {
var info = render(token, options, cm);
if (info) {
showPopup(cm, box, info);
}
}
}
}
function showPopup(cm, box, info) {
var popup = document.createElement('div');
popup.className = 'CodeMirror-info';
popup.appendChild(info);
document.body.appendChild(popup);
var popupBox = popup.getBoundingClientRect();
var popupStyle = popup.currentStyle || window.getComputedStyle(popup);
var popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight);
var popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom);
var topPos = box.bottom;
if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) {
topPos = box.top - popupHeight;
}
if (topPos < 0) {
topPos = box.bottom;
}
var leftPos = Math.max(0, window.innerWidth - popupWidth - 15);
if (leftPos > box.left) {
leftPos = box.left;
}
popup.style.opacity = 1;
popup.style.top = topPos + 'px';
popup.style.left = leftPos + 'px';
var popupTimeout = void 0;
var onMouseOverPopup = function onMouseOverPopup() {
clearTimeout(popupTimeout);
};
var onMouseOut = function onMouseOut() {
clearTimeout(popupTimeout);
popupTimeout = setTimeout(hidePopup, 200);
};
var hidePopup = function hidePopup() {
_codemirror2.default.off(popup, 'mouseover', onMouseOverPopup);
_codemirror2.default.off(popup, 'mouseout', onMouseOut);
_codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
if (popup.style.opacity) {
popup.style.opacity = 0;
setTimeout(function () {
if (popup.parentNode) {
popup.parentNode.removeChild(popup);
}
}, 600);
} else if (popup.parentNode) {
popup.parentNode.removeChild(popup);
}
};
_codemirror2.default.on(popup, 'mouseover', onMouseOverPopup);
_codemirror2.default.on(popup, 'mouseout', onMouseOut);
_codemirror2.default.on(cm.getWrapperElement(), 'mouseout', onMouseOut);
}
},{"codemirror":55}],35:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = jsonParse;
/**
* Copyright (c) 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.
*/
/**
* This JSON parser simply walks the input, generating an AST. Use this in lieu
* of JSON.parse if you need character offset parse errors and an AST parse tree
* with location information.
*
* If an error is encountered, a SyntaxError will be thrown, with properties:
*
* - message: string
* - start: int - the start inclusive offset of the syntax error
* - end: int - the end exclusive offset of the syntax error
*
*/
function jsonParse(str) {
string = str;
strLen = str.length;
start = end = lastEnd = -1;
ch();
lex();
var ast = parseObj();
expect('EOF');
return ast;
}
var string = void 0;
var strLen = void 0;
var start = void 0;
var end = void 0;
var lastEnd = void 0;
var code = void 0;
var kind = void 0;
function parseObj() {
var nodeStart = start;
var members = [];
expect('{');
if (!skip('}')) {
do {
members.push(parseMember());
} while (skip(','));
expect('}');
}
return {
kind: 'Object',
start: nodeStart,
end: lastEnd,
members: members
};
}
function parseMember() {
var nodeStart = start;
var key = kind === 'String' ? curToken() : null;
expect('String');
expect(':');
var value = parseVal();
return {
kind: 'Member',
start: nodeStart,
end: lastEnd,
key: key,
value: value
};
}
function parseArr() {
var nodeStart = start;
var values = [];
expect('[');
if (!skip(']')) {
do {
values.push(parseVal());
} while (skip(','));
expect(']');
}
return {
kind: 'Array',
start: nodeStart,
end: lastEnd,
values: values
};
}
function parseVal() {
switch (kind) {
case '[':
return parseArr();
case '{':
return parseObj();
case 'String':
case 'Number':
case 'Boolean':
case 'Null':
var token = curToken();
lex();
return token;
}
return expect('Value');
}
function curToken() {
return { kind: kind, start: start, end: end, value: JSON.parse(string.slice(start, end)) };
}
function expect(str) {
if (kind === str) {
lex();
return;
}
var found = void 0;
if (kind === 'EOF') {
found = '[end of file]';
} else if (end - start > 1) {
found = '`' + string.slice(start, end) + '`';
} else {
var match = string.slice(start).match(/^.+?\b/);
found = '`' + (match ? match[0] : string[start]) + '`';
}
throw syntaxError('Expected ' + str + ' but found ' + found + '.');
}
function syntaxError(message) {
return { message: message, start: start, end: end };
}
function skip(k) {
if (kind === k) {
lex();
return true;
}
}
function ch() {
if (end < strLen) {
end++;
code = end === strLen ? 0 : string.charCodeAt(end);
}
}
function lex() {
lastEnd = end;
while (code === 9 || code === 10 || code === 13 || code === 32) {
ch();
}
if (code === 0) {
kind = 'EOF';
return;
}
start = end;
switch (code) {
// "
case 34:
kind = 'String';
return readString();
// -, 0-9
case 45:
case 48:case 49:case 50:case 51:case 52:
case 53:case 54:case 55:case 56:case 57:
kind = 'Number';
return readNumber();
// f
case 102:
if (string.slice(start, start + 5) !== 'false') {
break;
}
end += 4;ch();
kind = 'Boolean';
return;
// n
case 110:
if (string.slice(start, start + 4) !== 'null') {
break;
}
end += 3;ch();
kind = 'Null';
return;
// t
case 116:
if (string.slice(start, start + 4) !== 'true') {
break;
}
end += 3;ch();
kind = 'Boolean';
return;
}
kind = string[start];
ch();
}
function readString() {
ch();
while (code !== 34 && code > 31) {
if (code === 92) {
// \
ch();
switch (code) {
case 34: // "
case 47: // /
case 92: // \
case 98: // b
case 102: // f
case 110: // n
case 114: // r
case 116:
// t
ch();
break;
case 117:
// u
ch();
readHex();
readHex();
readHex();
readHex();
break;
default:
throw syntaxError('Bad character escape sequence.');
}
} else if (end === strLen) {
throw syntaxError('Unterminated string.');
} else {
ch();
}
}
if (code === 34) {
ch();
return;
}
throw syntaxError('Unterminated string.');
}
function readHex() {
if (code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 70 || // A-F
code >= 97 && code <= 102 // a-f
) {
return ch();
}
throw syntaxError('Expected hexadecimal digit.');
}
function readNumber() {
if (code === 45) {
// -
ch();
}
if (code === 48) {
// 0
ch();
} else {
readDigits();
}
if (code === 46) {
// .
ch();
readDigits();
}
if (code === 69 || code === 101) {
// E e
ch();
if (code === 43 || code === 45) {
// + -
ch();
}
readDigits();
}
}
function readDigits() {
if (code < 48 || code > 57) {
// 0 - 9
throw syntaxError('Expected decimal digit.');
}
do {
ch();
} while (code >= 48 && code <= 57); // 0 - 9
}
},{}],36:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_codemirror2.default.defineOption('jump', false, function (cm, options, old) {
if (old && old !== _codemirror2.default.Init) {
var oldOnMouseOver = cm.state.jump.onMouseOver;
_codemirror2.default.off(cm.getWrapperElement(), 'mouseover', oldOnMouseOver);
var oldOnMouseOut = cm.state.jump.onMouseOut;
_codemirror2.default.off(cm.getWrapperElement(), 'mouseout', oldOnMouseOut);
_codemirror2.default.off(document, 'keydown', cm.state.jump.onKeyDown);
delete cm.state.jump;
}
if (options) {
var state = cm.state.jump = {
options: options,
onMouseOver: onMouseOver.bind(null, cm),
onMouseOut: onMouseOut.bind(null, cm),
onKeyDown: onKeyDown.bind(null, cm)
};
_codemirror2.default.on(cm.getWrapperElement(), 'mouseover', state.onMouseOver);
_codemirror2.default.on(cm.getWrapperElement(), 'mouseout', state.onMouseOut);
_codemirror2.default.on(document, 'keydown', state.onKeyDown);
}
}); /**
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function onMouseOver(cm, event) {
var target = event.target || event.srcElement;
if (target.nodeName !== 'SPAN') {
return;
}
var box = target.getBoundingClientRect();
var cursor = {
left: (box.left + box.right) / 2,
top: (box.top + box.bottom) / 2
};
cm.state.jump.cursor = cursor;
if (cm.state.jump.isHoldingModifier) {
enableJumpMode(cm);
}
}
function onMouseOut(cm) {
if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) {
cm.state.jump.cursor = null;
return;
}
if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) {
disableJumpMode(cm);
}
}
function onKeyDown(cm, event) {
if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) {
return;
}
cm.state.jump.isHoldingModifier = true;
if (cm.state.jump.cursor) {
enableJumpMode(cm);
}
var onKeyUp = function onKeyUp(upEvent) {
if (upEvent.code !== event.code) {
return;
}
cm.state.jump.isHoldingModifier = false;
if (cm.state.jump.marker) {
disableJumpMode(cm);
}
_codemirror2.default.off(document, 'keyup', onKeyUp);
_codemirror2.default.off(document, 'click', onClick);
cm.off('mousedown', onMouseDown);
};
var onClick = function onClick(clickEvent) {
var destination = cm.state.jump.destination;
if (destination) {
cm.state.jump.options.onClick(destination, clickEvent);
}
};
var onMouseDown = function onMouseDown(_, downEvent) {
if (cm.state.jump.destination) {
downEvent.codemirrorIgnore = true;
}
};
_codemirror2.default.on(document, 'keyup', onKeyUp);
_codemirror2.default.on(document, 'click', onClick);
cm.on('mousedown', onMouseDown);
}
var isMac = navigator && navigator.appVersion.indexOf('Mac') !== -1;
function isJumpModifier(key) {
return key === (isMac ? 'Meta' : 'Control');
}
function enableJumpMode(cm) {
if (cm.state.jump.marker) {
return;
}
var cursor = cm.state.jump.cursor;
var pos = cm.coordsChar(cursor);
var token = cm.getTokenAt(pos, true);
var options = cm.state.jump.options;
var getDestination = options.getDestination || cm.getHelper(pos, 'jump');
if (getDestination) {
var destination = getDestination(token, options, cm);
if (destination) {
var marker = cm.markText({ line: pos.line, ch: token.start }, { line: pos.line, ch: token.end }, { className: 'CodeMirror-jump-token' });
cm.state.jump.marker = marker;
cm.state.jump.destination = destination;
}
}
}
function disableJumpMode(cm) {
var marker = cm.state.jump.marker;
cm.state.jump.marker = null;
cm.state.jump.destination = null;
marker.clear();
}
},{"codemirror":55}],37:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = objectValues;
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function objectValues(object) {
var keys = Object.keys(object);
var len = keys.length;
var values = new Array(len);
for (var i = 0; i < len; ++i) {
values[i] = object[keys[i]];
}
return values;
}
},{}],38:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = onlineParser;
/**
* Copyright (c) 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.
*/
/**
* Builds an online immutable parser, designed to be used as part of a syntax
* highlighting and code intelligence tools.
*
* Options:
*
* eatWhitespace: (
* stream: Stream | CodeMirror.StringStream | CharacterStream
* ) => boolean
* Use CodeMirror API.
*
* LexRules: { [name: string]: RegExp }, Includes `Punctuation`, `Comment`.
*
* ParseRules: { [name: string]: Array<Rule> }, Includes `Document`.
*
* editorConfig: { [name: string]: mixed }, Provides an editor-specific
* configurations set.
*
*/
function onlineParser(options) {
return {
startState: function startState() {
var initialState = { level: 0 };
pushRule(options.ParseRules, initialState, 'Document');
return initialState;
},
token: function token(stream, state) {
return getToken(stream, state, options);
}
};
}
function getToken(stream, state, options) {
var LexRules = options.LexRules,
ParseRules = options.ParseRules,
eatWhitespace = options.eatWhitespace,
editorConfig = options.editorConfig;
// Restore state after an empty-rule.
if (state.rule && state.rule.length === 0) {
popRule(state);
} else if (state.needsAdvance) {
state.needsAdvance = false;
advanceRule(state, true);
}
// Remember initial indentation
if (stream.sol()) {
var tabSize = editorConfig && editorConfig.tabSize || 2;
state.indentLevel = Math.floor(stream.indentation() / tabSize);
}
// Consume spaces and ignored characters
if (eatWhitespace(stream)) {
return 'ws';
}
// Get a matched token from the stream, using lex
var token = lex(LexRules, stream);
// If there's no matching token, skip ahead.
if (!token) {
stream.match(/\S+/);
pushRule(SpecialParseRules, state, 'Invalid');
return 'invalidchar';
}
// If the next token is a Comment, insert a Comment parsing rule.
if (token.kind === 'Comment') {
pushRule(SpecialParseRules, state, 'Comment');
return 'comment';
}
// Save state before continuing.
var backupState = assign({}, state);
// Handle changes in expected indentation level
if (token.kind === 'Punctuation') {
if (/^[{([]/.test(token.value)) {
// Push on the stack of levels one level deeper than the current level.
state.levels = (state.levels || []).concat(state.indentLevel + 1);
} else if (/^[})\]]/.test(token.value)) {
// Pop from the stack of levels.
// If the top of the stack is lower than the current level, lower the
// current level to match.
var levels = state.levels = (state.levels || []).slice(0, -1);
if (levels.length > 0 && levels[levels.length - 1] < state.indentLevel) {
state.indentLevel = levels[levels.length - 1];
}
}
}
while (state.rule) {
// If this is a forking rule, determine what rule to use based on
// the current token, otherwise expect based on the current step.
var expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step];
// Seperator between list elements if necessary.
if (state.needsSeperator) {
expected = expected && expected.separator;
}
if (expected) {
// Un-wrap optional/list ParseRules.
if (expected.ofRule) {
expected = expected.ofRule;
}
// A string represents a Rule
if (typeof expected === 'string') {
pushRule(ParseRules, state, expected);
continue;
}
// Otherwise, match a Terminal.
if (expected.match && expected.match(token)) {
if (expected.update) {
expected.update(state, token);
}
// If this token was a punctuator, advance the parse rule, otherwise
// mark the state to be advanced before the next token. This ensures
// that tokens which can be appended to keep the appropriate state.
if (token.kind === 'Punctuation') {
advanceRule(state, true);
} else {
state.needsAdvance = true;
}
return expected.style;
}
}
unsuccessful(state);
}
// The parser does not know how to interpret this token, do not affect state.
assign(state, backupState);
pushRule(SpecialParseRules, state, 'Invalid');
return 'invalidchar';
}
// A special rule set for parsing comment tokens.
var SpecialParseRules = {
Invalid: [],
Comment: []
};
function assign(to, from) {
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
return to;
}
// Push a new rule onto the state.
function pushRule(ParseRules, state, ruleKind) {
if (!ParseRules[ruleKind]) {
throw new TypeError('Unknown rule: ' + ruleKind);
}
state.prevState = assign({}, state);
state.kind = ruleKind;
state.name = null;
state.type = null;
state.rule = ParseRules[ruleKind];
state.step = 0;
state.needsSeperator = false;
}
// Pop the current rule from the state.
function popRule(state) {
state.kind = state.prevState.kind;
state.name = state.prevState.name;
state.type = state.prevState.type;
state.rule = state.prevState.rule;
state.step = state.prevState.step;
state.needsSeperator = state.prevState.needsSeperator;
state.prevState = state.prevState.prevState;
}
// Advance the step of the current rule.
function advanceRule(state, successful) {
// If this is advancing successfully and the current state is a list, give
// it an opportunity to repeat itself.
if (isList(state)) {
var separator = state.rule[state.step].separator;
if (separator) {
state.needsSeperator = !state.needsSeperator;
// If the separator was optional, then give it an opportunity to repeat.
if (!state.needsSeperator && separator.ofRule) {
return;
}
}
// If this was a successful list parse, then allow it to repeat itself.
if (successful) {
return;
}
}
// Advance the step in the rule. If the rule is completed, pop
// the rule and advance the parent rule as well (recursively).
state.needsSeperator = false;
state.step++;
// While the current rule is completed.
while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) {
popRule(state);
if (state.rule) {
// Do not advance a List step so it has the opportunity to repeat itself.
if (isList(state)) {
if (state.rule[state.step].separator) {
state.needsSeperator = !state.needsSeperator;
}
} else {
state.needsSeperator = false;
state.step++;
}
}
}
}
function isList(state) {
return Array.isArray(state.rule) && state.rule[state.step].isList;
}
// Unwind the state after an unsuccessful match.
function unsuccessful(state) {
// Fall back to the parent rule until you get to an optional or list rule or
// until the entire stack of rules is empty.
while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) {
popRule(state);
}
// If there is still a rule, it must be an optional or list rule.
// Consider this rule a success so that we may move past it.
if (state.rule) {
advanceRule(state, false);
}
}
// Given a stream, returns a { kind, value } pair, or null.
function lex(LexRules, stream) {
var kinds = Object.keys(LexRules);
for (var i = 0; i < kinds.length; i++) {
var match = stream.match(LexRules[kinds[i]]);
if (match) {
return { kind: kinds[i], value: match[0] };
}
}
}
},{}],39:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = runParser;
var _CharacterStream = require('./CharacterStream');
var _CharacterStream2 = _interopRequireDefault(_CharacterStream);
var _onlineParser = require('./onlineParser');
var _onlineParser2 = _interopRequireDefault(_onlineParser);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function runParser(sourceText, parserOptions, callbackFn) {
var parser = (0, _onlineParser2.default)(parserOptions);
var state = parser.startState();
var lines = sourceText.split('\n');
lines.forEach(function (line) {
var stream = new _CharacterStream2.default(line);
while (!stream.eol()) {
var style = parser.token(stream, state);
callbackFn(stream, state, style);
}
});
}
},{"./CharacterStream":26,"./onlineParser":38}],40:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphql = require('graphql');
var _forEachState = require('../utils/forEachState');
var _forEachState2 = _interopRequireDefault(_forEachState);
var _hintList = require('../utils/hintList');
var _hintList2 = _interopRequireDefault(_hintList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers a "hint" helper for CodeMirror.
*
* Using CodeMirror's "hint" addon: https://codemirror.net/demo/complete.html
* Given an editor, this helper will take the token at the cursor and return a
* list of suggested tokens.
*
* Options:
*
* - variableToType: { [variable: string]: GraphQLInputType }
*
* Additional Events:
*
* - hasCompletion (codemirror, data, token) - signaled when the hinter has a
* new list of completion suggestions.
*
*/
/**
* Copyright (c) 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.
*/
_codemirror2.default.registerHelper('hint', 'graphql-variables', function (editor, options) {
var cur = editor.getCursor();
var token = editor.getTokenAt(cur);
var results = getVariablesHint(cur, token, options);
if (results && results.list && results.list.length > 0) {
results.from = _codemirror2.default.Pos(results.from.line, results.from.column);
results.to = _codemirror2.default.Pos(results.to.line, results.to.column);
_codemirror2.default.signal(editor, 'hasCompletion', editor, results, token);
}
return results;
});
function getVariablesHint(cur, token, options) {
// If currently parsing an invalid state, attempt to hint to the prior state.
var state = token.state.kind === 'Invalid' ? token.state.prevState : token.state;
var kind = state.kind;
var step = state.step;
// Variables can only be an object literal.
if (kind === 'Document' && step === 0) {
return (0, _hintList2.default)(cur, token, [{ text: '{' }]);
}
var variableToType = options.variableToType;
if (!variableToType) {
return;
}
var typeInfo = getTypeInfo(variableToType, token.state);
// Top level should typeahead possible variables.
if (kind === 'Document' || kind === 'Variable' && step === 0) {
var variableNames = Object.keys(variableToType);
return (0, _hintList2.default)(cur, token, variableNames.map(function (name) {
return {
text: '"' + name + '": ',
type: variableToType[name]
};
}));
}
// Input Object fields
if (kind === 'ObjectValue' || kind === 'ObjectField' && step === 0) {
if (typeInfo.fields) {
var inputFields = Object.keys(typeInfo.fields).map(function (fieldName) {
return typeInfo.fields[fieldName];
});
return (0, _hintList2.default)(cur, token, inputFields.map(function (field) {
return {
text: '"' + field.name + '": ',
type: field.type,
description: field.description
};
}));
}
}
// Input values.
if (kind === 'StringValue' || kind === 'NumberValue' || kind === 'BooleanValue' || kind === 'NullValue' || kind === 'ListValue' && step === 1 || kind === 'ObjectField' && step === 2 || kind === 'Variable' && step === 2) {
var _ret = function () {
var namedInputType = (0, _graphql.getNamedType)(typeInfo.type);
if (namedInputType instanceof _graphql.GraphQLInputObjectType) {
return {
v: (0, _hintList2.default)(cur, token, [{ text: '{' }])
};
} else if (namedInputType instanceof _graphql.GraphQLEnumType) {
var _ret2 = function () {
var valueMap = namedInputType.getValues();
var values = Object.keys(valueMap).map(function (name) {
return valueMap[name];
});
return {
v: {
v: (0, _hintList2.default)(cur, token, values.map(function (value) {
return {
text: '"' + value.name + '"',
type: namedInputType,
description: value.description
};
}))
}
};
}();
if (typeof _ret2 === "object") return _ret2.v;
} else if (namedInputType === _graphql.GraphQLBoolean) {
return {
v: (0, _hintList2.default)(cur, token, [{ text: 'true', type: _graphql.GraphQLBoolean, description: 'Not false.' }, { text: 'false', type: _graphql.GraphQLBoolean, description: 'Not true.' }])
};
}
}();
if (typeof _ret === "object") return _ret.v;
}
}
// Utility for collecting rich type information given any token's state
// from the graphql-variables-mode parser.
function getTypeInfo(variableToType, tokenState) {
var info = {
type: null,
fields: null
};
(0, _forEachState2.default)(tokenState, function (state) {
if (state.kind === 'Variable') {
info.type = variableToType[state.name];
} else if (state.kind === 'ListValue') {
var nullableType = (0, _graphql.getNullableType)(info.type);
info.type = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null;
} else if (state.kind === 'ObjectValue') {
var objectType = (0, _graphql.getNamedType)(info.type);
info.fields = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null;
} else if (state.kind === 'ObjectField') {
var objectField = state.name && info.fields ? info.fields[state.name] : null;
info.type = objectField && objectField.type;
}
});
return info;
}
},{"../utils/forEachState":30,"../utils/hintList":33,"codemirror":55,"graphql":144}],41:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphql = require('graphql');
var _jsonParse = require('../utils/jsonParse');
var _jsonParse2 = _interopRequireDefault(_jsonParse);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Registers a "lint" helper for CodeMirror.
*
* Using CodeMirror's "lint" addon: https://codemirror.net/demo/lint.html
* Given the text within an editor, this helper will take that text and return
* a list of linter issues ensuring that correct variables were provided.
*
* Options:
*
* - variableToType: { [variable: string]: GraphQLInputType }
*
*/
_codemirror2.default.registerHelper('lint', 'graphql-variables', function (text, options, editor) {
// If there's no text, do nothing.
if (!text) {
return [];
}
// First, linter needs to determine if there are any parsing errors.
var ast = void 0;
try {
ast = (0, _jsonParse2.default)(text);
} catch (syntaxError) {
if (syntaxError.stack) {
throw syntaxError;
}
return [lintError(editor, syntaxError, syntaxError.message)];
}
// If there are not yet known variables, do nothing.
var variableToType = options.variableToType;
if (!variableToType) {
return [];
}
// Then highlight any issues with the provided variables.
return validateVariables(editor, variableToType, ast);
});
// Given a variableToType object, a source text, and a JSON AST, produces a
// list of CodeMirror annotations for any variable validation errors.
/* eslint-disable max-len */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function validateVariables(editor, variableToType, variablesAST) {
var errors = [];
variablesAST.members.forEach(function (member) {
var variableName = member.key.value;
var type = variableToType[variableName];
if (!type) {
errors.push(lintError(editor, member.key, 'Variable "$' + variableName + '" does not appear in any GraphQL query.'));
} else {
validateValue(type, member.value).forEach(function (_ref) {
var node = _ref[0],
message = _ref[1];
errors.push(lintError(editor, node, message));
});
}
});
return errors;
}
// Returns a list of validation errors in the form Array<[Node, String]>.
function validateValue(type, valueAST) {
// Validate non-nullable values.
if (type instanceof _graphql.GraphQLNonNull) {
if (valueAST.kind === 'Null') {
return [[valueAST, 'Type "' + type + '" is non-nullable and cannot be null.']];
}
return validateValue(type.ofType, valueAST);
}
if (valueAST.kind === 'Null') {
return [];
}
// Validate lists of values, accepting a non-list as a list of one.
if (type instanceof _graphql.GraphQLList) {
var _ret = function () {
var itemType = type.ofType;
if (valueAST.kind === 'Array') {
return {
v: mapCat(valueAST.values, function (item) {
return validateValue(itemType, item);
})
};
}
return {
v: validateValue(itemType, valueAST)
};
}();
if (typeof _ret === "object") return _ret.v;
}
// Validate input objects.
if (type instanceof _graphql.GraphQLInputObjectType) {
var _ret2 = function () {
if (valueAST.kind !== 'Object') {
return {
v: [[valueAST, 'Type "' + type + '" must be an Object.']]
};
}
// Validate each field in the input object.
var providedFields = Object.create(null);
var fieldErrors = mapCat(valueAST.members, function (member) {
var fieldName = member.key.value;
providedFields[fieldName] = true;
var inputField = type.getFields()[fieldName];
if (!inputField) {
return [[member.key, 'Type "' + type + '" does not have a field "' + fieldName + '".']];
}
var fieldType = inputField ? inputField.type : undefined;
return validateValue(fieldType, member.value);
});
// Look for missing non-nullable fields.
Object.keys(type.getFields()).forEach(function (fieldName) {
if (!providedFields[fieldName]) {
var fieldType = type.getFields()[fieldName].type;
if (fieldType instanceof _graphql.GraphQLNonNull) {
fieldErrors.push([valueAST, 'Object of type "' + type + '" is missing required field "' + fieldName + '".']);
}
}
});
return {
v: fieldErrors
};
}();
if (typeof _ret2 === "object") return _ret2.v;
}
// Validate common scalars.
if (type.name === 'Boolean' && valueAST.kind !== 'Boolean' || type.name === 'String' && valueAST.kind !== 'String' || type.name === 'ID' && valueAST.kind !== 'Number' && valueAST.kind !== 'String' || type.name === 'Float' && valueAST.kind !== 'Number' || type.name === 'Int' && (valueAST.kind !== 'Number' || (valueAST.value | 0) !== valueAST.value)) {
return [[valueAST, 'Expected value of type "' + type + '".']];
}
// Validate enums and custom scalars.
if (type instanceof _graphql.GraphQLEnumType || type instanceof _graphql.GraphQLScalarType) {
if (valueAST.kind !== 'String' && valueAST.kind !== 'Number' && valueAST.kind !== 'Boolean' && valueAST.kind !== 'Null' || isNullish(type.parseValue(valueAST.value))) {
return [[valueAST, 'Expected value of type "' + type + '".']];
}
}
return [];
}
// Give a parent text, an AST node with location, and a message, produces a
// CodeMirror annotation object.
function lintError(editor, node, message) {
return {
message: message,
severity: 'error',
type: 'validation',
from: editor.posFromIndex(node.start),
to: editor.posFromIndex(node.end)
};
}
function isNullish(value) {
return value === null || value === undefined || value !== value;
}
function mapCat(array, mapper) {
return Array.prototype.concat.apply([], array.map(mapper));
}
},{"../utils/jsonParse":35,"codemirror":55,"graphql":144}],42:[function(require,module,exports){
'use strict';
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _onlineParser = require('../utils/onlineParser');
var _onlineParser2 = _interopRequireDefault(_onlineParser);
var _RuleHelpers = require('../utils/RuleHelpers');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This mode defines JSON, but provides a data-laden parser state to enable
* better code intelligence.
*/
_codemirror2.default.defineMode('graphql-variables', function (config) {
var parser = (0, _onlineParser2.default)({
eatWhitespace: function eatWhitespace(stream) {
return stream.eatSpace();
},
LexRules: LexRules,
ParseRules: ParseRules,
editorConfig: { tabSize: config.tabSize }
});
return {
config: config,
startState: parser.startState,
token: parser.token,
indent: indent,
electricInput: /^\s*[}\]]/,
fold: 'brace',
closeBrackets: {
pairs: '[]{}""',
explode: '[]{}'
}
};
}); /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function indent(state, textAfter) {
var levels = state.levels;
// If there is no stack of levels, use the current level.
// Otherwise, use the top level, pre-emptively dedenting for close braces.
var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
return level * this.config.indentUnit;
}
/**
* The lexer rules. These are exactly as described by the spec.
*/
var LexRules = {
// All Punctuation used in JSON.
Punctuation: /^\[|]|\{|\}|:|,/,
// JSON Number.
Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
// JSON String.
String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,
// JSON literal keywords.
Keyword: /^true|false|null/
};
/**
* The parser rules for JSON.
*/
var ParseRules = {
Document: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Variable', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)(','))), (0, _RuleHelpers.p)('}')],
Variable: [namedKey('variable'), (0, _RuleHelpers.p)(':'), 'Value'],
Value: function Value(token) {
switch (token.kind) {
case 'Number':
return 'NumberValue';
case 'String':
return 'StringValue';
case 'Punctuation':
switch (token.value) {
case '[':
return 'ListValue';
case '{':
return 'ObjectValue';
}
return null;
case 'Keyword':
switch (token.value) {
case 'true':case 'false':
return 'BooleanValue';
case 'null':
return 'NullValue';
}
return null;
}
},
NumberValue: [(0, _RuleHelpers.t)('Number', 'number')],
StringValue: [(0, _RuleHelpers.t)('String', 'string')],
BooleanValue: [(0, _RuleHelpers.t)('Keyword', 'builtin')],
NullValue: [(0, _RuleHelpers.t)('Keyword', 'keyword')],
ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)(','))), (0, _RuleHelpers.p)(']')],
ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)(','))), (0, _RuleHelpers.p)('}')],
ObjectField: [namedKey('attribute'), (0, _RuleHelpers.p)(':'), 'Value']
};
// A namedKey Token which will decorate the state with a `name`
function namedKey(style) {
return {
style: style,
match: function match(token) {
return token.kind === 'String';
},
update: function update(state, token) {
state.name = token.value.slice(1, -1); // Remove quotes.
}
};
}
},{"../utils/RuleHelpers":27,"../utils/onlineParser":38,"codemirror":55}],43:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var noOptions = {};
var nonWS = /[^\s\u00a0]/;
var Pos = CodeMirror.Pos;
function firstNonWS(str) {
var found = str.search(nonWS);
return found == -1 ? 0 : found;
}
CodeMirror.commands.toggleComment = function(cm) {
cm.toggleComment();
};
CodeMirror.defineExtension("toggleComment", function(options) {
if (!options) options = noOptions;
var cm = this;
var minLine = Infinity, ranges = this.listSelections(), mode = null;
for (var i = ranges.length - 1; i >= 0; i--) {
var from = ranges[i].from(), to = ranges[i].to();
if (from.line >= minLine) continue;
if (to.line >= minLine) to = Pos(minLine, 0);
minLine = from.line;
if (mode == null) {
if (cm.uncomment(from, to, options)) mode = "un";
else { cm.lineComment(from, to, options); mode = "line"; }
} else if (mode == "un") {
cm.uncomment(from, to, options);
} else {
cm.lineComment(from, to, options);
}
}
});
// Rough heuristic to try and detect lines that are part of multi-line string
function probablyInsideString(cm, pos, line) {
return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"`]/.test(line)
}
CodeMirror.defineExtension("lineComment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var firstLine = self.getLine(from.line);
if (firstLine == null || probablyInsideString(self, from, firstLine)) return;
var commentString = options.lineComment || mode.lineComment;
if (!commentString) {
if (options.blockCommentStart || mode.blockCommentStart) {
options.fullLines = true;
self.blockComment(from, to, options);
}
return;
}
var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
var pad = options.padding == null ? " " : options.padding;
var blankLines = options.commentBlankLines || from.line == to.line;
self.operation(function() {
if (options.indent) {
var baseString = null;
for (var i = from.line; i < end; ++i) {
var line = self.getLine(i);
var whitespace = line.slice(0, firstNonWS(line));
if (baseString == null || baseString.length > whitespace.length) {
baseString = whitespace;
}
}
for (var i = from.line; i < end; ++i) {
var line = self.getLine(i), cut = baseString.length;
if (!blankLines && !nonWS.test(line)) continue;
if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
}
} else {
for (var i = from.line; i < end; ++i) {
if (blankLines || nonWS.test(self.getLine(i)))
self.replaceRange(commentString + pad, Pos(i, 0));
}
}
});
});
CodeMirror.defineExtension("blockComment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var startString = options.blockCommentStart || mode.blockCommentStart;
var endString = options.blockCommentEnd || mode.blockCommentEnd;
if (!startString || !endString) {
if ((options.lineComment || mode.lineComment) && options.fullLines != false)
self.lineComment(from, to, options);
return;
}
if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
var end = Math.min(to.line, self.lastLine());
if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
var pad = options.padding == null ? " " : options.padding;
if (from.line > end) return;
self.operation(function() {
if (options.fullLines != false) {
var lastLineHasText = nonWS.test(self.getLine(end));
self.replaceRange(pad + endString, Pos(end));
self.replaceRange(startString + pad, Pos(from.line, 0));
var lead = options.blockCommentLead || mode.blockCommentLead;
if (lead != null) for (var i = from.line + 1; i <= end; ++i)
if (i != end || lastLineHasText)
self.replaceRange(lead + pad, Pos(i, 0));
} else {
self.replaceRange(endString, to);
self.replaceRange(startString, from);
}
});
});
CodeMirror.defineExtension("uncomment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
// Try finding line comments
var lineString = options.lineComment || mode.lineComment, lines = [];
var pad = options.padding == null ? " " : options.padding, didSomething;
lineComment: {
if (!lineString) break lineComment;
for (var i = start; i <= end; ++i) {
var line = self.getLine(i);
var found = line.indexOf(lineString);
if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
if (found == -1 && nonWS.test(line)) break lineComment;
if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
lines.push(line);
}
self.operation(function() {
for (var i = start; i <= end; ++i) {
var line = lines[i - start];
var pos = line.indexOf(lineString), endPos = pos + lineString.length;
if (pos < 0) continue;
if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
didSomething = true;
self.replaceRange("", Pos(i, pos), Pos(i, endPos));
}
});
if (didSomething) return true;
}
// Try block comments
var startString = options.blockCommentStart || mode.blockCommentStart;
var endString = options.blockCommentEnd || mode.blockCommentEnd;
if (!startString || !endString) return false;
var lead = options.blockCommentLead || mode.blockCommentLead;
var startLine = self.getLine(start), open = startLine.indexOf(startString)
if (open == -1) return false
var endLine = end == start ? startLine : self.getLine(end)
var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
if (close == -1 && start != end) {
endLine = self.getLine(--end);
close = endLine.indexOf(endString);
}
if (close == -1 ||
!/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
!/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
return false;
// Avoid killing block comments completely outside the selection.
// Positions of the last startString before the start of the selection, and the first endString after it.
var lastStart = startLine.lastIndexOf(startString, from.ch);
var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
// Positions of the first endString after the end of the selection, and the last startString before it.
firstEnd = endLine.indexOf(endString, to.ch);
var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;
self.operation(function() {
self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
Pos(end, close + endString.length));
var openEnd = open + startString.length;
if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
self.replaceRange("", Pos(start, open), Pos(start, openEnd));
if (lead) for (var i = start + 1; i <= end; ++i) {
var line = self.getLine(i), found = line.indexOf(lead);
if (found == -1 || nonWS.test(line.slice(0, found))) continue;
var foundEnd = found + lead.length;
if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
}
});
return true;
});
});
},{"../../lib/codemirror":55}],44:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Open simple dialogs on top of an editor. Relies on dialog.css.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom)
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
else
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
if (typeof template == "string") {
dialog.innerHTML = template;
} else { // Assuming it's a detached DOM element.
dialog.appendChild(template);
}
return dialog;
}
function closeNotification(cm, newVal) {
if (cm.state.currentNotificationClose)
cm.state.currentNotificationClose();
cm.state.currentNotificationClose = newVal;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
if (!options) options = {};
closeNotification(this, null);
var dialog = dialogDiv(this, template, options.bottom);
var closed = false, me = this;
function close(newVal) {
if (typeof newVal == 'string') {
inp.value = newVal;
} else {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
if (options.onClose) options.onClose(dialog);
}
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
inp.focus();
if (options.value) {
inp.value = options.value;
if (options.selectValueOnOpen !== false) {
inp.select();
}
}
if (options.onInput)
CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
if (options.onKeyUp)
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
inp.blur();
CodeMirror.e_stop(e);
close();
}
if (e.keyCode == 13) callback(inp.value, e);
});
if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
button.focus();
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
/*
* openNotification
* Opens a notification, that can be closed with an optional timer
* (default 5000ms timer) and always closes on click.
*
* If a notification is opened while another is opened, it will close the
* currently opened one and open the new one immediately.
*/
CodeMirror.defineExtension("openNotification", function(template, options) {
closeNotification(this, close);
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, doneTimer;
var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
function close() {
if (closed) return;
closed = true;
clearTimeout(doneTimer);
dialog.parentNode.removeChild(dialog);
}
CodeMirror.on(dialog, 'click', function(e) {
CodeMirror.e_preventDefault(e);
close();
});
if (duration)
doneTimer = setTimeout(close, duration);
return close;
});
});
},{"../../lib/codemirror":55}],45:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var defaults = {
pairs: "()[]{}''\"\"",
triples: "",
explode: "[]{}"
};
var Pos = CodeMirror.Pos;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.removeKeyMap(keyMap);
cm.state.closeBrackets = null;
}
if (val) {
cm.state.closeBrackets = val;
cm.addKeyMap(keyMap);
}
});
function getOption(conf, name) {
if (name == "pairs" && typeof conf == "string") return conf;
if (typeof conf == "object" && conf[name] != null) return conf[name];
return defaults[name];
}
var bind = defaults.pairs + "`";
var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
for (var i = 0; i < bind.length; i++)
keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));
function handler(ch) {
return function(cm) { return handleChar(cm, ch); };
}
function getConfig(cm) {
var deflt = cm.state.closeBrackets;
if (!deflt || deflt.override) return deflt;
var mode = cm.getModeAt(cm.getCursor());
return mode.closeBrackets || deflt;
}
function handleBackspace(cm) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
for (var i = ranges.length - 1; i >= 0; i--) {
var cur = ranges[i].head;
cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
}
}
function handleEnter(cm) {
var conf = getConfig(cm);
var explode = conf && getOption(conf, "explode");
if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
cm.operation(function() {
cm.replaceSelection("\n\n", null);
cm.execCommand("goCharLeft");
ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var line = ranges[i].head.line;
cm.indentLine(line, null, true);
cm.indentLine(line + 1, null, true);
}
});
}
function contractSelection(sel) {
var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
}
function handleChar(cm, ch) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var pos = pairs.indexOf(ch);
if (pos == -1) return CodeMirror.Pass;
var triples = getOption(conf, "triples");
var identical = pairs.charAt(pos + 1) == ch;
var ranges = cm.listSelections();
var opening = pos % 2 == 0;
var type;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
if (opening && !range.empty()) {
curType = "surround";
} else if ((identical || !opening) && next == ch) {
if (identical && stringStartsAfter(cm, cur))
curType = "both";
else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
curType = "skipThree";
else
curType = "skip";
} else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
(cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
curType = "addFour";
} else if (identical) {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both";
else return CodeMirror.Pass;
} else if (opening && (cm.getLine(cur.line).length == cur.ch ||
isClosingBracket(next, pairs) ||
/\s/.test(next))) {
curType = "both";
} else {
return CodeMirror.Pass;
}
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
var right = pos % 2 ? ch : pairs.charAt(pos + 1);
cm.operation(function() {
if (type == "skip") {
cm.execCommand("goCharRight");
} else if (type == "skipThree") {
for (var i = 0; i < 3; i++)
cm.execCommand("goCharRight");
} else if (type == "surround") {
var sels = cm.getSelections();
for (var i = 0; i < sels.length; i++)
sels[i] = left + sels[i] + right;
cm.replaceSelections(sels, "around");
sels = cm.listSelections().slice();
for (var i = 0; i < sels.length; i++)
sels[i] = contractSelection(sels[i]);
cm.setSelections(sels);
} else if (type == "both") {
cm.replaceSelection(left + right, null);
cm.triggerElectric(left + right);
cm.execCommand("goCharLeft");
} else if (type == "addFour") {
cm.replaceSelection(left + left + left + left, "before");
cm.execCommand("goCharRight");
}
});
}
function isClosingBracket(ch, pairs) {
var pos = pairs.lastIndexOf(ch);
return pos > -1 && pos % 2 == 1;
}
function charsAround(cm, pos) {
var str = cm.getRange(Pos(pos.line, pos.ch - 1),
Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
// Project the token type that will exists after the given char is
// typed, and use it to determine whether it would cause the start
// of a string token.
function enteringString(cm, pos, ch) {
var line = cm.getLine(pos.line);
var token = cm.getTokenAt(pos);
if (/\bstring2?\b/.test(token.type)) return false;
var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
stream.pos = stream.start = token.start;
for (;;) {
var type1 = cm.getMode().token(stream, token.state);
if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
stream.start = stream.pos;
}
}
function stringStartsAfter(cm, pos) {
var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
return /\bstring/.test(token.type) && token.start == pos.ch
}
});
},{"../../lib/codemirror":55}],46:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
(document.documentMode == null || document.documentMode < 8);
var Pos = CodeMirror.Pos;
var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
function findMatchingBracket(cm, where, strict, config) {
var line = cm.getLineHandle(where.line), pos = where.ch - 1;
var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
if (!match) return null;
var dir = match.charAt(1) == ">" ? 1 : -1;
if (strict && (dir > 0) != (pos == where.ch)) return null;
var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
if (found == null) return null;
return {from: Pos(where.line, pos), to: found && found.pos,
match: found && found.ch == match.charAt(0), forward: dir > 0};
}
// bracketRegex is used to specify which type of bracket to scan
// should be a regexp, e.g. /[[\]]/
//
// Note: If "where" is on an open bracket, then this bracket is ignored.
//
// Returns false when no bracket was found, null when it reached
// maxScanLines and gave up
function scanForBracket(cm, where, dir, style, config) {
var maxScanLen = (config && config.maxScanLineLength) || 10000;
var maxScanLines = (config && config.maxScanLines) || 1000;
var stack = [];
var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
: Math.max(cm.firstLine() - 1, where.line - maxScanLines);
for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
var line = cm.getLine(lineNo);
if (!line) continue;
var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
if (line.length > maxScanLen) continue;
if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
for (; pos != end; pos += dir) {
var ch = line.charAt(pos);
if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
var match = matching[ch];
if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
else stack.pop();
}
}
}
return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
}
function matchBrackets(cm, autoclear, config) {
// Disable brace matching in long lines, since it'll cause hugely slow updates
var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
var marks = [], ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
}
}
if (marks.length) {
// Kludge to work around the IE bug from issue #1193, where text
// input stops going to the textare whever this fires.
if (ie_lt8 && cm.state.focused) cm.focus();
var clear = function() {
cm.operation(function() {
for (var i = 0; i < marks.length; i++) marks[i].clear();
});
};
if (autoclear) setTimeout(clear, 800);
else return clear;
}
}
var currentlyHighlighted = null;
function doMatchBrackets(cm) {
cm.operation(function() {
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
});
}
CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("cursorActivity", doMatchBrackets);
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
}
if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {};
cm.on("cursorActivity", doMatchBrackets);
}
});
CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
return findMatchingBracket(this, pos, strict, config);
});
CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
return scanForBracket(this, pos, dir, style, config);
});
});
},{"../../lib/codemirror":55}],47:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("fold", "brace", function(cm, start) {
var line = start.line, lineText = cm.getLine(line);
var tokenType;
function findOpening(openCh) {
for (var at = start.ch, pass = 0;;) {
var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
if (found == -1) {
if (pass == 1) break;
pass = 1;
at = lineText.length;
continue;
}
if (pass == 1 && found < start.ch) break;
tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
if (!/^(comment|string)/.test(tokenType)) return found + 1;
at = found - 1;
}
}
var startToken = "{", endToken = "}", startCh = findOpening("{");
if (startCh == null) {
startToken = "[", endToken = "]";
startCh = findOpening("[");
}
if (startCh == null) return;
var count = 1, lastLine = cm.lastLine(), end, endCh;
outer: for (var i = line; i <= lastLine; ++i) {
var text = cm.getLine(i), pos = i == line ? startCh : 0;
for (;;) {
var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
if (nextOpen < 0) nextOpen = text.length;
if (nextClose < 0) nextClose = text.length;
pos = Math.min(nextOpen, nextClose);
if (pos == text.length) break;
if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
if (pos == nextOpen) ++count;
else if (!--count) { end = i; endCh = pos; break outer; }
}
++pos;
}
}
if (end == null || line == end && endCh == startCh) return;
return {from: CodeMirror.Pos(line, startCh),
to: CodeMirror.Pos(end, endCh)};
});
CodeMirror.registerHelper("fold", "import", function(cm, start) {
function hasImport(line) {
if (line < cm.firstLine() || line > cm.lastLine()) return null;
var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
if (start.type != "keyword" || start.string != "import") return null;
// Now find closing semicolon, return its position
for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
var text = cm.getLine(i), semi = text.indexOf(";");
if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
}
}
var startLine = start.line, has = hasImport(startLine), prev;
if (!has || hasImport(startLine - 1) || ((prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1))
return null;
for (var end = has.end;;) {
var next = hasImport(end.line + 1);
if (next == null) break;
end = next.end;
}
return {from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), to: end};
});
CodeMirror.registerHelper("fold", "include", function(cm, start) {
function hasInclude(line) {
if (line < cm.firstLine() || line > cm.lastLine()) return null;
var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
}
var startLine = start.line, has = hasInclude(startLine);
if (has == null || hasInclude(startLine - 1) != null) return null;
for (var end = startLine;;) {
var next = hasInclude(end + 1);
if (next == null) break;
++end;
}
return {from: CodeMirror.Pos(startLine, has + 1),
to: cm.clipPos(CodeMirror.Pos(end))};
});
});
},{"../../lib/codemirror":55}],48:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function doFold(cm, pos, options, force) {
if (options && options.call) {
var finder = options;
options = null;
} else {
var finder = getOption(cm, options, "rangeFinder");
}
if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
var minSize = getOption(cm, options, "minFoldSize");
function getRange(allowFolded) {
var range = finder(cm, pos);
if (!range || range.to.line - range.from.line < minSize) return null;
var marks = cm.findMarksAt(range.from);
for (var i = 0; i < marks.length; ++i) {
if (marks[i].__isFold && force !== "fold") {
if (!allowFolded) return null;
range.cleared = true;
marks[i].clear();
}
}
return range;
}
var range = getRange(true);
if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
pos = CodeMirror.Pos(pos.line - 1, 0);
range = getRange(false);
}
if (!range || range.cleared || force === "unfold") return;
var myWidget = makeWidget(cm, options);
CodeMirror.on(myWidget, "mousedown", function(e) {
myRange.clear();
CodeMirror.e_preventDefault(e);
});
var myRange = cm.markText(range.from, range.to, {
replacedWith: myWidget,
clearOnEnter: getOption(cm, options, "clearOnEnter"),
__isFold: true
});
myRange.on("clear", function(from, to) {
CodeMirror.signal(cm, "unfold", cm, from, to);
});
CodeMirror.signal(cm, "fold", cm, range.from, range.to);
}
function makeWidget(cm, options) {
var widget = getOption(cm, options, "widget");
if (typeof widget == "string") {
var text = document.createTextNode(widget);
widget = document.createElement("span");
widget.appendChild(text);
widget.className = "CodeMirror-foldmarker";
}
return widget;
}
// Clumsy backwards-compatible interface
CodeMirror.newFoldFunction = function(rangeFinder, widget) {
return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
};
// New-style interface
CodeMirror.defineExtension("foldCode", function(pos, options, force) {
doFold(this, pos, options, force);
});
CodeMirror.defineExtension("isFolded", function(pos) {
var marks = this.findMarksAt(pos);
for (var i = 0; i < marks.length; ++i)
if (marks[i].__isFold) return true;
});
CodeMirror.commands.toggleFold = function(cm) {
cm.foldCode(cm.getCursor());
};
CodeMirror.commands.fold = function(cm) {
cm.foldCode(cm.getCursor(), null, "fold");
};
CodeMirror.commands.unfold = function(cm) {
cm.foldCode(cm.getCursor(), null, "unfold");
};
CodeMirror.commands.foldAll = function(cm) {
cm.operation(function() {
for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
});
};
CodeMirror.commands.unfoldAll = function(cm) {
cm.operation(function() {
for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
});
};
CodeMirror.registerHelper("fold", "combine", function() {
var funcs = Array.prototype.slice.call(arguments, 0);
return function(cm, start) {
for (var i = 0; i < funcs.length; ++i) {
var found = funcs[i](cm, start);
if (found) return found;
}
};
});
CodeMirror.registerHelper("fold", "auto", function(cm, start) {
var helpers = cm.getHelpers(start, "fold");
for (var i = 0; i < helpers.length; i++) {
var cur = helpers[i](cm, start);
if (cur) return cur;
}
});
var defaultOptions = {
rangeFinder: CodeMirror.fold.auto,
widget: "\u2194",
minFoldSize: 0,
scanUp: false,
clearOnEnter: true
};
CodeMirror.defineOption("foldOptions", null);
function getOption(cm, options, name) {
if (options && options[name] !== undefined)
return options[name];
var editorOptions = cm.options.foldOptions;
if (editorOptions && editorOptions[name] !== undefined)
return editorOptions[name];
return defaultOptions[name];
}
CodeMirror.defineExtension("foldOption", function(options, name) {
return getOption(this, options, name);
});
});
},{"../../lib/codemirror":55}],49:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./foldcode"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./foldcode"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.clearGutter(cm.state.foldGutter.options.gutter);
cm.state.foldGutter = null;
cm.off("gutterClick", onGutterClick);
cm.off("change", onChange);
cm.off("viewportChange", onViewportChange);
cm.off("fold", onFold);
cm.off("unfold", onFold);
cm.off("swapDoc", onChange);
}
if (val) {
cm.state.foldGutter = new State(parseOptions(val));
updateInViewport(cm);
cm.on("gutterClick", onGutterClick);
cm.on("change", onChange);
cm.on("viewportChange", onViewportChange);
cm.on("fold", onFold);
cm.on("unfold", onFold);
cm.on("swapDoc", onChange);
}
});
var Pos = CodeMirror.Pos;
function State(options) {
this.options = options;
this.from = this.to = 0;
}
function parseOptions(opts) {
if (opts === true) opts = {};
if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
return opts;
}
function isFolded(cm, line) {
var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));
for (var i = 0; i < marks.length; ++i)
if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
}
function marker(spec) {
if (typeof spec == "string") {
var elt = document.createElement("div");
elt.className = spec + " CodeMirror-guttermarker-subtle";
return elt;
} else {
return spec.cloneNode(true);
}
}
function updateFoldInfo(cm, from, to) {
var opts = cm.state.foldGutter.options, cur = from;
var minSize = cm.foldOption(opts, "minFoldSize");
var func = cm.foldOption(opts, "rangeFinder");
cm.eachLine(from, to, function(line) {
var mark = null;
if (isFolded(cm, cur)) {
mark = marker(opts.indicatorFolded);
} else {
var pos = Pos(cur, 0);
var range = func && func(cm, pos);
if (range && range.to.line - range.from.line >= minSize)
mark = marker(opts.indicatorOpen);
}
cm.setGutterMarker(line, opts.gutter, mark);
++cur;
});
}
function updateInViewport(cm) {
var vp = cm.getViewport(), state = cm.state.foldGutter;
if (!state) return;
cm.operation(function() {
updateFoldInfo(cm, vp.from, vp.to);
});
state.from = vp.from; state.to = vp.to;
}
function onGutterClick(cm, line, gutter) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
if (gutter != opts.gutter) return;
var folded = isFolded(cm, line);
if (folded) folded.clear();
else cm.foldCode(Pos(line, 0), opts.rangeFinder);
}
function onChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
state.from = state.to = 0;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
}
function onViewportChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() {
var vp = cm.getViewport();
if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
updateInViewport(cm);
} else {
cm.operation(function() {
if (vp.from < state.from) {
updateFoldInfo(cm, vp.from, state.from);
state.from = vp.from;
}
if (vp.to > state.to) {
updateFoldInfo(cm, state.to, vp.to);
state.to = vp.to;
}
});
}
}, opts.updateViewportTimeSpan || 400);
}
function onFold(cm, from) {
var state = cm.state.foldGutter;
if (!state) return;
var line = from.line;
if (line >= state.from && line < state.to)
updateFoldInfo(cm, line, line + 1);
}
});
},{"../../lib/codemirror":55,"./foldcode":48}],50:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var HINT_ELEMENT_CLASS = "CodeMirror-hint";
var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
// This is the old interface, kept around for now to stay
// backwards-compatible.
CodeMirror.showHint = function(cm, getHints, options) {
if (!getHints) return cm.showHint(options);
if (options && options.async) getHints.async = true;
var newOpts = {hint: getHints};
if (options) for (var prop in options) newOpts[prop] = options[prop];
return cm.showHint(newOpts);
};
CodeMirror.defineExtension("showHint", function(options) {
options = parseOptions(this, this.getCursor("start"), options);
var selections = this.listSelections()
if (selections.length > 1) return;
// By default, don't allow completion when something is selected.
// A hint function can have a `supportsSelection` property to
// indicate that it can handle selections.
if (this.somethingSelected()) {
if (!options.hint.supportsSelection) return;
// Don't try with cross-line selections
for (var i = 0; i < selections.length; i++)
if (selections[i].head.line != selections[i].anchor.line) return;
}
if (this.state.completionActive) this.state.completionActive.close();
var completion = this.state.completionActive = new Completion(this, options);
if (!completion.options.hint) return;
CodeMirror.signal(this, "startCompletion", this);
completion.update(true);
});
function Completion(cm, options) {
this.cm = cm;
this.options = options;
this.widget = null;
this.debounce = 0;
this.tick = 0;
this.startPos = this.cm.getCursor("start");
this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
var self = this;
cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
}
var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
return setTimeout(fn, 1000/60);
};
var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
Completion.prototype = {
close: function() {
if (!this.active()) return;
this.cm.state.completionActive = null;
this.tick = null;
this.cm.off("cursorActivity", this.activityFunc);
if (this.widget && this.data) CodeMirror.signal(this.data, "close");
if (this.widget) this.widget.close();
CodeMirror.signal(this.cm, "endCompletion", this.cm);
},
active: function() {
return this.cm.state.completionActive == this;
},
pick: function(data, i) {
var completion = data.list[i];
if (completion.hint) completion.hint(this.cm, data, completion);
else this.cm.replaceRange(getText(completion), completion.from || data.from,
completion.to || data.to, "complete");
CodeMirror.signal(data, "pick", completion);
this.close();
},
cursorActivity: function() {
if (this.debounce) {
cancelAnimationFrame(this.debounce);
this.debounce = 0;
}
var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
(pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
this.close();
} else {
var self = this;
this.debounce = requestAnimationFrame(function() {self.update();});
if (this.widget) this.widget.disable();
}
},
update: function(first) {
if (this.tick == null) return
var self = this, myTick = ++this.tick
fetchHints(this.options.hint, this.cm, this.options, function(data) {
if (self.tick == myTick) self.finishUpdate(data, first)
})
},
finishUpdate: function(data, first) {
if (this.data) CodeMirror.signal(this.data, "update");
var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
if (this.widget) this.widget.close();
if (data && this.data && isNewCompletion(this.data, data)) return;
this.data = data;
if (data && data.list.length) {
if (picked && data.list.length == 1) {
this.pick(data, 0);
} else {
this.widget = new Widget(this, data);
CodeMirror.signal(data, "shown");
}
}
}
};
function isNewCompletion(old, nw) {
var moved = CodeMirror.cmpPos(nw.from, old.from)
return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch
}
function parseOptions(cm, pos, options) {
var editor = cm.options.hintOptions;
var out = {};
for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
if (editor) for (var prop in editor)
if (editor[prop] !== undefined) out[prop] = editor[prop];
if (options) for (var prop in options)
if (options[prop] !== undefined) out[prop] = options[prop];
if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
return out;
}
function getText(completion) {
if (typeof completion == "string") return completion;
else return completion.text;
}
function buildKeyMap(completion, handle) {
var baseMap = {
Up: function() {handle.moveFocus(-1);},
Down: function() {handle.moveFocus(1);},
PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
Home: function() {handle.setFocus(0);},
End: function() {handle.setFocus(handle.length - 1);},
Enter: handle.pick,
Tab: handle.pick,
Esc: handle.close
};
var custom = completion.options.customKeys;
var ourMap = custom ? {} : baseMap;
function addBinding(key, val) {
var bound;
if (typeof val != "string")
bound = function(cm) { return val(cm, handle); };
// This mechanism is deprecated
else if (baseMap.hasOwnProperty(val))
bound = baseMap[val];
else
bound = val;
ourMap[key] = bound;
}
if (custom)
for (var key in custom) if (custom.hasOwnProperty(key))
addBinding(key, custom[key]);
var extra = completion.options.extraKeys;
if (extra)
for (var key in extra) if (extra.hasOwnProperty(key))
addBinding(key, extra[key]);
return ourMap;
}
function getHintElement(hintsElement, el) {
while (el && el != hintsElement) {
if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
el = el.parentNode;
}
}
function Widget(completion, data) {
this.completion = completion;
this.data = data;
this.picked = false;
var widget = this, cm = completion.cm;
var hints = this.hints = document.createElement("ul");
hints.className = "CodeMirror-hints";
this.selectedHint = data.selectedHint || 0;
var completions = data.list;
for (var i = 0; i < completions.length; ++i) {
var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
if (cur.className != null) className = cur.className + " " + className;
elt.className = className;
if (cur.render) cur.render(elt, data, cur);
else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
elt.hintId = i;
}
var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
var left = pos.left, top = pos.bottom, below = true;
hints.style.left = left + "px";
hints.style.top = top + "px";
// If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
(completion.options.container || document.body).appendChild(hints);
var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
var scrolls = hints.scrollHeight > hints.clientHeight + 1
var startScroll = cm.getScrollInfo();
if (overlapY > 0) {
var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
if (curTop - height > 0) { // Fits above cursor
hints.style.top = (top = pos.top - height) + "px";
below = false;
} else if (height > winH) {
hints.style.height = (winH - 5) + "px";
hints.style.top = (top = pos.bottom - box.top) + "px";
var cursor = cm.getCursor();
if (data.from.ch != cursor.ch) {
pos = cm.cursorCoords(cursor);
hints.style.left = (left = pos.left) + "px";
box = hints.getBoundingClientRect();
}
}
}
var overlapX = box.right - winW;
if (overlapX > 0) {
if (box.right - box.left > winW) {
hints.style.width = (winW - 5) + "px";
overlapX -= (box.right - box.left) - winW;
}
hints.style.left = (left = pos.left - overlapX) + "px";
}
if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
node.style.paddingRight = cm.display.nativeBarWidth + "px"
cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
setFocus: function(n) { widget.changeActive(n); },
menuSize: function() { return widget.screenAmount(); },
length: completions.length,
close: function() { completion.close(); },
pick: function() { widget.pick(); },
data: data
}));
if (completion.options.closeOnUnfocus) {
var closingOnBlur;
cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
}
cm.on("scroll", this.onScroll = function() {
var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
var newTop = top + startScroll.top - curScroll.top;
var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
if (!below) point += hints.offsetHeight;
if (point <= editor.top || point >= editor.bottom) return completion.close();
hints.style.top = newTop + "px";
hints.style.left = (left + startScroll.left - curScroll.left) + "px";
});
CodeMirror.on(hints, "dblclick", function(e) {
var t = getHintElement(hints, e.target || e.srcElement);
if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
});
CodeMirror.on(hints, "click", function(e) {
var t = getHintElement(hints, e.target || e.srcElement);
if (t && t.hintId != null) {
widget.changeActive(t.hintId);
if (completion.options.completeOnSingleClick) widget.pick();
}
});
CodeMirror.on(hints, "mousedown", function() {
setTimeout(function(){cm.focus();}, 20);
});
CodeMirror.signal(data, "select", completions[0], hints.firstChild);
return true;
}
Widget.prototype = {
close: function() {
if (this.completion.widget != this) return;
this.completion.widget = null;
this.hints.parentNode.removeChild(this.hints);
this.completion.cm.removeKeyMap(this.keyMap);
var cm = this.completion.cm;
if (this.completion.options.closeOnUnfocus) {
cm.off("blur", this.onBlur);
cm.off("focus", this.onFocus);
}
cm.off("scroll", this.onScroll);
},
disable: function() {
this.completion.cm.removeKeyMap(this.keyMap);
var widget = this;
this.keyMap = {Enter: function() { widget.picked = true; }};
this.completion.cm.addKeyMap(this.keyMap);
},
pick: function() {
this.completion.pick(this.data, this.selectedHint);
},
changeActive: function(i, avoidWrap) {
if (i >= this.data.list.length)
i = avoidWrap ? this.data.list.length - 1 : 0;
else if (i < 0)
i = avoidWrap ? 0 : this.data.list.length - 1;
if (this.selectedHint == i) return;
var node = this.hints.childNodes[this.selectedHint];
node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
node = this.hints.childNodes[this.selectedHint = i];
node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
if (node.offsetTop < this.hints.scrollTop)
this.hints.scrollTop = node.offsetTop - 3;
else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
},
screenAmount: function() {
return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
}
};
function applicableHelpers(cm, helpers) {
if (!cm.somethingSelected()) return helpers
var result = []
for (var i = 0; i < helpers.length; i++)
if (helpers[i].supportsSelection) result.push(helpers[i])
return result
}
function fetchHints(hint, cm, options, callback) {
if (hint.async) {
hint(cm, callback, options)
} else {
var result = hint(cm, options)
if (result && result.then) result.then(callback)
else callback(result)
}
}
function resolveAutoHints(cm, pos) {
var helpers = cm.getHelpers(pos, "hint"), words
if (helpers.length) {
var resolved = function(cm, callback, options) {
var app = applicableHelpers(cm, helpers);
function run(i) {
if (i == app.length) return callback(null)
fetchHints(app[i], cm, options, function(result) {
if (result && result.list.length > 0) callback(result)
else run(i + 1)
})
}
run(0)
}
resolved.async = true
resolved.supportsSelection = true
return resolved
} else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
} else if (CodeMirror.hint.anyword) {
return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
} else {
return function() {}
}
}
CodeMirror.registerHelper("hint", "auto", {
resolve: resolveAutoHints
});
CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var to = CodeMirror.Pos(cur.line, token.end);
if (token.string && /\w/.test(token.string[token.string.length - 1])) {
var term = token.string, from = CodeMirror.Pos(cur.line, token.start);
} else {
var term = "", from = to;
}
var found = [];
for (var i = 0; i < options.words.length; i++) {
var word = options.words[i];
if (word.slice(0, term.length) == term)
found.push(word);
}
if (found.length) return {list: found, from: from, to: to};
});
CodeMirror.commands.autocomplete = CodeMirror.showHint;
var defaultOptions = {
hint: CodeMirror.hint.auto,
completeSingle: true,
alignWithWord: true,
closeCharacters: /[\s()\[\]{};:>,]/,
closeOnUnfocus: true,
completeOnSingleClick: true,
container: null,
customKeys: null,
extraKeys: null
};
CodeMirror.defineOption("hintOptions", null);
});
},{"../../lib/codemirror":55}],51:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var GUTTER_ID = "CodeMirror-lint-markers";
function showTooltip(e, content) {
var tt = document.createElement("div");
tt.className = "CodeMirror-lint-tooltip";
tt.appendChild(content.cloneNode(true));
document.body.appendChild(tt);
function position(e) {
if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
tt.style.left = (e.clientX + 5) + "px";
}
CodeMirror.on(document, "mousemove", position);
position(e);
if (tt.style.opacity != null) tt.style.opacity = 1;
return tt;
}
function rm(elt) {
if (elt.parentNode) elt.parentNode.removeChild(elt);
}
function hideTooltip(tt) {
if (!tt.parentNode) return;
if (tt.style.opacity == null) rm(tt);
tt.style.opacity = 0;
setTimeout(function() { rm(tt); }, 600);
}
function showTooltipFor(e, content, node) {
var tooltip = showTooltip(e, content);
function hide() {
CodeMirror.off(node, "mouseout", hide);
if (tooltip) { hideTooltip(tooltip); tooltip = null; }
}
var poll = setInterval(function() {
if (tooltip) for (var n = node;; n = n.parentNode) {
if (n && n.nodeType == 11) n = n.host;
if (n == document.body) return;
if (!n) { hide(); break; }
}
if (!tooltip) return clearInterval(poll);
}, 400);
CodeMirror.on(node, "mouseout", hide);
}
function LintState(cm, options, hasGutter) {
this.marked = [];
this.options = options;
this.timeout = null;
this.hasGutter = hasGutter;
this.onMouseOver = function(e) { onMouseOver(cm, e); };
this.waitingFor = 0
}
function parseOptions(_cm, options) {
if (options instanceof Function) return {getAnnotations: options};
if (!options || options === true) options = {};
return options;
}
function clearMarks(cm) {
var state = cm.state.lint;
if (state.hasGutter) cm.clearGutter(GUTTER_ID);
for (var i = 0; i < state.marked.length; ++i)
state.marked[i].clear();
state.marked.length = 0;
}
function makeMarker(labels, severity, multiple, tooltips) {
var marker = document.createElement("div"), inner = marker;
marker.className = "CodeMirror-lint-marker-" + severity;
if (multiple) {
inner = marker.appendChild(document.createElement("div"));
inner.className = "CodeMirror-lint-marker-multiple";
}
if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
showTooltipFor(e, labels, inner);
});
return marker;
}
function getMaxSeverity(a, b) {
if (a == "error") return a;
else return b;
}
function groupByLine(annotations) {
var lines = [];
for (var i = 0; i < annotations.length; ++i) {
var ann = annotations[i], line = ann.from.line;
(lines[line] || (lines[line] = [])).push(ann);
}
return lines;
}
function annotationTooltip(ann) {
var severity = ann.severity;
if (!severity) severity = "error";
var tip = document.createElement("div");
tip.className = "CodeMirror-lint-message-" + severity;
tip.appendChild(document.createTextNode(ann.message));
return tip;
}
function lintAsync(cm, getAnnotations, passOptions) {
var state = cm.state.lint
var id = ++state.waitingFor
function abort() {
id = -1
cm.off("change", abort)
}
cm.on("change", abort)
getAnnotations(cm.getValue(), function(annotations, arg2) {
cm.off("change", abort)
if (state.waitingFor != id) return
if (arg2 && annotations instanceof CodeMirror) annotations = arg2
updateLinting(cm, annotations)
}, passOptions, cm);
}
function startLinting(cm) {
var state = cm.state.lint, options = state.options;
var passOptions = options.options || options; // Support deprecated passing of `options` property in options
var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
if (!getAnnotations) return;
if (options.async || getAnnotations.async) {
lintAsync(cm, getAnnotations, passOptions)
} else {
updateLinting(cm, getAnnotations(cm.getValue(), passOptions, cm));
}
}
function updateLinting(cm, annotationsNotSorted) {
clearMarks(cm);
var state = cm.state.lint, options = state.options;
var annotations = groupByLine(annotationsNotSorted);
for (var line = 0; line < annotations.length; ++line) {
var anns = annotations[line];
if (!anns) continue;
var maxSeverity = null;
var tipLabel = state.hasGutter && document.createDocumentFragment();
for (var i = 0; i < anns.length; ++i) {
var ann = anns[i];
var severity = ann.severity;
if (!severity) severity = "error";
maxSeverity = getMaxSeverity(maxSeverity, severity);
if (options.formatAnnotation) ann = options.formatAnnotation(ann);
if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
className: "CodeMirror-lint-mark-" + severity,
__annotation: ann
}));
}
if (state.hasGutter)
cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
state.options.tooltips));
}
if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
}
function onChange(cm) {
var state = cm.state.lint;
if (!state) return;
clearTimeout(state.timeout);
state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
}
function popupTooltips(annotations, e) {
var target = e.target || e.srcElement;
var tooltip = document.createDocumentFragment();
for (var i = 0; i < annotations.length; i++) {
var ann = annotations[i];
tooltip.appendChild(annotationTooltip(ann));
}
showTooltipFor(e, tooltip, target);
}
function onMouseOver(cm, e) {
var target = e.target || e.srcElement;
if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
var annotations = [];
for (var i = 0; i < spans.length; ++i) {
var ann = spans[i].__annotation;
if (ann) annotations.push(ann);
}
if (annotations.length) popupTooltips(annotations, e);
}
CodeMirror.defineOption("lint", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearMarks(cm);
if (cm.state.lint.options.lintOnChange !== false)
cm.off("change", onChange);
CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
clearTimeout(cm.state.lint.timeout);
delete cm.state.lint;
}
if (val) {
var gutters = cm.getOption("gutters"), hasLintGutter = false;
for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
if (state.options.lintOnChange !== false)
cm.on("change", onChange);
if (state.options.tooltips != false && state.options.tooltips != "gutter")
CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
startLinting(cm);
}
});
CodeMirror.defineExtension("performLint", function() {
if (this.state.lint) startLinting(this);
});
});
},{"../../lib/codemirror":55}],52:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Define search commands. Depends on dialog.js or another
// implementation of the openDialog method.
// Replace works a little oddly -- it will do the replace on the next
// Ctrl-G (or whatever is bound to findNext) press. You prevent a
// replace by making sure the match is no longer selected when hitting
// Ctrl-G.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function searchOverlay(query, caseInsensitive) {
if (typeof query == "string")
query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
else if (!query.global)
query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
return {token: function(stream) {
query.lastIndex = stream.pos;
var match = query.exec(stream.string);
if (match && match.index == stream.pos) {
stream.pos += match[0].length || 1;
return "searching";
} else if (match) {
stream.pos = match.index;
} else {
stream.skipToEnd();
}
}};
}
function SearchState() {
this.posFrom = this.posTo = this.lastQuery = this.query = null;
this.overlay = null;
}
function getSearchState(cm) {
return cm.state.search || (cm.state.search = new SearchState());
}
function queryCaseInsensitive(query) {
return typeof query == "string" && query == query.toLowerCase();
}
function getSearchCursor(cm, query, pos) {
// Heuristic: if the query string is all lowercase, do a case insensitive search.
return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
}
function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
cm.openDialog(text, onEnter, {
value: deflt,
selectValueOnOpen: true,
closeOnEnter: false,
onClose: function() { clearSearch(cm); },
onKeyDown: onKeyDown
});
}
function dialog(cm, text, shortText, deflt, f) {
if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
else f(prompt(shortText, deflt));
}
function confirmDialog(cm, text, shortText, fs) {
if (cm.openConfirm) cm.openConfirm(text, fs);
else if (confirm(shortText)) fs[0]();
}
function parseString(string) {
return string.replace(/\\(.)/g, function(_, ch) {
if (ch == "n") return "\n"
if (ch == "r") return "\r"
return ch
})
}
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
catch(e) {} // Not a regular expression after all, do a string search
} else {
query = parseString(query)
}
if (typeof query == "string" ? query == "" : query.test(""))
query = /x^/;
return query;
}
var queryDialog =
'Search: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
function startSearch(cm, state, query) {
state.queryText = query;
state.query = parseQuery(query);
cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
cm.addOverlay(state.overlay);
if (cm.showMatchesOnScrollbar) {
if (state.annotate) { state.annotate.clear(); state.annotate = null; }
state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
}
}
function doSearch(cm, rev, persistent, immediate) {
var state = getSearchState(cm);
if (state.query) return findNext(cm, rev);
var q = cm.getSelection() || state.lastQuery;
if (persistent && cm.openDialog) {
var hiding = null
var searchNext = function(query, event) {
CodeMirror.e_stop(event);
if (!query) return;
if (query != state.queryText) {
startSearch(cm, state, query);
state.posFrom = state.posTo = cm.getCursor();
}
if (hiding) hiding.style.opacity = 1
findNext(cm, event.shiftKey, function(_, to) {
var dialog
if (to.line < 3 && document.querySelector &&
(dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
(hiding = dialog).style.opacity = .4
})
};
persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
var keyName = CodeMirror.keyName(event)
var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
if (!cmd) cmd = cm.getOption('extraKeys')[keyName]
if (cmd == "findNext" || cmd == "findPrev" ||
cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
CodeMirror.e_stop(event);
startSearch(cm, getSearchState(cm), query);
cm.execCommand(cmd);
} else if (cmd == "find" || cmd == "findPersistent") {
CodeMirror.e_stop(event);
searchNext(query, event);
}
});
if (immediate && q) {
startSearch(cm, state, q);
findNext(cm, rev);
}
} else {
dialog(cm, queryDialog, "Search for:", q, function(query) {
if (query && !state.query) cm.operation(function() {
startSearch(cm, state, query);
state.posFrom = state.posTo = cm.getCursor();
findNext(cm, rev);
});
});
}
}
function findNext(cm, rev, callback) {cm.operation(function() {
var state = getSearchState(cm);
var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
if (!cursor.find(rev)) {
cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
if (!cursor.find(rev)) return;
}
cm.setSelection(cursor.from(), cursor.to());
cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
state.posFrom = cursor.from(); state.posTo = cursor.to();
if (callback) callback(cursor.from(), cursor.to())
});}
function clearSearch(cm) {cm.operation(function() {
var state = getSearchState(cm);
state.lastQuery = state.query;
if (!state.query) return;
state.query = state.queryText = null;
cm.removeOverlay(state.overlay);
if (state.annotate) { state.annotate.clear(); state.annotate = null; }
});}
var replaceQueryDialog =
' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
var replacementQueryDialog = 'With: <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>";
function replaceAll(cm, query, text) {
cm.operation(function() {
for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
if (typeof query != "string") {
var match = cm.getRange(cursor.from(), cursor.to()).match(query);
cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
} else cursor.replace(text);
}
});
}
function replace(cm, all) {
if (cm.getOption("readOnly")) return;
var query = cm.getSelection() || getSearchState(cm).lastQuery;
var dialogText = all ? "Replace all:" : "Replace:"
dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
if (!query) return;
query = parseQuery(query);
dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
text = parseString(text)
if (all) {
replaceAll(cm, query, text)
} else {
clearSearch(cm);
var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
var advance = function() {
var start = cursor.from(), match;
if (!(match = cursor.findNext())) {
cursor = getSearchCursor(cm, query);
if (!(match = cursor.findNext()) ||
(start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
}
cm.setSelection(cursor.from(), cursor.to());
cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
confirmDialog(cm, doReplaceConfirm, "Replace?",
[function() {doReplace(match);}, advance,
function() {replaceAll(cm, query, text)}]);
};
var doReplace = function(match) {
cursor.replace(typeof query == "string" ? text :
text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
advance();
};
advance();
}
});
});
}
CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
CodeMirror.commands.findNext = doSearch;
CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
CodeMirror.commands.clearSearch = clearSearch;
CodeMirror.commands.replace = replace;
CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
});
},{"../../lib/codemirror":55,"../dialog/dialog":44,"./searchcursor":53}],53:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function SearchCursor(doc, query, pos, caseFold) {
this.atOccurrence = false; this.doc = doc;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
for (;;) {
query.lastIndex = cutOff;
var newMatch = query.exec(line);
if (!newMatch) break;
match = newMatch;
start = match.index;
cutOff = match.index + (match[0].length || 1);
if (cutOff == line.length) break;
}
var matchLen = (match && match[0].length) || 0;
if (!matchLen) {
if (start == 0 && line.length == 0) {match = undefined;}
else if (start != doc.getLine(pos.line).length) {
matchLen++;
}
}
} else {
query.lastIndex = pos.ch;
var line = doc.getLine(pos.line), match = query.exec(line);
var matchLen = (match && match[0].length) || 0;
var start = match && match.index;
if (start + matchLen != line.length && !matchLen) matchLen = 1;
}
if (match && matchLen)
return {from: Pos(pos.line, start),
to: Pos(pos.line, start + matchLen),
match: match};
};
} else { // String query
var origQuery = query;
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1) {
if (!query.length) {
// Empty string would match anything and never progress, so
// we define it to match nothing instead.
this.matches = function() {};
} else {
this.matches = function(reverse, pos) {
if (reverse) {
var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
var match = line.lastIndexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match);
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
} else {
var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
var match = line.indexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match) + pos.ch;
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
}
};
}
} else {
var origTarget = origQuery.split("\n");
this.matches = function(reverse, pos) {
var last = target.length - 1;
if (reverse) {
if (pos.line - (target.length - 1) < doc.firstLine()) return;
if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
var to = Pos(pos.line, origTarget[last].length);
for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
if (target[i] != fold(doc.getLine(ln))) return;
var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
return {from: Pos(ln, cut), to: to};
} else {
if (pos.line + (target.length - 1) > doc.lastLine()) return;
var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
var from = Pos(pos.line, cut);
for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
if (target[i] != fold(doc.getLine(ln))) return;
if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
return {from: from, to: Pos(ln, origTarget[last].length)};
}
};
}
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = Pos(line, 0);
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
}
else {
var maxLine = this.doc.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = Pos(pos.line + 1, 0);
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText, origin) {
if (!this.atOccurrence) return;
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
// Maps a position in a case-folded line back to a position in the original line
// (compensating for codepoints increasing in number during folding)
function adjustPos(orig, folded, pos) {
if (orig.length == folded.length) return pos;
for (var pos1 = Math.min(pos, orig.length);;) {
var len1 = orig.slice(0, pos1).toLowerCase().length;
if (len1 < pos) ++pos1;
else if (len1 > pos) --pos1;
else return pos1;
}
}
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold);
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
var ranges = [];
var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
while (cur.findNext()) {
if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
ranges.push({anchor: cur.from(), head: cur.to()});
}
if (ranges.length)
this.setSelections(ranges, 0);
});
});
},{"../../lib/codemirror":55}],54:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var map = CodeMirror.keyMap.sublime = {fallthrough: "default"};
var cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
var ctrl = mac ? "Cmd-" : "Ctrl-";
// This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type;
for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
break;
}
}
}
return Pos(start.line, pos);
}
function moveSubword(cm, dir) {
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosSubword(cm.doc, range.head, dir);
else
return dir < 0 ? range.from() : range.to();
});
}
var goSubwordCombo = mac ? "Ctrl-" : "Alt-";
cmds[map[goSubwordCombo + "Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); };
cmds[map[goSubwordCombo + "Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); };
if (mac) map["Cmd-Left"] = "goLineStartSmart";
var scrollLineCombo = mac ? "Ctrl-Alt-" : "Ctrl-";
cmds[map[scrollLineCombo + "Up"] = "scrollLineUp"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
if (cm.getCursor().line >= visibleBottomLine)
cm.execCommand("goLineUp");
}
cm.scrollTo(null, info.top - cm.defaultTextHeight());
};
cmds[map[scrollLineCombo + "Down"] = "scrollLineDown"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
if (cm.getCursor().line <= visibleTopLine)
cm.execCommand("goLineDown");
}
cm.scrollTo(null, info.top + cm.defaultTextHeight());
};
cmds[map["Shift-" + ctrl + "L"] = "splitSelectionByLine"] = function(cm) {
var ranges = cm.listSelections(), lineRanges = [];
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
for (var line = from.line; line <= to.line; ++line)
if (!(to.line > from.line && line == to.line && to.ch == 0))
lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
head: line == to.line ? to : Pos(line)});
}
cm.setSelections(lineRanges, 0);
};
map["Shift-Tab"] = "indentLess";
cmds[map["Esc"] = "singleSelectionTop"] = function(cm) {
var range = cm.listSelections()[0];
cm.setSelection(range.anchor, range.head, {scroll: false});
};
cmds[map[ctrl + "L"] = "selectLine"] = function(cm) {
var ranges = cm.listSelections(), extended = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
extended.push({anchor: Pos(range.from().line, 0),
head: Pos(range.to().line + 1, 0)});
}
cm.setSelections(extended);
};
map["Shift-Ctrl-K"] = "deleteLine";
function insertLine(cm, above) {
if (cm.isReadOnly()) return CodeMirror.Pass
cm.operation(function() {
var len = cm.listSelections().length, newSelection = [], last = -1;
for (var i = 0; i < len; i++) {
var head = cm.listSelections()[i].head;
if (head.line <= last) continue;
var at = Pos(head.line + (above ? 0 : 1), 0);
cm.replaceRange("\n", at, null, "+insertLine");
cm.indentLine(at.line, null, true);
newSelection.push({head: at, anchor: at});
last = head.line + 1;
}
cm.setSelections(newSelection);
});
cm.execCommand("indentAuto");
}
cmds[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { return insertLine(cm, false); };
cmds[map["Shift-" + ctrl + "Enter"] = "insertLineBefore"] = function(cm) { return insertLine(cm, true); };
function wordAt(cm, pos) {
var start = pos.ch, end = start, line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
}
cmds[map[ctrl + "D"] = "selectNextOccurrence"] = function(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
cm.setSelection(word.from, word.to);
fullWord = true;
} else {
var text = cm.getRange(from, to);
var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
var cur = cm.getSearchCursor(query, to);
if (cur.findNext()) {
cm.addSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
if (cur.findNext())
cm.addSelection(cur.from(), cur.to());
}
}
if (fullWord)
cm.state.sublimeFindFullWord = cm.doc.sel;
};
var mirror = "(){}[]";
function selectBetweenBrackets(cm) {
var ranges = cm.listSelections(), newRanges = []
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
if (!opening) return false;
for (;;) {
var closing = cm.scanForBracket(pos, 1);
if (!closing) return false;
if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
newRanges.push({anchor: Pos(opening.pos.line, opening.pos.ch + 1),
head: closing.pos});
break;
}
pos = Pos(closing.pos.line, closing.pos.ch + 1);
}
}
cm.setSelections(newRanges);
return true;
}
cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) {
selectBetweenBrackets(cm) || cm.execCommand("selectAll");
};
cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) {
if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
};
cmds[map[ctrl + "M"] = "goToBracket"] = function(cm) {
cm.extendSelectionsBy(function(range) {
var next = cm.scanForBracket(range.head, 1);
if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
var prev = cm.scanForBracket(range.head, -1);
return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
});
};
var swapLineCombo = mac ? "Cmd-Ctrl-" : "Shift-Ctrl-";
cmds[map[swapLineCombo + "Up"] = "swapLineUp"] = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from().line - 1, to = range.to().line;
newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
head: Pos(range.head.line - 1, range.head.ch)});
if (range.to().ch == 0 && !range.empty()) --to;
if (from > at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = 0; i < linesToMove.length; i += 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
if (to > cm.lastLine())
cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
else
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.setSelections(newSels);
cm.scrollIntoView();
});
};
cmds[map[swapLineCombo + "Down"] = "swapLineDown"] = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
for (var i = ranges.length - 1; i >= 0; i--) {
var range = ranges[i], from = range.to().line + 1, to = range.from().line;
if (range.to().ch == 0 && !range.empty()) from--;
if (from < at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
if (from == cm.lastLine())
cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
else
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.scrollIntoView();
});
};
cmds[map[ctrl + "/"] = "toggleCommentIndented"] = function(cm) {
cm.toggleComment({ indent: true });
}
cmds[map[ctrl + "J"] = "joinLines"] = function(cm) {
var ranges = cm.listSelections(), joined = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from();
var start = from.line, end = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
end = ranges[++i].to().line;
joined.push({start: start, end: end, anchor: !range.empty() && from});
}
cm.operation(function() {
var offset = 0, ranges = [];
for (var i = 0; i < joined.length; i++) {
var obj = joined[i];
var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
for (var line = obj.start; line <= obj.end; line++) {
var actual = line - offset;
if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
if (actual < cm.lastLine()) {
cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
++offset;
}
}
ranges.push({anchor: anchor || head, head: head});
}
cm.setSelections(ranges, 0);
});
};
cmds[map["Shift-" + ctrl + "D"] = "duplicateLine"] = function(cm) {
cm.operation(function() {
var rangeCount = cm.listSelections().length;
for (var i = 0; i < rangeCount; i++) {
var range = cm.listSelections()[i];
if (range.empty())
cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
else
cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
}
cm.scrollIntoView();
});
};
if (!mac) map[ctrl + "T"] = "transposeChars";
function sortLines(cm, caseSensitive) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), toSort = [], selected;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) continue;
var from = range.from().line, to = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
to = ranges[++i].to().line;
if (!ranges[i].to().ch) to--;
toSort.push(from, to);
}
if (toSort.length) selected = true;
else toSort.push(cm.firstLine(), cm.lastLine());
cm.operation(function() {
var ranges = [];
for (var i = 0; i < toSort.length; i += 2) {
var from = toSort[i], to = toSort[i + 1];
var start = Pos(from, 0), end = Pos(to);
var lines = cm.getRange(start, end, false);
if (caseSensitive)
lines.sort();
else
lines.sort(function(a, b) {
var au = a.toUpperCase(), bu = b.toUpperCase();
if (au != bu) { a = au; b = bu; }
return a < b ? -1 : a == b ? 0 : 1;
});
cm.replaceRange(lines, start, end);
if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
}
if (selected) cm.setSelections(ranges, 0);
});
}
cmds[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); };
cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); };
cmds[map["F2"] = "nextBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
var current = marks.shift();
var found = current.find();
if (found) {
marks.push(current);
return cm.setSelection(found.from, found.to);
}
}
};
cmds[map["Shift-F2"] = "prevBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
marks.unshift(marks.pop());
var found = marks[marks.length - 1].find();
if (!found)
marks.pop();
else
return cm.setSelection(found.from, found.to);
}
};
cmds[map[ctrl + "F2"] = "toggleBookmark"] = function(cm) {
var ranges = cm.listSelections();
var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
var found = cm.findMarks(from, to);
for (var j = 0; j < found.length; j++) {
if (found[j].sublimeBookmark) {
found[j].clear();
for (var k = 0; k < marks.length; k++)
if (marks[k] == found[j])
marks.splice(k--, 1);
break;
}
}
if (j == found.length)
marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
}
};
cmds[map["Shift-" + ctrl + "F2"] = "clearBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
marks.length = 0;
};
cmds[map["Alt-F2"] = "selectBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks, ranges = [];
if (marks) for (var i = 0; i < marks.length; i++) {
var found = marks[i].find();
if (!found)
marks.splice(i--, 0);
else
ranges.push({anchor: found.from, head: found.to});
}
if (ranges.length)
cm.setSelections(ranges, 0);
};
map["Alt-Q"] = "wrapLines";
var cK = ctrl + "K ";
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
var ranges = cm.listSelections(), indices = [], replacements = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) { indices.push(i); replacements.push(""); }
else replacements.push(mod(cm.getRange(range.from(), range.to())));
}
cm.replaceSelections(replacements, "around", "case");
for (var i = indices.length - 1, at; i >= 0; i--) {
var range = ranges[indices[i]];
if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
var word = wordAt(cm, range.head);
at = word.from;
cm.replaceRange(mod(word.word), word.from, word.to);
}
});
}
map[cK + ctrl + "Backspace"] = "delLineLeft";
cmds[map["Backspace"] = "smartBackspace"] = function(cm) {
if (cm.somethingSelected()) return CodeMirror.Pass;
cm.operation(function() {
var cursors = cm.listSelections();
var indentUnit = cm.getOption("indentUnit");
for (var i = cursors.length - 1; i >= 0; i--) {
var cursor = cursors[i].head;
var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
// Delete by one character by default
var deletePos = cm.findPosH(cursor, -1, "char", false);
if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
var prevIndent = new Pos(cursor.line,
CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
// Smart delete only if we found a valid prevIndent location
if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
}
cm.replaceRange("", deletePos, cursor, "+delete");
}
});
};
cmds[map[cK + ctrl + "K"] = "delLineRight"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
cm.scrollIntoView();
});
};
cmds[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
cmds[map[cK + ctrl + "W"] = "deleteToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
cm.state.sublimeKilled = cm.getRange(from, to);
cm.replaceRange("", from, to);
}
};
cmds[map[cK + ctrl + "X"] = "swapWithSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
cm.setCursor(found);
}
};
cmds[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
map[cK + ctrl + "G"] = "clearBookmarks";
cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
var selectLinesCombo = mac ? "Ctrl-Shift-" : "Ctrl-Alt-";
cmds[map[selectLinesCombo + "Up"] = "selectLinesUpward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line > cm.firstLine())
cm.addSelection(Pos(range.head.line - 1, range.head.ch));
}
});
};
cmds[map[selectLinesCombo + "Down"] = "selectLinesDownward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line < cm.lastLine())
cm.addSelection(Pos(range.head.line + 1, range.head.ch));
}
});
};
function getTarget(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
from = word.from;
to = word.to;
}
return {from: from, to: to, query: cm.getRange(from, to), word: word};
}
function findAndGoTo(cm, forward) {
var target = getTarget(cm);
if (!target) return;
var query = target.query;
var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
if (forward ? cur.findNext() : cur.findPrevious()) {
cm.setSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
: cm.clipPos(Pos(cm.lastLine())));
if (forward ? cur.findNext() : cur.findPrevious())
cm.setSelection(cur.from(), cur.to());
else if (target.word)
cm.setSelection(target.from, target.to);
}
};
cmds[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); };
cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); };
cmds[map["Alt-F3"] = "findAllUnder"] = function(cm) {
var target = getTarget(cm);
if (!target) return;
var cur = cm.getSearchCursor(target.query);
var matches = [];
var primaryIndex = -1;
while (cur.findNext()) {
matches.push({anchor: cur.from(), head: cur.to()});
if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
primaryIndex++;
}
cm.setSelections(matches, primaryIndex);
};
map["Shift-" + ctrl + "["] = "fold";
map["Shift-" + ctrl + "]"] = "unfold";
map[cK + ctrl + "0"] = map[cK + ctrl + "J"] = "unfoldAll";
map[ctrl + "I"] = "findIncremental";
map["Shift-" + ctrl + "I"] = "findIncrementalReverse";
map[ctrl + "H"] = "replace";
map["F3"] = "findNext";
map["Shift-F3"] = "findPrev";
CodeMirror.normalizeKeyMap(map);
});
},{"../addon/edit/matchbrackets":46,"../addon/search/searchcursor":53,"../lib/codemirror":55}],55:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.CodeMirror = factory());
}(this, (function () { 'use strict';
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var userAgent = navigator.userAgent
var platform = navigator.platform
var gecko = /gecko\/\d/i.test(userAgent)
var ie_upto10 = /MSIE \d/.test(userAgent)
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
var ie = ie_upto10 || ie_11up
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1])
var webkit = /WebKit\//.test(userAgent)
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
var chrome = /Chrome\//.test(userAgent)
var presto = /Opera\//.test(userAgent)
var safari = /Apple Computer/.test(navigator.vendor)
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
var phantom = /PhantomJS/.test(userAgent)
var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.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
}
var range
if (document.createRange) { range = function(node, start, end, endNode) {
var r = document.createRange()
r.setEnd(endNode || node, end)
r.setStart(node, start)
return r
} }
else { range = function(node, start, end) {
var r = document.body.createTextRange()
try { r.moveToElementText(node.parentNode) }
catch(e) { return r }
r.collapse(true)
r.moveEnd("character", end)
r.moveStart("character", start)
return r
} }
function contains(parent, child) {
if (child.nodeType == 3) // Android browser always returns false when child is a textnode
{ child = child.parentNode }
if (parent.contains)
{ return parent.contains(child) }
do {
if (child.nodeType == 11) { child = child.host }
if (child == parent) { return true }
} while (child = child.parentNode)
}
function activeElt() {
// IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
// IE < 10 will throw when accessed while the page is loading or in an iframe.
// IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
var activeElement
try {
activeElement = document.activeElement
} catch(e) {
activeElement = document.body || null
}
while (activeElement && activeElement.root && activeElement.root.activeElement)
{ activeElement = activeElement.root.activeElement }
return activeElement
}
function addClass(node, cls) {
var current = node.className
if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
}
function joinClasses(a, b) {
var as = a.split(" ")
for (var i = 0; i < as.length; i++)
{ if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
return b
}
var selectInput = function(node) { node.select() }
if (ios) // Mobile Safari apparently has a bug where select() is broken.
{ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
else if (ie) // Suppress mysterious IE10 errors
{ selectInput = function(node) { try { node.select() } catch(_e) {} } }
function bind(f) {
var args = Array.prototype.slice.call(arguments, 1)
return function(){return f.apply(null, args)}
}
function copyObj(obj, target, overwrite) {
if (!target) { target = {} }
for (var prop in obj)
{ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
{ target[prop] = obj[prop] } }
return target
}
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countColumn(string, end, tabSize, startIndex, startValue) {
if (end == null) {
end = string.search(/[^\s\u00a0]/)
if (end == -1) { end = string.length }
}
for (var i = startIndex || 0, n = startValue || 0;;) {
var nextTab = string.indexOf("\t", i)
if (nextTab < 0 || nextTab >= end)
{ return n + (end - i) }
n += nextTab - i
n += tabSize - (n % tabSize)
i = nextTab + 1
}
}
function Delayed() {this.id = null}
Delayed.prototype.set = function(ms, f) {
clearTimeout(this.id)
this.id = setTimeout(f, ms)
}
function indexOf(array, elt) {
for (var i = 0; i < array.length; ++i)
{ if (array[i] == elt) { return i } }
return -1
}
// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerGap = 30
// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = {toString: function(){return "CodeMirror.Pass"}}
// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false};
var sel_mouse = {origin: "*mouse"};
var sel_move = {origin: "+move"};
// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
function findColumn(string, goal, tabSize) {
for (var pos = 0, col = 0;;) {
var nextTab = string.indexOf("\t", pos)
if (nextTab == -1) { nextTab = string.length }
var skipped = nextTab - pos
if (nextTab == string.length || col + skipped >= goal)
{ return pos + Math.min(skipped, goal - col) }
col += nextTab - pos
col += tabSize - (col % tabSize)
pos = nextTab + 1
if (col >= goal) { return pos }
}
}
var spaceStrs = [""]
function spaceStr(n) {
while (spaceStrs.length <= n)
{ spaceStrs.push(lst(spaceStrs) + " ") }
return spaceStrs[n]
}
function lst(arr) { return arr[arr.length-1] }
function map(array, f) {
var out = []
for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
return out
}
function insertSorted(array, value, score) {
var pos = 0, priority = score(value)
while (pos < array.length && score(array[pos]) <= priority) { pos++ }
array.splice(pos, 0, value)
}
function nothing() {}
function createObj(base, props) {
var inst
if (Object.create) {
inst = Object.create(base)
} else {
nothing.prototype = base
inst = new nothing()
}
if (props) { copyObj(props, inst) }
return inst
}
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
function isWordCharBasic(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
}
function isWordChar(ch, helper) {
if (!helper) { return isWordCharBasic(ch) }
if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
return helper.test(ch)
}
function isEmpty(obj) {
for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
return true
}
// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.
function Display(place, doc, input) {
var d = this
this.input = input
// Covers bottom-right square when both scrollbars are present.
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
d.scrollbarFiller.setAttribute("cm-not-content", "true")
// Covers bottom of gutter when coverGutterNextToScrollbar is on
// and h scrollbar is present.
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
d.gutterFiller.setAttribute("cm-not-content", "true")
// Will contain the actual code, positioned to cover the viewport.
d.lineDiv = elt("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 = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
null, "position: relative; outline: none")
// Moved around its parent to cover visible view.
d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative")
// Set to the height of the document, allowing scrolling.
d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
d.sizerWidth = null
// Behavior of elts with overflow: auto and padding is
// inconsistent across browsers. This is used to ensure the
// scrollable area is big enough.
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
// Will contain the gutters, if any.
d.gutters = elt("div", null, "CodeMirror-gutters")
d.lineGutter = null
// Actual scrollable element.
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
d.scroller.setAttribute("tabIndex", "-1")
// The element in which the editor lives.
d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
if (place) {
if (place.appendChild) { place.appendChild(d.wrapper) }
else { place(d.wrapper) }
}
// Current rendered range (may be bigger than the view window).
d.viewFrom = d.viewTo = doc.first
d.reportedViewFrom = d.reportedViewTo = doc.first
// Information about the rendered lines.
d.view = []
d.renderedView = null
// Holds info about a single rendered line when it was rendered
// for measurement, while not in view.
d.externalMeasured = null
// Empty space (in pixels) above the view
d.viewOffset = 0
d.lastWrapHeight = d.lastWrapWidth = 0
d.updateLineNumbers = null
d.nativeBarWidth = d.barHeight = d.barWidth = 0
d.scrollbarsClipped = false
// Used to only resize the line number gutter when necessary (when
// the amount of lines crosses a boundary that makes its width change)
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
// Set to true when a non-horizontal-scrolling line widget is
// added. As an optimization, line widget aligning is skipped when
// this is false.
d.alignWidgets = false
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
d.maxLine = null
d.maxLineLength = 0
d.maxLineChanged = false
// Used for measuring wheel scrolling granularity
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
// True when shift is held down.
d.shift = false
// Used to track whether anything happened since the context menu
// was opened.
d.selForContextMenu = null
d.activeTouch = null
input.init(d)
}
// Find the line object corresponding to the given line number.
function getLine(doc, n) {
n -= doc.first
if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
var chunk = doc
while (!chunk.lines) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize()
if (n < sz) { chunk = child; break }
n -= sz
}
}
return chunk.lines[n]
}
// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
var out = [], n = start.line
doc.iter(start.line, end.line + 1, function (line) {
var text = line.text
if (n == end.line) { text = text.slice(0, end.ch) }
if (n == start.line) { text = text.slice(start.ch) }
out.push(text)
++n
})
return out
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
var out = []
doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
return out
}
// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
var diff = height - line.height
if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
}
// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
if (line.parent == null) { return null }
var cur = line.parent, no = indexOf(cur.lines, line)
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0;; ++i) {
if (chunk.children[i] == cur) { break }
no += chunk.children[i].chunkSize()
}
}
return no + cur.first
}
// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
var n = chunk.first
outer: do {
for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
var child = chunk.children[i$1], ch = child.height
if (h < ch) { chunk = child; continue outer }
h -= ch
n += child.chunkSize()
}
return n
} while (!chunk.lines)
var i = 0
for (; i < chunk.lines.length; ++i) {
var line = chunk.lines[i], lh = line.height
if (h < lh) { break }
h -= lh
}
return n + i
}
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
function lineNumberFor(options, i) {
return String(options.lineNumberFormatter(i + options.firstLineNumber))
}
// A Pos instance represents a position within the text.
function Pos (line, ch) {
if (!(this instanceof Pos)) { return new Pos(line, ch) }
this.line = line; this.ch = ch
}
// 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 copyPos(x) {return Pos(x.line, x.ch)}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
function clipPos(doc, pos) {
if (pos.line < doc.first) { return Pos(doc.first, 0) }
var last = doc.first + doc.size - 1
if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
return clipToLen(pos, getLine(doc, pos.line).text.length)
}
function clipToLen(pos, linelen) {
var ch = pos.ch
if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
else if (ch < 0) { return Pos(pos.line, 0) }
else { return pos }
}
function clipPosArray(doc, array) {
var out = []
for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
return out
}
// Optimize some code when these features are not used.
var sawReadOnlySpans = false;
var sawCollapsedSpans = false;
function seeReadOnlySpans() {
sawReadOnlySpans = true
}
function seeCollapsedSpans() {
sawCollapsedSpans = true
}
// TEXTMARKER SPANS
function MarkedSpan(marker, from, to) {
this.marker = marker
this.from = from; this.to = to
}
// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i]
if (span.marker == marker) { return span }
} }
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
var r
for (var i = 0; i < spans.length; ++i)
{ if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
return r
}
// Add a span to a line.
function addMarkedSpan(line, span) {
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
span.marker.attachLine(line)
}
// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
var nw
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
}
} }
return nw
}
function markedSpansAfter(old, endCh, isInsert) {
var nw
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
span.to == null ? null : span.to - endCh))
}
} }
return nw
}
// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
if (change.full) { return null }
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
if (!oldFirst && !oldLast) { return null }
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert)
var last = markedSpansAfter(oldLast, endCh, isInsert)
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i]
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker)
if (!found) { span.to = startCh }
else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i$1 = 0; i$1 < last.length; ++i$1) {
var span$1 = last[i$1]
if (span$1.to != null) { span$1.to += offset }
if (span$1.from == null) {
var found$1 = getMarkedSpanFor(first, span$1.marker)
if (!found$1) {
span$1.from = offset
if (sameLine) { (first || (first = [])).push(span$1) }
}
} else {
span$1.from += offset
if (sameLine) { (first || (first = [])).push(span$1) }
}
}
}
// Make sure we didn't create any zero-length spans
if (first) { first = clearEmptySpans(first) }
if (last && last != first) { last = clearEmptySpans(last) }
var newMarkers = [first]
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers
if (gap > 0 && first)
{ for (var i$2 = 0; i$2 < first.length; ++i$2)
{ if (first[i$2].to == null)
{ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
for (var i$3 = 0; i$3 < gap; ++i$3)
{ newMarkers.push(gapMarkers) }
newMarkers.push(last)
}
return newMarkers
}
// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
for (var i = 0; i < spans.length; ++i) {
var span = spans[i]
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
{ spans.splice(i--, 1) }
}
if (!spans.length) { return null }
return spans
}
// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
var markers = null
doc.iter(from.line, to.line + 1, function (line) {
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var mark = line.markedSpans[i].marker
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
{ (markers || (markers = [])).push(mark) }
} }
})
if (!markers) { return null }
var parts = [{from: from, to: to}]
for (var i = 0; i < markers.length; ++i) {
var mk = markers[i], m = mk.find(0)
for (var j = 0; j < parts.length; ++j) {
var p = parts[j]
if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
{ newParts.push({from: p.from, to: m.from}) }
if (dto > 0 || !mk.inclusiveRight && !dto)
{ newParts.push({from: m.to, to: p.to}) }
parts.splice.apply(parts, newParts)
j += newParts.length - 1
}
}
return parts
}
// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
var spans = line.markedSpans
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.detachLine(line) }
line.markedSpans = null
}
function attachMarkedSpans(line, spans) {
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.attachLine(line) }
line.markedSpans = spans
}
// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
var lenDiff = a.lines.length - b.lines.length
if (lenDiff != 0) { return lenDiff }
var aPos = a.find(), bPos = b.find()
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
if (fromCmp) { return -fromCmp }
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
if (toCmp) { return toCmp }
return b.id - a.id
}
// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
var sps = sawCollapsedSpans && line.markedSpans, found
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i]
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
{ found = sp.marker }
} }
return found
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo, 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
}
// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
var merged, lines
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line
;(lines || (lines = [])).push(line)
}
return lines
}
// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
var line = getLine(doc, lineN), vis = visualLine(line)
if (line == vis) { return lineN }
return lineNo(vis)
}
// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) { return lineN }
var line = getLine(doc, lineN), merged
if (!lineIsHidden(doc, line)) { return lineN }
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line }
return lineNo(line) + 1
}
// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
var sps = sawCollapsedSpans && line.markedSpans
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i]
if (!sp.marker.collapsed) { continue }
if (sp.from == null) { return true }
if (sp.marker.widgetNode) { continue }
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
{ return true }
} }
}
function lineIsHiddenInner(doc, line, span) {
if (span.to == null) {
var end = span.marker.find(1, true)
return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
}
if (span.marker.inclusiveRight && span.to == line.text.length)
{ return true }
for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
sp = line.markedSpans[i]
if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
(sp.to == null || sp.to != span.from) &&
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
lineIsHiddenInner(doc, line, sp)) { return true }
}
}
// Find the height above the given line.
function heightAtLine(lineObj) {
lineObj = visualLine(lineObj)
var h = 0, chunk = lineObj.parent
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i]
if (line == lineObj) { break }
else { h += line.height }
}
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
var cur = p.children[i$1]
if (cur == chunk) { break }
else { h += cur.height }
}
}
return h
}
// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
if (line.height == 0) { return 0 }
var len = line.text.length, merged, cur = line
while (merged = collapsedSpanAtStart(cur)) {
var found = merged.find(0, true)
cur = found.from.line
len += found.from.ch - found.to.ch
}
cur = line
while (merged = collapsedSpanAtEnd(cur)) {
var found$1 = merged.find(0, true)
len -= cur.text.length - found$1.from.ch
cur = found$1.to.line
len += cur.text.length - found$1.to.ch
}
return len
}
// Find the longest line in the document.
function findMaxLine(cm) {
var d = cm.display, doc = cm.doc
d.maxLine = getLine(doc, doc.first)
d.maxLineLength = lineLength(d.maxLine)
d.maxLineChanged = true
doc.iter(function (line) {
var len = lineLength(line)
if (len > d.maxLineLength) {
d.maxLineLength = len
d.maxLine = line
}
})
}
// BIDI HELPERS
function iterateBidiSections(order, from, to, f) {
if (!order) { return f(from, to, "ltr") }
var found = false
for (var i = 0; i < order.length; ++i) {
var part = order[i]
if (part.from < to && part.to > from || from == to && part.to == from) {
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
found = true
}
}
if (!found) { f(from, to, "ltr") }
}
function bidiLeft(part) { return part.level % 2 ? part.to : part.from }
function bidiRight(part) { return part.level % 2 ? part.from : part.to }
function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 }
function lineRight(line) {
var order = getOrder(line)
if (!order) { return line.text.length }
return bidiRight(lst(order))
}
function compareBidiLevel(order, a, b) {
var linedir = order[0].level
if (a == linedir) { return true }
if (b == linedir) { return false }
return a < b
}
var bidiOther = null
function getBidiPartAt(order, pos) {
var found
bidiOther = null
for (var i = 0; i < order.length; ++i) {
var cur = order[i]
if (cur.from < pos && cur.to > pos) { return i }
if ((cur.from == pos || cur.to == pos)) {
if (found == null) {
found = i
} else if (compareBidiLevel(order, cur.level, order[found].level)) {
if (cur.from != cur.to) { bidiOther = found }
return i
} else {
if (cur.from != cur.to) { bidiOther = i }
return found
}
}
}
return found
}
function moveInLine(line, pos, dir, byUnit) {
if (!byUnit) { return pos + dir }
do { pos += dir }
while (pos > 0 && isExtendingChar(line.text.charAt(pos)))
return pos
}
// This is needed in order to move 'visually' through bi-directional
// text -- i.e., pressing left should make the cursor go left, even
// when in RTL text. The tricky part is the 'jumps', where RTL and
// LTR text touch each other. This often requires the cursor offset
// to move more than one unit, in order to visually move one unit.
function moveVisually(line, start, dir, byUnit) {
var bidi = getOrder(line)
if (!bidi) { return moveLogically(line, start, dir, byUnit) }
var pos = getBidiPartAt(bidi, start), part = bidi[pos]
var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit)
for (;;) {
if (target > part.from && target < part.to) { return target }
if (target == part.from || target == part.to) {
if (getBidiPartAt(bidi, target) == pos) { return target }
part = bidi[pos += dir]
return (dir > 0) == part.level % 2 ? part.to : part.from
} else {
part = bidi[pos += dir]
if (!part) { return null }
if ((dir > 0) == part.level % 2)
{ target = moveInLine(line, part.to, -1, byUnit) }
else
{ target = moveInLine(line, part.from, 1, byUnit) }
}
}
}
function moveLogically(line, start, dir, byUnit) {
var target = start + dir
if (byUnit) { while (target > 0 && isExtendingChar(line.text.charAt(target))) { target += dir } }
return target < 0 || target > line.text.length ? null : target
}
// 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]/
// Browsers seem to always treat the boundaries of block elements as being L.
var outerType = "L"
function BidiSpan(level, from, to) {
this.level = level
this.from = from; this.to = to
}
return function(str) {
if (!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 ? "L" : "R"
for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
i$6 = end$1 - 1
}
}
// Here we depart from the documented algorithm, in order to avoid
// building up an actual levels array. Since there are only three
// levels (0, 1, 2) in an implementation that doesn't take
// explicit embedding into account, we can build up the order on
// the fly, without following the level-based algorithm.
var order = [], m
for (var i$7 = 0; i$7 < len;) {
if (countsAsLeft.test(types[i$7])) {
var start = i$7
for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
order.push(new BidiSpan(0, start, i$7))
} else {
var pos = i$7, at = order.length
for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
for (var j$2 = pos; j$2 < i$7;) {
if (countsAsNum.test(types[j$2])) {
if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
var nstart = j$2
for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
order.splice(at, 0, new BidiSpan(2, nstart, j$2))
pos = j$2
} else { ++j$2 }
}
if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
}
}
if (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))
}
if (order[0].level == 2)
{ order.unshift(new BidiSpan(1, order[0].to, order[0].to)) }
if (order[0].level != lst(order).level)
{ order.push(new BidiSpan(order[0].level, len, len)) }
return 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) {
var order = line.order
if (order == null) { order = line.order = bidiOrdering(line.text) }
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
}
var modes = {};
var mimeModes = {};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
function defineMode(name, mode) {
if (arguments.length > 2)
{ mode.dependencies = Array.prototype.slice.call(arguments, 2) }
modes[name] = mode
}
function defineMIME(mime, spec) {
mimeModes[mime] = spec
}
// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
function resolveMode(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec]
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
var found = mimeModes[spec.name]
if (typeof found == "string") { found = {name: found} }
spec = createObj(found, spec)
spec.name = found.name
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
return resolveMode("application/xml")
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
return resolveMode("application/json")
}
if (typeof spec == "string") { return {name: spec} }
else { return spec || {name: "null"} }
}
// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
function getMode(options, spec) {
spec = resolveMode(spec)
var mfactory = modes[spec.name]
if (!mfactory) { return getMode(options, "text/plain") }
var modeObj = mfactory(options, spec)
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name]
for (var prop in exts) {
if (!exts.hasOwnProperty(prop)) { continue }
if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
modeObj[prop] = exts[prop]
}
}
modeObj.name = spec.name
if (spec.helperType) { modeObj.helperType = spec.helperType }
if (spec.modeProps) { for (var prop$1 in spec.modeProps)
{ modeObj[prop$1] = spec.modeProps[prop$1] } }
return modeObj
}
// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = {}
function extendMode(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
copyObj(properties, exts)
}
function copyState(mode, state) {
if (state === true) { return state }
if (mode.copyState) { return mode.copyState(state) }
var nstate = {}
for (var n in state) {
var val = state[n]
if (val instanceof Array) { val = val.concat([]) }
nstate[n] = val
}
return nstate
}
// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
function innerMode(mode, state) {
var info
while (mode.innerMode) {
info = mode.innerMode(state)
if (!info || info.mode == mode) { break }
state = info.state
mode = info.mode
}
return info || {mode: mode, state: state}
}
function startState(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true
}
// STRING STREAM
// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.
var StringStream = function(string, tabSize) {
this.pos = this.start = 0
this.string = string
this.tabSize = tabSize || 8
this.lastColumnPos = this.lastColumnValue = 0
this.lineStart = 0
}
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length},
sol: function() {return this.pos == this.lineStart},
peek: function() {return this.string.charAt(this.pos) || undefined},
next: function() {
if (this.pos < this.string.length)
{ return this.string.charAt(this.pos++) }
},
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}
},
eatWhile: function(match) {
var start = this.pos
while (this.eat(match)){}
return this.pos > start
},
eatSpace: function() {
var this$1 = this;
var start = this.pos
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
return this.pos > start
},
skipToEnd: function() {this.pos = this.string.length},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos)
if (found > -1) {this.pos = found; return true}
},
backUp: function(n) {this.pos -= n},
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)
},
indentation: function() {
return countColumn(this.string, null, this.tabSize) -
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
},
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
}
},
current: function(){return this.string.slice(this.start, this.pos)},
hideFirstChars: function(n, inner) {
this.lineStart += n
try { return inner() }
finally { this.lineStart -= n }
}
}
// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, state, forceToEnd) {
// A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen], lineClasses = {}
// Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
lineClasses, forceToEnd)
// Run overlays, adjust style array.
var loop = function ( o ) {
var overlay = cm.state.overlays[o], i = 1, at = 0
runMode(cm, line.text, overlay.mode, true, function (end, style) {
var start = i
// Ensure there's a token end at the current position, and that i points at it
while (at < end) {
var i_end = st[i]
if (i_end > end)
{ st.splice(i, 1, end, st[i+1], i_end) }
i += 2
at = Math.min(end, i_end)
}
if (!style) { return }
if (overlay.opaque) {
st.splice(start, i - start, end, "overlay " + style)
i = start + 2
} else {
for (; start < i; start += 2) {
var cur = st[start+1]
st[start+1] = (cur ? cur + " " : "") + "overlay " + style
}
}
}, lineClasses)
};
for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
}
function getLineStyles(cm, line, updateFrontier) {
if (!line.styles || line.styles[0] != cm.state.modeGen) {
var state = getStateBefore(cm, lineNo(line))
var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state)
line.stateAfter = state
line.styles = result.styles
if (result.classes) { line.styleClasses = result.classes }
else if (line.styleClasses) { line.styleClasses = null }
if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ }
}
return line.styles
}
function getStateBefore(cm, n, precise) {
var doc = cm.doc, display = cm.display
if (!doc.mode.startState) { return true }
var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter
if (!state) { state = startState(doc.mode) }
else { state = copyState(doc.mode, state) }
doc.iter(pos, n, function (line) {
processLine(cm, line.text, state)
var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo
line.stateAfter = save ? copyState(doc.mode, state) : null
++pos
})
if (precise) { doc.frontier = pos }
return state
}
// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, state, startAt) {
var mode = cm.doc.mode
var stream = new StringStream(text, cm.options.tabSize)
stream.start = stream.pos = startAt || 0
if (text == "") { callBlankLine(mode, state) }
while (!stream.eol()) {
readToken(mode, stream, state)
stream.start = stream.pos
}
}
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.")
}
// Utility for getTokenAt and getLineTokens
function takeToken(cm, pos, precise, asArray) {
var getObj = function (copy) { return ({
start: stream.start, end: stream.pos,
string: stream.current(),
type: style || null,
state: copy ? copyState(doc.mode, state) : state
}); }
var doc = cm.doc, mode = doc.mode, style
pos = clipPos(doc, pos)
var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise)
var stream = new StringStream(line.text, cm.options.tabSize), tokens
if (asArray) { tokens = [] }
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos
style = readToken(mode, stream, state)
if (asArray) { tokens.push(getObj(true)) }
}
return asArray ? tokens : getObj()
}
function extractLineClasses(type, output) {
if (type) { for (;;) {
var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
if (!lineClass) { break }
type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
var prop = lineClass[1] ? "bgClass" : "textClass"
if (output[prop] == null)
{ output[prop] = lineClass[2] }
else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
{ output[prop] += " " + lineClass[2] }
} }
return type
}
// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
var flattenSpans = mode.flattenSpans
if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
var curStart = 0, curStyle = null
var stream = new StringStream(text, cm.options.tabSize), style
var inner = cm.options.addModeClass && [null]
if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) }
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false
if (forceToEnd) { processLine(cm, text, state, stream.pos) }
stream.pos = text.length
style = null
} else {
style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses)
}
if (inner) {
var mName = inner[0].name
if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 5000)
f(curStart, curStyle)
}
curStyle = style
}
stream.start = stream.pos
}
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)
if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
var indented = countColumn(line.text, null, cm.options.tabSize)
if (minline == null || minindent > indented) {
minline = search - 1
minindent = indented
}
}
return minline
}
// LINE DATA STRUCTURE
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
function Line(text, markedSpans, estimateHeight) {
this.text = text
attachMarkedSpans(this, markedSpans)
this.height = estimateHeight ? estimateHeight(this) : 1
}
eventMixin(Line)
Line.prototype.lineNo = function() { return lineNo(this) }
// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text
if (line.stateAfter) { line.stateAfter = null }
if (line.styles) { line.styles = null }
if (line.order != null) { line.order = null }
detachMarkedSpans(line)
attachMarkedSpans(line, markedSpans)
var estHeight = estimateHeight ? estimateHeight(line) : 1
if (estHeight != line.height) { updateLineHeight(line, estHeight) }
}
// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
line.parent = null
detachMarkedSpans(line)
}
// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {};
var styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
if (!style || /^\s*$/.test(style)) { return null }
var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
return cache[style] ||
(cache[style] = style.replace(/\S+/g, "cm-$&"))
}
// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null)
var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
col: 0, pos: 0, cm: cm,
trailingSpace: false,
splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
// hide from accessibility tree
content.setAttribute("role", "presentation")
builder.pre.setAttribute("role", "presentation")
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)))
{ builder.addToken = buildTokenBadBidi(builder.addToken, order) }
builder.map = []
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
if (line.styleClasses) {
if (line.styleClasses.bgClass)
{ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
if (line.styleClasses.textClass)
{ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
{ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map
lineView.measure.cache = {}
} else {
;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
}
}
// See issue #2901
if (webkit) {
var last = builder.content.lastChild
if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
{ builder.content.className = "cm-tab-wrap-hack" }
}
signal(cm, "renderLine", cm, lineView.line, builder.pre)
if (builder.pre.className)
{ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
return builder
}
function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar")
token.title = "\\u" + ch.charCodeAt(0).toString(16)
token.setAttribute("aria-label", token.title)
return token
}
// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) { return }
var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
var special = builder.cm.state.specialChars, mustWrap = false
var content
if (!special.test(text)) {
builder.col += text.length
content = document.createTextNode(displayText)
builder.map.push(builder.pos, builder.pos + text.length, content)
if (ie && ie_version < 9) { mustWrap = true }
builder.pos += text.length
} else {
content = document.createDocumentFragment()
var pos = 0
while (true) {
special.lastIndex = pos
var m = special.exec(text)
var skipped = m ? m.index - pos : text.length - pos
if (skipped) {
var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
else { content.appendChild(txt) }
builder.map.push(builder.pos, builder.pos + skipped, txt)
builder.col += skipped
builder.pos += skipped
}
if (!m) { break }
pos += skipped + 1
var txt$1 = (void 0)
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
txt$1.setAttribute("role", "presentation")
txt$1.setAttribute("cm-text", "\t")
builder.col += tabWidth
} else if (m[0] == "\r" || m[0] == "\n") {
txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
txt$1.setAttribute("cm-text", m[0])
builder.col += 1
} else {
txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
txt$1.setAttribute("cm-text", m[0])
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
else { content.appendChild(txt$1) }
builder.col += 1
}
builder.map.push(builder.pos, builder.pos + 1, txt$1)
builder.pos++
}
}
builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
if (style || startStyle || endStyle || mustWrap || css) {
var fullStyle = style || ""
if (startStyle) { fullStyle += startStyle }
if (endStyle) { fullStyle += endStyle }
var token = elt("span", [content], fullStyle, css)
if (title) { token.title = title }
return builder.content.appendChild(token)
}
builder.content.appendChild(content)
}
function splitSpaces(text, trailingBefore) {
if (text.length > 1 && !/ /.test(text)) { return text }
var spaceBefore = trailingBefore, result = ""
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i)
if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
{ ch = "\u00a0" }
result += ch
spaceBefore = ch == " "
}
return result
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function (builder, text, style, startStyle, endStyle, title, css) {
style = style ? style + " cm-force-border" : "cm-force-border"
var start = builder.pos, end = start + text.length
for (;;) {
// Find the part that overlaps with the start of this text
var part = (void 0)
for (var i = 0; i < order.length; i++) {
part = order[i]
if (part.to > start && part.from <= start) { break }
}
if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
startStyle = null
text = text.slice(part.to - start)
start = part.to
}
}
}
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
var widget = !ignoreWidget && marker.widgetNode
if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
if (!widget)
{ widget = builder.content.appendChild(document.createElement("span")) }
widget.setAttribute("cm-marker", marker.id)
}
if (widget) {
builder.cm.display.input.setUneditable(widget)
builder.content.appendChild(widget)
}
builder.pos += size
builder.trailingSpace = false
}
// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
var spans = line.markedSpans, allText = line.text, at = 0
if (!spans) {
for (var i$1 = 1; i$1 < styles.length; i$1+=2)
{ builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
return
}
var len = allText.length, pos = 0, i = 1, text = "", style, css
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
for (;;) {
if (nextChange == pos) { // Update current marker set
spanStyle = spanEndStyle = spanStartStyle = title = css = ""
collapsed = null; nextChange = Infinity
var foundBookmarks = [], endStyles = (void 0)
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
foundBookmarks.push(m)
} else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
if (sp.to != null && sp.to != pos && nextChange > sp.to) {
nextChange = sp.to
spanEndStyle = ""
}
if (m.className) { spanStyle += " " + m.className }
if (m.css) { css = (css ? css + ";" : "") + m.css }
if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
if (m.title && !title) { title = m.title }
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
{ collapsed = sp }
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from
}
}
if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
{ if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
{ buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null)
if (collapsed.to == null) { return }
if (collapsed.to == pos) { collapsed = false }
}
}
if (pos >= len) { break }
var upto = Math.min(len, nextChange)
while (true) {
if (text) {
var end = pos + text.length
if (!collapsed) {
var tokenText = end > upto ? text.slice(0, upto - pos) : text
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
}
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
pos = end
spanStartStyle = ""
}
text = allText.slice(at, at = styles[i++])
style = interpretTokenStyle(styles[i++], builder.cm.options)
}
}
}
// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
// The starting line
this.line = line
// Continuing lines, if any
this.rest = visualLineContinued(line)
// Number of logical lines in this visual line
this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
this.node = this.text = null
this.hidden = lineIsHidden(doc, line)
}
// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
var array = [], nextPos
for (var pos = from; pos < to; pos = nextPos) {
var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
nextPos = pos + view.size
array.push(view)
}
return array
}
var operationGroup = null
function pushOperation(op) {
if (operationGroup) {
operationGroup.ops.push(op)
} else {
op.ownsGroup = operationGroup = {
ops: [op],
delayedCallbacks: []
}
}
}
function fireCallbacksForOps(group) {
// Calls delayed callbacks and cursorActivity handlers until no
// new ones appear
var callbacks = group.delayedCallbacks, i = 0
do {
for (; i < callbacks.length; i++)
{ callbacks[i].call(null) }
for (var j = 0; j < group.ops.length; j++) {
var op = group.ops[j]
if (op.cursorActivityHandlers)
{ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
{ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
}
} while (i < callbacks.length)
}
function finishOperation(op, endCb) {
var group = op.ownsGroup
if (!group) { return }
try { fireCallbacksForOps(group) }
finally {
operationGroup = null
endCb(group)
}
}
var orphanDelayedCallbacks = null
// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
function signalLater(emitter, type /*, values...*/) {
var arr = getHandlers(emitter, type)
if (!arr.length) { return }
var args = Array.prototype.slice.call(arguments, 2), list
if (operationGroup) {
list = operationGroup.delayedCallbacks
} else if (orphanDelayedCallbacks) {
list = orphanDelayedCallbacks
} else {
list = orphanDelayedCallbacks = []
setTimeout(fireOrphanDelayed, 0)
}
var loop = function ( i ) {
list.push(function () { return arr[i].apply(null, args); })
};
for (var i = 0; i < arr.length; ++i)
loop( i );
}
function fireOrphanDelayed() {
var delayed = orphanDelayedCallbacks
orphanDelayedCallbacks = null
for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
}
// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
for (var j = 0; j < lineView.changes.length; j++) {
var type = lineView.changes[j]
if (type == "text") { updateLineText(cm, lineView) }
else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
else if (type == "class") { updateLineClasses(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(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)
}
}
// 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(lineView)
} else if (cls) {
lineView.text.className = cls
}
}
function updateLineClasses(lineView) {
updateLineBackground(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"))
wrap.insertBefore(lineView.gutterBackground, lineView.text)
}
var markers = lineView.line.gutterMarkers
if (cm.options.lineNumbers || markers) {
var wrap$1 = ensureLineWrapped(lineView)
var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
cm.display.input.setUneditable(gutterWrap)
wrap$1.insertBefore(gutterWrap, lineView.text)
if (lineView.line.gutterClass)
{ gutterWrap.className += " " + lineView.line.gutterClass }
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
{ lineView.lineNumber = gutterWrap.appendChild(
elt("div", lineNumberFor(cm.options, lineN),
"CodeMirror-linenumber CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
if (found)
{ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
} }
}
}
function updateLineWidgets(cm, lineView, dims) {
if (lineView.alignable) { lineView.alignable = null }
for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
next = node.nextSibling
if (node.className == "CodeMirror-linewidget")
{ lineView.node.removeChild(node) }
}
insertLineWidgets(cm, lineView, dims)
}
// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
var built = getLineContent(cm, lineView)
lineView.text = lineView.node = built.pre
if (built.bgClass) { lineView.bgClass = built.bgClass }
if (built.textClass) { lineView.textClass = built.textClass }
updateLineClasses(lineView)
updateLineGutter(cm, lineView, lineN, dims)
insertLineWidgets(cm, lineView, dims)
return lineView.node
}
// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(cm, lineView, dims) {
insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
{ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
}
function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
if (!line.widgets) { return }
var wrap = ensureLineWrapped(lineView)
for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
positionLineWidget(widget, node, lineView, dims)
cm.display.input.setUneditable(node)
if (allowAbove && widget.above)
{ wrap.insertBefore(node, lineView.gutter || lineView.text) }
else
{ wrap.appendChild(node) }
signalLater(widget, "redraw")
}
}
function positionLineWidget(widget, node, lineView, dims) {
if (widget.noHScroll) {
;(lineView.alignable || (lineView.alignable = [])).push(node)
var width = dims.wrapperWidth
node.style.left = dims.fixedPos + "px"
if (!widget.coverGutter) {
width -= dims.gutterTotalWidth
node.style.paddingLeft = dims.gutterTotalWidth + "px"
}
node.style.width = width + "px"
}
if (widget.coverGutter) {
node.style.zIndex = 5
node.style.position = "relative"
if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
}
}
function widgetHeight(widget) {
if (widget.height != null) { return widget.height }
var cm = widget.doc.cm
if (!cm) { return 0 }
if (!contains(document.body, widget.node)) {
var parentStyle = "position: relative;"
if (widget.coverGutter)
{ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
if (widget.noHScroll)
{ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
}
return widget.height = widget.node.parentNode.offsetHeight
}
// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
(n.parentNode == display.sizer && n != display.mover))
{ return true }
}
}
// POSITION MEASUREMENT
function paddingTop(display) {return display.lineSpace.offsetTop}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
function paddingH(display) {
if (display.cachedPaddingH) { return display.cachedPaddingH }
var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
return data
}
function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
function displayWidth(cm) {
return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
}
function displayHeight(cm) {
return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
}
// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
var wrapping = cm.options.lineWrapping
var curWidth = wrapping && displayWidth(cm)
if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
var heights = lineView.measure.heights = []
if (wrapping) {
lineView.measure.width = curWidth
var rects = lineView.text.firstChild.getClientRects()
for (var i = 0; i < rects.length - 1; i++) {
var cur = rects[i], next = rects[i + 1]
if (Math.abs(cur.bottom - next.bottom) > 2)
{ heights.push((cur.bottom + next.top) / 2 - rect.top) }
}
}
heights.push(rect.bottom - rect.top)
}
}
// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
if (lineView.line == line)
{ return {map: lineView.measure.map, cache: lineView.measure.cache} }
for (var i = 0; i < lineView.rest.length; i++)
{ if (lineView.rest[i] == line)
{ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
{ if (lineNo(lineView.rest[i$1]) > lineN)
{ return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
}
// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
line = visualLine(line)
var lineN = lineNo(line)
var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
view.lineN = lineN
var built = view.built = buildLineContent(cm, view)
view.text = built.pre
removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
return view
}
// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
}
// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
{ return cm.display.view[findViewIndex(cm, lineN)] }
var ext = cm.display.externalMeasured
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
{ return ext }
}
// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line)
var view = findViewForLine(cm, lineN)
if (view && !view.text) {
view = null
} else if (view && view.changes) {
updateLineForChanges(cm, view, lineN, getDimensions(cm))
cm.curOp.forceUpdate = true
}
if (!view)
{ view = updateExternalMeasurement(cm, line) }
var info = mapFromLineView(view, line, lineN)
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
}
}
// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
if (prepared.before) { ch = -1 }
var key = ch + (bias || ""), found
if (prepared.cache.hasOwnProperty(key)) {
found = prepared.cache[key]
} else {
if (!prepared.rect)
{ prepared.rect = prepared.view.text.getBoundingClientRect() }
if (!prepared.hasHeights) {
ensureLineHeights(cm, prepared.view, prepared.rect)
prepared.hasHeights = true
}
found = measureCharInner(cm, prepared, ch, bias)
if (!found.bogus) { prepared.cache[key] = found }
}
return {left: found.left, right: found.right,
top: varHeight ? found.rtop : found.top,
bottom: varHeight ? found.rbottom : found.bottom}
}
var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
function nodeAndOffsetInLineMap(map, 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() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft }
function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop }
// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"./null (editor), "window",
// or "page".
function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
var size = widgetHeight(lineObj.widgets[i])
rect.top += size; rect.bottom += size
} } }
if (context == "line") { return rect }
if (!context) { context = "local" }
var yOff = heightAtLine(lineObj)
if (context == "local") { yOff += paddingTop(cm.display) }
else { yOff -= cm.display.viewOffset }
if (context == "page" || context == "window") {
var lOff = cm.display.lineSpace.getBoundingClientRect()
yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
rect.left += xOff; rect.right += xOff
}
rect.top += yOff; rect.bottom += yOff
return rect
}
// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"./null.
function fromCoordSystem(cm, coords, context) {
if (context == "div") { return coords }
var left = coords.left, top = coords.top
// First move into "page" coordinate system
if (context == "page") {
left -= pageScrollX()
top -= pageScrollY()
} else if (context == "local" || !context) {
var localBox = cm.display.sizer.getBoundingClientRect()
left += localBox.left
top += localBox.top
}
var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
}
function charCoords(cm, pos, context, lineObj, bias) {
if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
}
// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
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)
}
function getBidi(ch, partPos) {
var part = order[partPos], right = part.level % 2
if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
part = order[--partPos]
ch = bidiRight(part) - (part.level % 2 ? 0 : 1)
right = true
} else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
part = order[++partPos]
ch = bidiLeft(part) - part.level % 2
right = false
}
if (right && ch == part.to && ch > part.from) { return get(ch - 1) }
return get(ch, right)
}
var order = getOrder(lineObj), ch = pos.ch
if (!order) { return get(ch) }
var partPos = getBidiPartAt(order, ch)
var val = getBidi(ch, partPos)
if (bidiOther != null) { val.other = getBidi(ch, bidiOther) }
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, outside, xRel) {
var pos = Pos(line, ch)
pos.xRel = xRel
if (outside) { pos.outside = true }
return pos
}
// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
var doc = cm.doc
y += cm.display.viewOffset
if (y < 0) { return PosWithInfo(doc.first, 0, true, -1) }
var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
if (lineN > last)
{ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) }
if (x < 0) { x = 0 }
var lineObj = getLine(doc, lineN)
for (;;) {
var found = coordsCharInner(cm, lineObj, lineN, x, y)
var merged = collapsedSpanAtEnd(lineObj)
var mergedPos = merged && merged.find(0, true)
if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
{ lineN = lineNo(lineObj = mergedPos.to.line) }
else
{ return found }
}
}
function coordsCharInner(cm, lineObj, lineNo, x, y) {
var innerOff = y - heightAtLine(lineObj)
var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth
var preparedMeasure = prepareMeasureForLine(cm, lineObj)
function getX(ch) {
var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure)
wrongLine = true
if (innerOff > sp.bottom) { return sp.left - adjust }
else if (innerOff < sp.top) { return sp.left + adjust }
else { wrongLine = false }
return sp.left
}
var bidi = getOrder(lineObj), dist = lineObj.text.length
var from = lineLeft(lineObj), to = lineRight(lineObj)
var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine
if (x > toX) { return PosWithInfo(lineNo, to, toOutside, 1) }
// Do a binary search between these bounds.
for (;;) {
if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
var ch = x < fromX || x - fromX <= toX - x ? from : to
var outside = ch == from ? fromOutside : toOutside
var xDiff = x - (ch == from ? fromX : toX)
// This is a kludge to handle the case where the coordinates
// are after a line-wrapped line. We should replace it with a
// more general handling of cursor positions around line
// breaks. (Issue #4078)
if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right")
if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
outside = false
ch++
xDiff = x - charSize.right
}
}
while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch }
var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0)
return pos
}
var step = Math.ceil(dist / 2), middle = from + step
if (bidi) {
middle = from
for (var i = 0; i < step; ++i) { middle = moveVisually(lineObj, middle, 1) }
}
var middleX = getX(middle)
if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step}
else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step}
}
}
var measureText
// Compute the default text height.
function textHeight(display) {
if (display.cachedTextHeight != null) { return display.cachedTextHeight }
if (measureText == null) {
measureText = elt("pre")
// Measure a bunch of lines, for browsers that compute
// fractional heights.
for (var i = 0; i < 49; ++i) {
measureText.appendChild(document.createTextNode("x"))
measureText.appendChild(elt("br"))
}
measureText.appendChild(document.createTextNode("x"))
}
removeChildrenAndAdd(display.measure, measureText)
var height = measureText.offsetHeight / 50
if (height > 3) { display.cachedTextHeight = height }
removeChildren(display.measure)
return height || 1
}
// Compute the default character width.
function charWidth(display) {
if (display.cachedCharWidth != null) { return display.cachedCharWidth }
var anchor = elt("span", "xxxxxxxxxx")
var pre = elt("pre", [anchor])
removeChildrenAndAdd(display.measure, pre)
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
if (width > 2) { display.cachedCharWidth = width }
return width || 10
}
// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
var d = cm.display, left = {}, width = {}
var gutterLeft = d.gutters.clientLeft
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
width[cm.options.gutters[i]] = n.clientWidth
}
return {fixedPos: compensateForHScroll(d),
gutterTotalWidth: d.gutters.offsetWidth,
gutterLeft: left,
gutterWidth: width,
wrapperWidth: d.wrapper.clientWidth}
}
// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
}
// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
return function (line) {
if (lineIsHidden(cm.doc, line)) { return 0 }
var widgetsHeight = 0
if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
} }
if (wrapping)
{ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
else
{ return widgetsHeight + th }
}
}
function estimateLineHeights(cm) {
var doc = cm.doc, est = estimateHeight(cm)
doc.iter(function (line) {
var estHeight = est(line)
if (estHeight != line.height) { updateLineHeight(line, estHeight) }
})
}
// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
var display = cm.display
if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
var x, y, space = display.lineSpace.getBoundingClientRect()
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX - space.left; y = e.clientY - space.top }
catch (e) { return null }
var coords = coordsChar(cm, x, y), line
if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
}
return coords
}
// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
if (n >= cm.display.viewTo) { return null }
n -= cm.display.viewFrom
if (n < 0) { return null }
var view = cm.display.view
for (var i = 0; i < view.length; i++) {
n -= view[i].size
if (n < 0) { return i }
}
}
function updateSelection(cm) {
cm.display.input.showSelection(cm.display.input.prepareSelection())
}
function prepareSelection(cm, primary) {
var doc = cm.doc, result = {}
var curFragment = result.cursors = document.createDocumentFragment()
var selFragment = result.selection = document.createDocumentFragment()
for (var i = 0; i < doc.sel.ranges.length; i++) {
if (primary === false && 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 (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 (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"
}
}
// 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
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)
}
iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
var leftPos = coords(from, "left"), rightPos, left, right
if (from == to) {
rightPos = leftPos
left = right = leftPos.left
} else {
rightPos = coords(to - 1, "right")
if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
left = leftPos.left
right = rightPos.right
}
if (fromArg == null && from == 0) { left = leftSide }
if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
add(left, leftPos.top, null, leftPos.bottom)
left = leftSide
if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
}
if (toArg == null && to == lineLen) { right = rightSide }
if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
{ start = leftPos }
if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
{ end = rightPos }
if (left < leftSide + 1) { left = leftSide }
add(left, rightPos.top, right - left, rightPos.bottom)
})
return {start: start, end: end}
}
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 () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
cm.options.cursorBlinkRate) }
else if (cm.options.cursorBlinkRate < 0)
{ display.cursorDiv.style.visibility = "hidden" }
}
function ensureFocus(cm) {
if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
}
function delayBlurEvent(cm) {
cm.state.delayingBlurEvent = true
setTimeout(function () { if (cm.state.delayingBlurEvent) {
cm.state.delayingBlurEvent = false
onBlur(cm)
} }, 100)
}
function onFocus(cm, e) {
if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
if (cm.options.readOnly == "nocursor") { return }
if (!cm.state.focused) {
signal(cm, "focus", cm, e)
cm.state.focused = true
addClass(cm.display.wrapper, "CodeMirror-focused")
// This test prevents this from firing when a context
// menu is closed (since the input reset would kill the
// select-all detection hack)
if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
cm.display.input.reset()
if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
}
cm.display.input.receivedFocus()
}
restartBlink(cm)
}
function onBlur(cm, e) {
if (cm.state.delayingBlurEvent) { return }
if (cm.state.focused) {
signal(cm, "blur", cm, e)
cm.state.focused = false
rmClass(cm.display.wrapper, "CodeMirror-focused")
}
clearInterval(cm.display.blinker)
setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
}
// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
var display = cm.display, view = display.view
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
var gutterW = display.gutters.offsetWidth, left = comp + "px"
for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
if (cm.options.fixedGutter) {
if (view[i].gutter)
{ view[i].gutter.style.left = left }
if (view[i].gutterBackground)
{ view[i].gutterBackground.style.left = left }
}
var align = view[i].alignable
if (align) { for (var j = 0; j < align.length; j++)
{ align[j].style.left = left } }
} }
if (cm.options.fixedGutter)
{ display.gutters.style.left = (comp + gutterW) + "px" }
}
// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
if (!cm.options.lineNumbers) { return false }
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
if (last.length != display.lineNumChars) {
var test = display.measure.appendChild(elt("div", [elt("div", last)],
"CodeMirror-linenumber CodeMirror-gutter-elt"))
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
display.lineGutter.style.width = ""
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
display.lineNumWidth = display.lineNumInnerWidth + padding
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
display.lineGutter.style.width = display.lineNumWidth + "px"
updateGutterSpace(cm)
return true
}
return false
}
// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
var display = cm.display
var prevBottom = display.lineDiv.offsetTop
for (var i = 0; i < display.view.length; i++) {
var cur = display.view[i], height = (void 0)
if (cur.hidden) { continue }
if (ie && ie_version < 8) {
var bot = cur.node.offsetTop + cur.node.offsetHeight
height = bot - prevBottom
prevBottom = bot
} else {
var box = cur.node.getBoundingClientRect()
height = box.bottom - box.top
}
var diff = cur.line.height - height
if (height < 2) { height = textHeight(display) }
if (diff > .001 || diff < -.001) {
updateLineHeight(cur.line, height)
updateWidgetHeight(cur.line)
if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
{ updateWidgetHeight(cur.rest[j]) } }
}
}
}
// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
{ line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
}
// 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)}
}
// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
cm.doc.scrollTop = val
if (!gecko) { updateDisplaySimple(cm, {top: val}) }
if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
cm.display.scrollbars.setScrollTop(val)
if (gecko) { updateDisplaySimple(cm) }
startWorker(cm, 100)
}
// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller) {
if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
cm.doc.scrollLeft = val
alignHorizontally(cm)
if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
cm.display.scrollbars.setScrollLeft(val)
}
// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.
var wheelSamples = 0;
var wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) { wheelPixelsPerUnit = -.53 }
else if (gecko) { wheelPixelsPerUnit = 15 }
else if (chrome) { wheelPixelsPerUnit = -.7 }
else if (safari) { wheelPixelsPerUnit = -1/3 }
function wheelEventDelta(e) {
var dx = e.wheelDeltaX, dy = e.wheelDeltaY
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
else if (dy == null) { dy = e.wheelDelta }
return {x: dx, y: dy}
}
function wheelEventPixels(e) {
var delta = wheelEventDelta(e)
delta.x *= wheelPixelsPerUnit
delta.y *= wheelPixelsPerUnit
return delta
}
function onScrollWheel(cm, e) {
var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
var display = cm.display, scroll = display.scroller
// Quit if there's nothing to scroll here
var canScrollX = scroll.scrollWidth > scroll.clientWidth
var canScrollY = scroll.scrollHeight > scroll.clientHeight
if (!(dx && canScrollX || dy && canScrollY)) { return }
// Webkit browsers on OS X abort momentum scrolls when the target
// of the scroll event is removed from the scrollable element.
// This hack (see related code in patchDisplay) makes sure the
// element is kept around.
if (dy && mac && webkit) {
outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
for (var i = 0; i < view.length; i++) {
if (view[i].node == cur) {
cm.display.currentWheelTarget = cur
break outer
}
}
}
}
// On some browsers, horizontal scrolling will cause redraws to
// happen before the gutter has been realigned, causing it to
// wriggle around in a most unseemly way. When we have an
// estimated pixels/delta value, we just handle horizontal
// scrolling entirely here. It'll be slightly off from native, but
// better than glitching out.
if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
if (dy && canScrollY)
{ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) }
setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)))
// Only prevent default scrolling if vertical scrolling is
// actually possible. Otherwise, it causes vertical scroll
// jitter on OSX trackpads when deltaX is small and deltaY
// is large (issue #3579)
if (!dy || (dy && canScrollY))
{ e_preventDefault(e) }
display.wheelStartX = null // Abort measurement, if in progress
return
}
// 'Project' the visible viewport to cover the area that is being
// scrolled into view (if we know enough to estimate it).
if (dy && wheelPixelsPerUnit != null) {
var pixels = dy * wheelPixelsPerUnit
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
updateDisplaySimple(cm, {top: top, bottom: bot})
}
if (wheelSamples < 20) {
if (display.wheelStartX == null) {
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
display.wheelDX = dx; display.wheelDY = dy
setTimeout(function () {
if (display.wheelStartX == null) { return }
var movedX = scroll.scrollLeft - display.wheelStartX
var movedY = scroll.scrollTop - display.wheelStartY
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
(movedX && display.wheelDX && movedX / display.wheelDX)
display.wheelStartX = display.wheelStartY = null
if (!sample) { return }
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
++wheelSamples
}, 200)
} else {
display.wheelDX += dx; display.wheelDY += dy
}
}
}
// SCROLLBARS
// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
var d = cm.display, gutterW = d.gutters.offsetWidth
var docH = Math.round(cm.doc.height + paddingVert(cm.display))
return {
clientHeight: d.scroller.clientHeight,
viewHeight: d.wrapper.clientHeight,
scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
viewWidth: d.wrapper.clientWidth,
barLeft: cm.options.fixedGutter ? gutterW : 0,
docHeight: docH,
scrollHeight: docH + scrollGap(cm) + d.barHeight,
nativeBarWidth: d.nativeBarWidth,
gutterWidth: gutterW
}
}
var NativeScrollbars = function(place, scroll, cm) {
this.cm = cm
var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
place(vert); place(horiz)
on(vert, "scroll", function () {
if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
})
on(horiz, "scroll", function () {
if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
})
this.checkedZeroWidth = false
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
};
NativeScrollbars.prototype.update = function (measure) {
var needsH = measure.scrollWidth > measure.clientWidth + 1
var needsV = measure.scrollHeight > measure.clientHeight + 1
var sWidth = measure.nativeBarWidth
if (needsV) {
this.vert.style.display = "block"
this.vert.style.bottom = needsH ? sWidth + "px" : "0"
var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
// A bug in IE8 can cause this value to be negative, so guard it.
this.vert.firstChild.style.height =
Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
} else {
this.vert.style.display = ""
this.vert.firstChild.style.height = "0"
}
if (needsH) {
this.horiz.style.display = "block"
this.horiz.style.right = needsV ? sWidth + "px" : "0"
this.horiz.style.left = measure.barLeft + "px"
var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
this.horiz.firstChild.style.width =
(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) }
};
NativeScrollbars.prototype.setScrollTop = function (pos) {
if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) }
};
NativeScrollbars.prototype.zeroWidthHack = function () {
var w = mac && !mac_geMountainLion ? "12px" : "18px"
this.horiz.style.height = this.vert.style.width = w
this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
this.disableHoriz = new Delayed
this.disableVert = new Delayed
};
NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay) {
bar.style.pointerEvents = "auto"
function maybeDisable() {
// To find out whether the scrollbar is still visible, we
// check whether the element under the pixel in the bottom
// left 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 = document.elementFromPoint(box.left + 1, box.bottom - 1)
if (elt != bar) { bar.style.pointerEvents = "none" }
else { delay.set(1000, maybeDisable) }
}
delay.set(1000, maybeDisable)
};
NativeScrollbars.prototype.clear = function () {
var parent = this.horiz.parentNode
parent.removeChild(this.horiz)
parent.removeChild(this.vert)
};
var NullScrollbars = function () {};
NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
NullScrollbars.prototype.setScrollLeft = function () {};
NullScrollbars.prototype.setScrollTop = function () {};
NullScrollbars.prototype.clear = function () {};
function updateScrollbars(cm, measure) {
if (!measure) { measure = measureForScrollbars(cm) }
var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
updateScrollbarsInner(cm, measure)
for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
{ updateHeightsInViewport(cm) }
updateScrollbarsInner(cm, measureForScrollbars(cm))
startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
}
}
// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbarsInner(cm, measure) {
var d = cm.display
var sizes = d.scrollbars.update(measure)
d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
if (sizes.right && sizes.bottom) {
d.scrollbarFiller.style.display = "block"
d.scrollbarFiller.style.height = sizes.bottom + "px"
d.scrollbarFiller.style.width = sizes.right + "px"
} else { d.scrollbarFiller.style.display = "" }
if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
d.gutterFiller.style.display = "block"
d.gutterFiller.style.height = sizes.bottom + "px"
d.gutterFiller.style.width = measure.gutterWidth + "px"
} else { d.gutterFiller.style.display = "" }
}
var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
function initScrollbars(cm) {
if (cm.display.scrollbars) {
cm.display.scrollbars.clear()
if (cm.display.scrollbars.addClass)
{ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
}
cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
// Prevent clicks in the scrollbars from killing focus
on(node, "mousedown", function () {
if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
})
node.setAttribute("cm-not-content", "true")
}, function (pos, axis) {
if (axis == "horizontal") { setScrollLeft(cm, pos) }
else { setScrollTop(cm, pos) }
}, cm)
if (cm.display.scrollbars.addClass)
{ addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
}
// 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, coords) {
if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
if (coords.top + box.top < 0) { doScroll = true }
else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
if (doScroll != null && !phantom) {
var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;"))
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 coords
for (var limit = 0; limit < 5; limit++) {
var changed = false
coords = cursorCoords(cm, pos)
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
Math.min(coords.top, endCoords.top) - margin,
Math.max(coords.left, endCoords.left),
Math.max(coords.bottom, endCoords.bottom) + margin)
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
if (scrollPos.scrollTop != null) {
setScrollTop(cm, scrollPos.scrollTop)
if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
}
if (scrollPos.scrollLeft != null) {
setScrollLeft(cm, scrollPos.scrollLeft)
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
}
if (!changed) { break }
}
return coords
}
// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, x1, y1, x2, y2) {
var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2)
if (scrollPos.scrollTop != null) { setScrollTop(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, x1, y1, x2, y2) {
var display = cm.display, snapMargin = textHeight(cm.display)
if (y1 < 0) { y1 = 0 }
var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
var screen = displayHeight(cm), result = {}
if (y2 - y1 > screen) { y2 = y1 + screen }
var docBottom = cm.doc.height + paddingVert(display)
var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin
if (y1 < screentop) {
result.scrollTop = atTop ? 0 : y1
} else if (y2 > screentop + screen) {
var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen)
if (newTop != screentop) { result.scrollTop = newTop }
}
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
var tooWide = x2 - x1 > screenw
if (tooWide) { x2 = x1 + screenw }
if (x1 < 10)
{ result.scrollLeft = 0 }
else if (x1 < screenleft)
{ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) }
else if (x2 > screenw + screenleft - 3)
{ result.scrollLeft = x2 + (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 addToScrollPos(cm, left, top) {
if (left != null || top != null) { resolveScrollToPos(cm) }
if (left != null)
{ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left }
if (top != null)
{ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top }
}
// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
resolveScrollToPos(cm)
var cur = cm.getCursor(), from = cur, to = cur
if (!cm.options.lineWrapping) {
from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur
to = Pos(cur.line, cur.ch + 1)
}
cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}
}
// 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)
var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
Math.min(from.top, to.top) - range.margin,
Math.max(from.right, to.right),
Math.max(from.bottom, to.bottom) + range.margin)
cm.scrollTo(sPos.scrollLeft, sPos.scrollTop)
}
}
// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.
var nextOpId = 0
// Start a new operation.
function startOperation(cm) {
cm.curOp = {
cm: cm,
viewChanged: false, // Flag that indicates that lines might need to be redrawn
startHeight: cm.doc.height, // Used to detect need to update scrollbar
forceUpdate: false, // Used to force a redraw
updateInput: null, // Whether to reset the input textarea
typing: false, // Whether this reset should be careful to leave existing text (for compositing)
changeObjs: null, // Accumulated changes, for firing change events
cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
selectionChanged: false, // Whether the selection needs to be redrawn
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
focus: false,
id: ++nextOpId // Unique ID
}
pushOperation(cm.curOp)
}
// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
var op = cm.curOp
finishOperation(op, function (group) {
for (var i = 0; i < group.ops.length; i++)
{ group.ops[i].cm.curOp = null }
endOperations(group)
})
}
// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
var ops = group.ops
for (var i = 0; i < ops.length; i++) // Read DOM
{ endOperation_R1(ops[i]) }
for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
{ endOperation_W1(ops[i$1]) }
for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
{ endOperation_R2(ops[i$2]) }
for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
{ endOperation_W2(ops[i$3]) }
for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
{ endOperation_finish(ops[i$4]) }
}
function endOperation_R1(op) {
var cm = op.cm, display = cm.display
maybeClipScrollbars(cm)
if (op.updateMaxLine) { findMaxLine(cm) }
op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
op.scrollToPos.to.line >= display.viewTo) ||
display.maxLineChanged && cm.options.lineWrapping
op.update = op.mustUpdate &&
new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
}
function endOperation_W1(op) {
op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
}
function endOperation_R2(op) {
var cm = op.cm, display = cm.display
if (op.updatedDisplay) { updateHeightsInViewport(cm) }
op.barMeasure = measureForScrollbars(cm)
// If the max line changed since it was last measured, measure it,
// and ensure the document's width matches it.
// updateDisplay_W2 will use these properties to do the actual resizing
if (display.maxLineChanged && !cm.options.lineWrapping) {
op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
cm.display.sizerWidth = op.adjustWidthTo
op.barMeasure.scrollWidth =
Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
}
if (op.updatedDisplay || op.selectionChanged)
{ op.preparedSelection = display.input.prepareSelection(op.focus) }
}
function endOperation_W2(op) {
var cm = op.cm
if (op.adjustWidthTo != null) {
cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
if (op.maxScrollLeft < cm.doc.scrollLeft)
{ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
cm.display.maxLineChanged = false
}
var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
if (op.preparedSelection)
{ cm.display.input.showSelection(op.preparedSelection, takeFocus) }
if (op.updatedDisplay || op.startHeight != cm.doc.height)
{ updateScrollbars(cm, op.barMeasure) }
if (op.updatedDisplay)
{ setDocumentHeight(cm, op.barMeasure) }
if (op.selectionChanged) { restartBlink(cm) }
if (cm.state.focused && op.updateInput)
{ cm.display.input.reset(op.typing) }
if (takeFocus) { ensureFocus(op.cm) }
}
function endOperation_finish(op) {
var cm = op.cm, display = cm.display, doc = cm.doc
if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
// Abort mouse wheel delta measurement, when scrolling explicitly
if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
{ display.wheelStartX = display.wheelStartY = null }
// Propagate the scroll position to the actual DOM scroller
if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop))
display.scrollbars.setScrollTop(doc.scrollTop)
display.scroller.scrollTop = doc.scrollTop
}
if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft))
display.scrollbars.setScrollLeft(doc.scrollLeft)
display.scroller.scrollLeft = doc.scrollLeft
alignHorizontally(cm)
}
// If we need to scroll a specific position into view, do so.
if (op.scrollToPos) {
var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) }
}
// Fire events for markers that are hidden/unidden by editing or
// undoing
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
if (hidden) { for (var i = 0; i < hidden.length; ++i)
{ if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
{ if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
if (display.wrapper.offsetHeight)
{ doc.scrollTop = cm.display.scroller.scrollTop }
// Fire change events, and delayed event handlers
if (op.changeObjs)
{ signal(cm, "changes", cm, op.changeObjs) }
if (op.update)
{ op.update.finish() }
}
// Run the given function in an operation
function runInOp(cm, f) {
if (cm.curOp) { return f() }
startOperation(cm)
try { return f() }
finally { endOperation(cm) }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
return function() {
if (cm.curOp) { return f.apply(cm, arguments) }
startOperation(cm)
try { return f.apply(cm, arguments) }
finally { endOperation(cm) }
}
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
return function() {
if (this.curOp) { return f.apply(this, arguments) }
startOperation(this)
try { return f.apply(this, arguments) }
finally { endOperation(this) }
}
}
function docMethodOp(f) {
return function() {
var cm = this.cm
if (!cm || cm.curOp) { return f.apply(this, arguments) }
startOperation(cm)
try { return f.apply(this, arguments) }
finally { endOperation(cm) }
}
}
// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
if (from == null) { from = cm.doc.first }
if (to == null) { to = cm.doc.first + cm.doc.size }
if (!lendiff) { lendiff = 0 }
var display = cm.display
if (lendiff && to < display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers > from))
{ display.updateLineNumbers = from }
cm.curOp.viewChanged = true
if (from >= display.viewTo) { // Change after
if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
{ resetView(cm) }
} else if (to <= display.viewFrom) { // Change before
if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
resetView(cm)
} else {
display.viewFrom += lendiff
display.viewTo += lendiff
}
} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
resetView(cm)
} else if (from <= display.viewFrom) { // Top overlap
var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
if (cut) {
display.view = display.view.slice(cut.index)
display.viewFrom = cut.lineN
display.viewTo += lendiff
} else {
resetView(cm)
}
} else if (to >= display.viewTo) { // Bottom overlap
var cut$1 = viewCuttingPoint(cm, from, from, -1)
if (cut$1) {
display.view = display.view.slice(0, cut$1.index)
display.viewTo = cut$1.lineN
} else {
resetView(cm)
}
} else { // Gap in the middle
var cutTop = viewCuttingPoint(cm, from, from, -1)
var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
if (cutTop && cutBot) {
display.view = display.view.slice(0, cutTop.index)
.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
.concat(display.view.slice(cutBot.index))
display.viewTo += lendiff
} else {
resetView(cm)
}
}
var ext = display.externalMeasured
if (ext) {
if (to < ext.lineN)
{ ext.lineN += lendiff }
else if (from < ext.lineN + ext.size)
{ display.externalMeasured = null }
}
}
// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
cm.curOp.viewChanged = true
var display = cm.display, ext = cm.display.externalMeasured
if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
{ display.externalMeasured = null }
if (line < display.viewFrom || line >= display.viewTo) { return }
var lineView = display.view[findViewIndex(cm, line)]
if (lineView.node == null) { return }
var arr = lineView.changes || (lineView.changes = [])
if (indexOf(arr, type) == -1) { arr.push(type) }
}
// Clear the view.
function resetView(cm) {
cm.display.viewFrom = cm.display.viewTo = cm.doc.first
cm.display.view = []
cm.display.viewOffset = 0
}
function viewCuttingPoint(cm, oldN, newN, dir) {
var index = findViewIndex(cm, oldN), diff, view = cm.display.view
if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
{ return {index: index, lineN: newN} }
var n = cm.display.viewFrom
for (var i = 0; i < index; i++)
{ n += view[i].size }
if (n != oldN) {
if (dir > 0) {
if (index == view.length - 1) { return null }
diff = (n + view[index].size) - oldN
index++
} else {
diff = n - oldN
}
oldN += diff; newN += diff
}
while (visualLineNo(cm.doc, newN) != newN) {
if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
newN += dir * view[index - (dir < 0 ? 1 : 0)].size
index += dir
}
return {index: index, lineN: newN}
}
// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
var display = cm.display, view = display.view
if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
display.view = buildViewArray(cm, from, to)
display.viewFrom = from
} else {
if (display.viewFrom > from)
{ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
else if (display.viewFrom < from)
{ display.view = display.view.slice(findViewIndex(cm, from)) }
display.viewFrom = from
if (display.viewTo < to)
{ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
else if (display.viewTo > to)
{ display.view = display.view.slice(0, findViewIndex(cm, to)) }
}
display.viewTo = to
}
// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
var view = cm.display.view, dirty = 0
for (var i = 0; i < view.length; i++) {
var lineView = view[i]
if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
}
return dirty
}
// HIGHLIGHT WORKER
function startWorker(cm, time) {
if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
{ cm.state.highlight.set(time, bind(highlightWorker, cm)) }
}
function highlightWorker(cm) {
var doc = cm.doc
if (doc.frontier < doc.first) { doc.frontier = doc.first }
if (doc.frontier >= cm.display.viewTo) { return }
var end = +new Date + cm.options.workTime
var state = copyState(doc.mode, getStateBefore(cm, doc.frontier))
var changedLines = []
doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
if (doc.frontier >= cm.display.viewFrom) { // Visible
var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength
var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true)
line.styles = highlighted.styles
var oldCls = line.styleClasses, newCls = highlighted.classes
if (newCls) { line.styleClasses = newCls }
else if (oldCls) { line.styleClasses = null }
var ischange = !oldStyles || oldStyles.length != line.styles.length ||
oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
if (ischange) { changedLines.push(doc.frontier) }
line.stateAfter = tooLong ? state : copyState(doc.mode, state)
} else {
if (line.text.length <= cm.options.maxHighlightLength)
{ processLine(cm, line.text, state) }
line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null
}
++doc.frontier
if (+new Date > end) {
startWorker(cm, cm.options.workDelay)
return true
}
})
if (changedLines.length) { runInOp(cm, function () {
for (var i = 0; i < changedLines.length; i++)
{ regLineChange(cm, changedLines[i], "text") }
}) }
}
// DISPLAY DRAWING
var DisplayUpdate = function(cm, viewport, force) {
var display = cm.display
this.viewport = viewport
// Store some values that we'll need later (but don't want to force a relayout for)
this.visible = visibleLines(display, cm.doc, viewport)
this.editorIsHidden = !display.wrapper.offsetWidth
this.wrapperHeight = display.wrapper.clientHeight
this.wrapperWidth = display.wrapper.clientWidth
this.oldDisplayWidth = displayWidth(cm)
this.force = force
this.dims = getDimensions(cm)
this.events = []
};
DisplayUpdate.prototype.signal = function (emitter, type) {
if (hasHandler(emitter, type))
{ this.events.push(arguments) }
};
DisplayUpdate.prototype.finish = function () {
var this$1 = this;
for (var i = 0; i < this.events.length; i++)
{ signal.apply(null, this$1.events[i]) }
};
function maybeClipScrollbars(cm) {
var display = cm.display
if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
display.heightForcer.style.height = scrollGap(cm) + "px"
display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
display.scrollbarsClipped = true
}
}
// 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 focused = activeElt()
if (toUpdate > 4) { display.lineDiv.style.display = "none" }
patchDisplay(cm, display.updateLineNumbers, update.dims)
if (toUpdate > 4) { display.lineDiv.style.display = "" }
display.renderedView = display.view
// There might have been a widget with a focused element that got
// hidden or updated, if so re-focus it.
if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() }
// Prevent selection and cursors from interfering with the scroll
// width and height.
removeChildren(display.cursorDiv)
removeChildren(display.selectionDiv)
display.gutters.style.height = display.sizer.style.minHeight = 0
if (different) {
display.lastWrapHeight = update.wrapperHeight
display.lastWrapWidth = update.wrapperWidth
startWorker(cm, 400)
}
display.updateLineNumbers = null
return true
}
function postUpdateDisplay(cm, update) {
var viewport = update.viewport
for (var first = true;; first = false) {
if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
// Clip forced viewport to actual scrollable area.
if (viewport && viewport.top != null)
{ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
// Updated line heights might result in the drawn area not
// actually covering the viewport. Keep looping until it does.
update.visible = visibleLines(cm.display, cm.doc, viewport)
if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
{ break }
}
if (!updateDisplayIfNeeded(cm, update)) { break }
updateHeightsInViewport(cm)
var barMeasure = measureForScrollbars(cm)
updateSelection(cm)
updateScrollbars(cm, barMeasure)
setDocumentHeight(cm, barMeasure)
}
update.signal(cm, "update", cm)
if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
}
}
function updateDisplaySimple(cm, viewport) {
var update = new DisplayUpdate(cm, viewport)
if (updateDisplayIfNeeded(cm, update)) {
updateHeightsInViewport(cm)
postUpdateDisplay(cm, update)
var barMeasure = measureForScrollbars(cm)
updateSelection(cm)
updateScrollbars(cm, barMeasure)
setDocumentHeight(cm, barMeasure)
update.finish()
}
}
// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
var display = cm.display, lineNumbers = cm.options.lineNumbers
var container = display.lineDiv, cur = container.firstChild
function rm(node) {
var next = node.nextSibling
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
{ node.style.display = "none" }
else
{ node.parentNode.removeChild(node) }
return next
}
var view = display.view, lineN = display.viewFrom
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (var i = 0; i < view.length; i++) {
var lineView = view[i]
if (lineView.hidden) {
} else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
var node = buildLineElement(cm, lineView, lineN, dims)
container.insertBefore(node, cur)
} else { // Already drawn
while (cur != lineView.node) { cur = rm(cur) }
var updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
updateLineForChanges(cm, lineView, lineN, dims)
}
if (updateNumber) {
removeChildren(lineView.lineNumber)
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
}
cur = lineView.node.nextSibling
}
lineN += lineView.size
}
while (cur) { cur = rm(cur) }
}
function updateGutterSpace(cm) {
var width = cm.display.gutters.offsetWidth
cm.display.sizer.style.marginLeft = width + "px"
}
function setDocumentHeight(cm, measure) {
cm.display.sizer.style.minHeight = measure.docHeight + "px"
cm.display.heightForcer.style.top = measure.docHeight + "px"
cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
}
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function updateGutters(cm) {
var gutters = cm.display.gutters, specs = cm.options.gutters
removeChildren(gutters)
var i = 0
for (; i < specs.length; ++i) {
var gutterClass = specs[i]
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
if (gutterClass == "CodeMirror-linenumbers") {
cm.display.lineGutter = gElt
gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
}
}
gutters.style.display = i ? "" : "none"
updateGutterSpace(cm)
}
// Make sure the gutters options contains the element
// "CodeMirror-linenumbers" when the lineNumbers option is true.
function setGuttersForLineNumbers(options) {
var found = indexOf(options.gutters, "CodeMirror-linenumbers")
if (found == -1 && options.lineNumbers) {
options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
} else if (found > -1 && !options.lineNumbers) {
options.gutters = options.gutters.slice(0)
options.gutters.splice(found, 1)
}
}
// 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).
function Selection(ranges, primIndex) {
this.ranges = ranges
this.primIndex = primIndex
}
Selection.prototype = {
primary: function() { return this.ranges[this.primIndex] },
equals: function(other) {
var this$1 = this;
if (other == this) { return true }
if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
for (var i = 0; i < this.ranges.length; i++) {
var here = this$1.ranges[i], there = other.ranges[i]
if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false }
}
return true
},
deepCopy: function() {
var this$1 = this;
var out = []
for (var i = 0; i < this.ranges.length; i++)
{ out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
return new Selection(out, this.primIndex)
},
somethingSelected: function() {
var this$1 = this;
for (var i = 0; i < this.ranges.length; i++)
{ if (!this$1.ranges[i].empty()) { return true } }
return false
},
contains: function(pos, end) {
var this$1 = this;
if (!end) { end = pos }
for (var i = 0; i < this.ranges.length; i++) {
var range = this$1.ranges[i]
if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
{ return i }
}
return -1
}
}
function Range(anchor, head) {
this.anchor = anchor; this.head = head
}
Range.prototype = {
from: function() { return minPos(this.anchor, this.head) },
to: function() { return maxPos(this.anchor, this.head) },
empty: function() {
return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch
}
}
// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(ranges, primIndex) {
var prim = ranges[primIndex]
ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
primIndex = indexOf(ranges, prim)
for (var i = 1; i < ranges.length; i++) {
var cur = ranges[i], prev = ranges[i - 1]
if (cmp(prev.to(), cur.from()) >= 0) {
var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
if (i <= primIndex) { --primIndex }
ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
}
}
return new Selection(ranges, primIndex)
}
function simpleSelection(anchor, head) {
return new Selection([new Range(anchor, head || anchor)], 0)
}
// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
function changeEnd(change) {
if (!change.text) { return change.to }
return Pos(change.from.line + change.text.length - 1,
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
}
// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
if (cmp(pos, change.from) < 0) { return pos }
if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
return Pos(line, ch)
}
function computeSelAfterChange(doc, change) {
var out = []
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i]
out.push(new Range(adjustForChange(range.anchor, change),
adjustForChange(range.head, change)))
}
return normalizeSelection(out, doc.sel.primIndex)
}
function offsetPos(pos, old, nw) {
if (pos.line == old.line)
{ return Pos(nw.line, pos.ch - old.ch + nw.ch) }
else
{ return Pos(nw.line + (pos.line - old.line), pos.ch) }
}
// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
var out = []
var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
for (var i = 0; i < changes.length; i++) {
var change = changes[i]
var from = offsetPos(change.from, oldPrev, newPrev)
var to = offsetPos(changeEnd(change), oldPrev, newPrev)
oldPrev = change.to
newPrev = to
if (hint == "around") {
var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
out[i] = new Range(inv ? to : from, inv ? from : to)
} else {
out[i] = new Range(from, from)
}
}
return new Selection(out, doc.sel.primIndex)
}
// Used to get the editor into a consistent state again when options change.
function loadMode(cm) {
cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
resetModeState(cm)
}
function resetModeState(cm) {
cm.doc.iter(function (line) {
if (line.stateAfter) { line.stateAfter = null }
if (line.styles) { line.styles = null }
})
cm.doc.frontier = 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)
if (!cm.options.lineWrapping) { findMaxLine(cm) }
cm.options.mode = doc.modeOption
regChange(cm)
}
function History(startGen) {
// Arrays of change events and selections. Doing something adds an
// event to done and clears undo. Undoing moves events from done
// to undone, redoing moves them in the other direction.
this.done = []; this.undone = []
this.undoDepth = Infinity
// Used to track when changes can be merged into a single undo
// event
this.lastModTime = this.lastSelTime = 0
this.lastOp = this.lastSelOp = null
this.lastOrigin = this.lastSelOrigin = null
// Used by the isClean() method
this.generation = this.maxGeneration = startGen || 1
}
// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
return histChange
}
// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array)
if (last.ranges) { array.pop() }
else { break }
}
}
// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done)
return lst(hist.done)
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done)
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop()
return lst(hist.done)
}
}
// Register a change in the history. Merges changes that are within
// a single operation, or are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
var hist = doc.history
hist.undone.length = 0
var time = +new Date, cur
var last
if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event
last = lst(cur.changes)
if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
// Optimized case for simple insertion -- don't want to add
// new changesets for every character typed
last.to = changeEnd(change)
} else {
// Add new sub-event
cur.changes.push(historyChangeFromChange(doc, change))
}
} else {
// Can not be merged, start a new event.
var before = lst(hist.done)
if (!before || !before.ranges)
{ pushSelectionToHistory(doc.sel, hist.done) }
cur = {changes: [historyChangeFromChange(doc, change)],
generation: hist.generation}
hist.done.push(cur)
while (hist.done.length > hist.undoDepth) {
hist.done.shift()
if (!hist.done[0].ranges) { hist.done.shift() }
}
}
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(doc, range, head, other) {
if (doc.cm && doc.cm.display.shift || doc.extend) {
var anchor = range.anchor
if (other) {
var posBefore = cmp(head, anchor) < 0
if (posBefore != (cmp(other, anchor) < 0)) {
anchor = head
head = other
} else if (posBefore != (cmp(head, other) < 0)) {
head = other
}
}
return new Range(anchor, head)
} else {
return new Range(other || head, head)
}
}
// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options)
}
// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
var out = []
for (var i = 0; i < doc.sel.ranges.length; i++)
{ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) }
var newSel = normalizeSelection(out, doc.sel.primIndex)
setSelection(doc, newSel, options)
}
// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
var ranges = doc.sel.ranges.slice(0)
ranges[i] = range
setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
}
// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
setSelection(doc, simpleSelection(anchor, head), options)
}
// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel, options) {
var obj = {
ranges: sel.ranges,
update: function(ranges) {
var this$1 = this;
this.ranges = []
for (var i = 0; i < ranges.length; i++)
{ this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
clipPos(doc, ranges[i].head)) }
},
origin: options && options.origin
}
signal(doc, "beforeSelectionChange", doc, obj)
if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
else { return sel }
}
function setSelectionReplaceHistory(doc, sel, options) {
var done = doc.history.done, last = lst(done)
if (last && last.ranges) {
done[done.length - 1] = sel
setSelectionNoUndo(doc, sel, options)
} else {
setSelection(doc, sel, options)
}
}
// Set a new selection.
function setSelection(doc, sel, options) {
setSelectionNoUndo(doc, sel, options)
addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
}
function setSelectionNoUndo(doc, sel, options) {
if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
{ sel = filterSelectionChange(doc, sel, options) }
var bias = options && options.bias ||
(cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
if (!(options && options.scroll === false) && doc.cm)
{ ensureCursorVisible(doc.cm) }
}
function setSelectionInner(doc, sel) {
if (sel.equals(doc.sel)) { return }
doc.sel = sel
if (doc.cm) {
doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
signalCursorActivity(doc.cm)
}
signalLater(doc, "cursorActivity", doc)
}
// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll)
}
// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
var out
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i]
var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) { out = sel.ranges.slice(0, i) }
out[i] = new Range(newAnchor, newHead)
}
}
return out ? normalizeSelection(out, sel.primIndex) : sel
}
function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
var line = getLine(doc, pos.line)
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter")
if (m.explicitlyCleared) {
if (!line.markedSpans) { break }
else {--i; continue}
}
}
if (!m.atomic) { continue }
if (oldPos) {
var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
{ near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
{ return skipAtomicInner(doc, near, pos, dir, mayClear) }
}
var far = m.find(dir < 0 ? -1 : 1)
if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
{ far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
}
} }
return pos
}
// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, oldPos, bias, mayClear) {
var dir = bias || 1
var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
if (!found) {
doc.cantEdit = true
return Pos(doc.first, 0)
}
return found
}
function movePos(doc, pos, dir, line) {
if (dir < 0 && pos.ch == 0) {
if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
else { return null }
} else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
else { return null }
} else {
return new Pos(pos.line, pos.ch + dir)
}
}
function selectAll(cm) {
cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
}
// UPDATING
// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
var obj = {
canceled: false,
from: change.from,
to: change.to,
text: change.text,
origin: change.origin,
cancel: function () { return obj.canceled = true; }
}
if (update) { obj.update = function (from, to, text, origin) {
if (from) { obj.from = clipPos(doc, from) }
if (to) { obj.to = clipPos(doc, to) }
if (text) { obj.text = text }
if (origin !== undefined) { obj.origin = origin }
} }
signal(doc, "beforeChange", doc, obj)
if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
if (obj.canceled) { return null }
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
}
// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
if (doc.cm) {
if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
if (doc.cm.state.suppressEdits) { return }
}
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
change = filterChange(doc, change, true)
if (!change) { return }
}
// Possibly split or suppress the update based on the presence
// of read-only spans in its range.
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
if (split) {
for (var i = split.length - 1; i >= 0; --i)
{ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) }
} 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) {
if (doc.cm && doc.cm.state.suppressEdits && !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 { break }
}
// Build up a reverse change object to add to the opposite history
// stack (redo when undoing, and vice versa).
var antiChanges = []
pushSelectionToHistory(selAfter, dest)
dest.push({changes: antiChanges, generation: hist.generation})
hist.generation = event.generation || ++hist.maxGeneration
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
var loop = function ( i ) {
var change = event.changes[i]
change.origin = type
if (filter && !filterChange(doc, change, false)) {
source.length = 0
return {}
}
antiChanges.push(historyChangeFromChange(doc, change))
var after = i ? computeSelAfterChange(doc, change) : lst(source)
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
var rebased = []
// Propagate to the linked documents
linkedDocs(doc, function (doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change)
rebased.push(doc.history)
}
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
})
};
for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
var returned = loop( i$1 );
if ( returned ) return returned.v;
}
}
// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
if (distance == 0) { return }
doc.first += distance
doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
Pos(range.anchor.line + distance, range.anchor.ch),
Pos(range.head.line + distance, range.head.ch)
); }), doc.sel.primIndex)
if (doc.cm) {
regChange(doc.cm, doc.first, doc.first - distance, distance)
for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
{ regLineChange(doc.cm, l, "gutter") }
}
}
// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
if (doc.cm && !doc.cm.curOp)
{ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
if (change.to.line < doc.first) {
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
return
}
if (change.from.line > doc.lastLine()) { return }
// Clip the change to the size of this doc
if (change.from.line < doc.first) {
var shift = change.text.length - 1 - (doc.first - change.from.line)
shiftDoc(doc, shift)
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
text: [lst(change.text)], origin: change.origin}
}
var last = doc.lastLine()
if (change.to.line > last) {
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
text: [change.text[0]], origin: change.origin}
}
change.removed = getBetween(doc, change.from, change.to)
if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
else { updateDoc(doc, change, spans) }
setSelectionNoUndo(doc, selAfter, sel_dontScroll)
}
// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
var doc = cm.doc, display = cm.display, from = change.from, to = change.to
var recomputeMaxLength = false, checkWidthStart = from.line
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
doc.iter(checkWidthStart, to.line + 1, function (line) {
if (line == display.maxLine) {
recomputeMaxLength = true
return true
}
})
}
if (doc.sel.contains(change.from, change.to) > -1)
{ signalCursorActivity(cm) }
updateDoc(doc, change, spans, estimateHeight(cm))
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
var len = lineLength(line)
if (len > display.maxLineLength) {
display.maxLine = line
display.maxLineLength = len
display.maxLineChanged = true
recomputeMaxLength = false
}
})
if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
}
// Adjust frontier, schedule worker
doc.frontier = Math.min(doc.frontier, from.line)
startWorker(cm, 400)
var lendiff = change.text.length - (to.line - from.line) - 1
// Remember that these lines changed, for updating the display
if (change.full)
{ regChange(cm) }
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
{ regLineChange(cm, from.line, "text") }
else
{ regChange(cm, from.line, to.line + 1, lendiff) }
var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
if (changeHandler || changesHandler) {
var obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
}
if (changeHandler) { signalLater(cm, "change", cm, obj) }
if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
}
cm.display.selForContextMenu = null
}
function replaceRange(doc, code, from, to, origin) {
if (!to) { to = from }
if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp }
if (typeof code == "string") { code = doc.splitLines(code) }
makeChange(doc, {from: from, to: to, text: code, origin: origin})
}
// Rebasing/resetting history to deal with externally-sourced changes
function rebaseHistSelSingle(pos, from, to, diff) {
if (to < pos.line) {
pos.line += diff
} else if (from < pos.line) {
pos.line = from
pos.ch = 0
}
}
// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
for (var i = 0; i < array.length; ++i) {
var sub = array[i], ok = true
if (sub.ranges) {
if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
for (var j = 0; j < sub.ranges.length; j++) {
rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
}
continue
}
for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
var cur = sub.changes[j$1]
if (to < cur.from.line) {
cur.from = Pos(cur.from.line + diff, cur.from.ch)
cur.to = Pos(cur.to.line + diff, cur.to.ch)
} else if (from <= cur.to.line) {
ok = false
break
}
}
if (!ok) {
array.splice(0, i + 1)
i = 0
}
}
}
function rebaseHist(hist, change) {
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
rebaseHistArray(hist.done, from, to, diff)
rebaseHistArray(hist.undone, from, to, diff)
}
// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(doc, handle, changeType, op) {
var no = handle, line = handle
if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
else { no = lineNo(handle) }
if (no == null) { return null }
if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
return line
}
// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
function LeafChunk(lines) {
var this$1 = this;
this.lines = lines
this.parent = null
var height = 0
for (var i = 0; i < lines.length; ++i) {
lines[i].parent = this$1
height += lines[i].height
}
this.height = height
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length },
// Remove the n lines at offset 'at'.
removeInner: function(at, n) {
var this$1 = this;
for (var i = at, e = at + n; i < e; ++i) {
var line = this$1.lines[i]
this$1.height -= line.height
cleanUpLine(line)
signalLater(line, "delete")
}
this.lines.splice(at, n)
},
// Helper used to collapse a small branch into a single leaf.
collapse: function(lines) {
lines.push.apply(lines, this.lines)
},
// Insert the given array of lines at offset 'at', count them as
// having the given height.
insertInner: function(at, lines, height) {
var this$1 = this;
this.height += height
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
},
// Used to iterate over a part of the tree.
iterN: function(at, n, op) {
var this$1 = this;
for (var e = at + n; at < e; ++at)
{ if (op(this$1.lines[at])) { return true } }
}
}
function BranchChunk(children) {
var this$1 = this;
this.children = children
var size = 0, height = 0
for (var i = 0; i < children.length; ++i) {
var ch = children[i]
size += ch.chunkSize(); height += ch.height
ch.parent = this$1
}
this.size = size
this.height = height
this.parent = null
}
BranchChunk.prototype = {
chunkSize: function() { return this.size },
removeInner: function(at, n) {
var this$1 = this;
this.size -= n
for (var i = 0; i < this.children.length; ++i) {
var child = this$1.children[i], sz = child.chunkSize()
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height
child.removeInner(at, rm)
this$1.height -= oldHeight - child.height
if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
if ((n -= rm) == 0) { break }
at = 0
} else { at -= sz }
}
// If the result is smaller than 25 lines, ensure that it is a
// single leaf node.
if (this.size - n < 25 &&
(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
var lines = []
this.collapse(lines)
this.children = [new LeafChunk(lines)]
this.children[0].parent = this
}
},
collapse: function(lines) {
var this$1 = this;
for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
},
insertInner: function(at, lines, height) {
var this$1 = this;
this.size += lines.length
this.height += height
for (var i = 0; i < this.children.length; ++i) {
var child = this$1.children[i], sz = child.chunkSize()
if (at <= sz) {
child.insertInner(at, lines, height)
if (child.lines && child.lines.length > 50) {
// To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
// Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
var remaining = child.lines.length % 25 + 25
for (var pos = remaining; pos < child.lines.length;) {
var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
child.height -= leaf.height
this$1.children.splice(++i, 0, leaf)
leaf.parent = this$1
}
child.lines = child.lines.slice(0, remaining)
this$1.maybeSpill()
}
break
}
at -= sz
}
},
// When a node has grown, check whether it should be split.
maybeSpill: function() {
if (this.children.length <= 10) { return }
var me = this
do {
var spilled = me.children.splice(me.children.length - 5, 5)
var sibling = new BranchChunk(spilled)
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children)
copy.parent = me
me.children = [copy, sibling]
me = copy
} else {
me.size -= sibling.size
me.height -= sibling.height
var myIndex = indexOf(me.parent.children, me)
me.parent.children.splice(myIndex + 1, 0, sibling)
}
sibling.parent = me.parent
} while (me.children.length > 10)
me.parent.maybeSpill()
},
iterN: function(at, n, op) {
var this$1 = this;
for (var i = 0; i < this.children.length; ++i) {
var child = this$1.children[i], sz = child.chunkSize()
if (at < sz) {
var used = Math.min(n, sz - at)
if (child.iterN(at, used, op)) { return true }
if ((n -= used) == 0) { break }
at = 0
} else { at -= sz }
}
}
}
// Line widgets are block elements displayed above or below a line.
function LineWidget(doc, node, options) {
var this$1 = this;
if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
{ this$1[opt] = options[opt] } } }
this.doc = doc
this.node = node
}
eventMixin(LineWidget)
function adjustScrollWhenAboveVisible(cm, line, diff) {
if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
{ addToScrollPos(cm, null, diff) }
}
LineWidget.prototype.clear = function() {
var this$1 = this;
var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
if (no == null || !ws) { return }
for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
if (!ws.length) { line.widgets = null }
var height = widgetHeight(this)
updateLineHeight(line, Math.max(0, line.height - height))
if (cm) { runInOp(cm, function () {
adjustScrollWhenAboveVisible(cm, line, -height)
regLineChange(cm, no, "widget")
}) }
}
LineWidget.prototype.changed = function() {
var oldH = this.height, cm = this.doc.cm, line = this.line
this.height = null
var diff = widgetHeight(this) - oldH
if (!diff) { return }
updateLineHeight(line, line.height + diff)
if (cm) { runInOp(cm, function () {
cm.curOp.forceUpdate = true
adjustScrollWhenAboveVisible(cm, line, diff)
}) }
}
function addLineWidget(doc, handle, node, options) {
var widget = new LineWidget(doc, node, options)
var cm = doc.cm
if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
changeLine(doc, handle, "widget", function (line) {
var widgets = line.widgets || (line.widgets = [])
if (widget.insertAt == null) { widgets.push(widget) }
else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
widget.line = line
if (cm && !lineIsHidden(doc, line)) {
var aboveVisible = heightAtLine(line) < doc.scrollTop
updateLineHeight(line, line.height + widgetHeight(widget))
if (aboveVisible) { addToScrollPos(cm, null, widget.height) }
cm.curOp.forceUpdate = true
}
return true
})
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
function TextMarker(doc, type) {
this.lines = []
this.type = type
this.doc = doc
this.id = ++nextMarkerId
}
eventMixin(TextMarker)
// Clear the marker.
TextMarker.prototype.clear = function() {
var this$1 = this;
if (this.explicitlyCleared) { return }
var cm = this.doc.cm, withOp = cm && !cm.curOp
if (withOp) { startOperation(cm) }
if (hasHandler(this, "clear")) {
var found = this.find()
if (found) { signalLater(this, "clear", found.from, found.to) }
}
var min = null, max = null
for (var i = 0; i < this.lines.length; ++i) {
var line = this$1.lines[i]
var span = getMarkedSpanFor(line.markedSpans, this$1)
if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
else if (cm) {
if (span.to != null) { max = lineNo(line) }
if (span.from != null) { min = lineNo(line) }
}
line.markedSpans = removeMarkedSpan(line.markedSpans, span)
if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
{ updateLineHeight(line, textHeight(cm.display)) }
}
if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
if (len > cm.display.maxLineLength) {
cm.display.maxLine = visual
cm.display.maxLineLength = len
cm.display.maxLineChanged = true
}
} }
if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
this.lines.length = 0
this.explicitlyCleared = true
if (this.atomic && this.doc.cantEdit) {
this.doc.cantEdit = false
if (cm) { reCheckSelection(cm.doc) }
}
if (cm) { signalLater(cm, "markerCleared", cm, this) }
if (withOp) { endOperation(cm) }
if (this.parent) { this.parent.clear() }
}
// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function(side, lineObj) {
var this$1 = this;
if (side == null && this.type == "bookmark") { side = 1 }
var from, to
for (var i = 0; i < this.lines.length; ++i) {
var line = this$1.lines[i]
var span = getMarkedSpanFor(line.markedSpans, this$1)
if (span.from != null) {
from = Pos(lineObj ? line : lineNo(line), span.from)
if (side == -1) { return from }
}
if (span.to != null) {
to = Pos(lineObj ? line : lineNo(line), span.to)
if (side == 1) { return to }
}
}
return from && {from: from, to: to}
}
// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function() {
var 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) }
}
})
}
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)
}
}
// 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 = elt("span", [marker.replacedWith], "CodeMirror-widget")
marker.widgetNode.setAttribute("role", "presentation") // hide from accessibility tree
if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
if (options.insertLeft) { marker.widgetNode.insertLeft = true }
}
if (marker.collapsed) {
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
{ throw new Error("Inserting collapsed marker partially overlapping an existing one") }
seeCollapsedSpans()
}
if (marker.addToHistory)
{ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
var curLine = from.line, cm = doc.cm, updateMaxLine
doc.iter(curLine, to.line + 1, function (line) {
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
{ updateMaxLine = true }
if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
addMarkedSpan(line, new MarkedSpan(marker,
curLine == from.line ? from.ch : null,
curLine == to.line ? to.ch : null))
++curLine
})
// lineIsHidden depends on the presence of the spans, so needs a second pass
if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
}) }
if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
if (marker.readOnly) {
seeReadOnlySpans()
if (doc.history.done.length || doc.history.undone.length)
{ doc.clearHistory() }
}
if (marker.collapsed) {
marker.id = ++nextMarkerId
marker.atomic = true
}
if (cm) {
// Sync editor state
if (updateMaxLine) { cm.curOp.updateMaxLine = true }
if (marker.collapsed)
{ regChange(cm, from.line, to.line + 1) }
else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
{ for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
if (marker.atomic) { reCheckSelection(cm.doc) }
signalLater(cm, "markerAdded", cm, marker)
}
return marker
}
// SHARED TEXTMARKERS
// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
function SharedTextMarker(markers, primary) {
var this$1 = this;
this.markers = markers
this.primary = primary
for (var i = 0; i < markers.length; ++i)
{ markers[i].parent = this$1 }
}
eventMixin(SharedTextMarker)
SharedTextMarker.prototype.clear = function() {
var this$1 = this;
if (this.explicitlyCleared) { return }
this.explicitlyCleared = true
for (var i = 0; i < this.markers.length; ++i)
{ this$1.markers[i].clear() }
signalLater(this, "clear")
}
SharedTextMarker.prototype.find = function(side, lineObj) {
return this.primary.find(side, lineObj)
}
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) {
if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) }
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.frontier = firstLine
var start = Pos(firstLine, 0)
this.sel = simpleSelection(start)
this.history = new History(null)
this.id = ++nextDocId
this.modeOption = mode
this.lineSep = lineSep
this.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)
setSelection(this, simpleSelection(top))
}),
replaceRange: function(code, from, to, origin) {
from = clipPos(this, from)
to = to ? clipPos(this, to) : from
replaceRange(this, code, from, to, origin)
},
getRange: function(from, to, lineSep) {
var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
if (lineSep === false) { return lines }
return lines.join(lineSep || this.lineSeparator())
},
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
getLineNumber: function(line) {return lineNo(line)},
getLineHandleVisualStart: function(line) {
if (typeof line == "number") { line = getLine(this, line) }
return visualLine(line)
},
lineCount: function() {return this.size},
firstLine: function() {return this.first},
lastLine: function() {return this.first + this.size - 1},
clipPos: function(pos) {return clipPos(this, pos)},
getCursor: function(start) {
var range = 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) {
var this$1 = this;
if (!ranges.length) { return }
var out = []
for (var i = 0; i < ranges.length; i++)
{ out[i] = new Range(clipPos(this$1, ranges[i].anchor),
clipPos(this$1, ranges[i].head)) }
if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
setSelection(this, normalizeSelection(out, primary), options)
}),
addSelection: docMethodOp(function(anchor, head, options) {
var ranges = this.sel.ranges.slice(0)
ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
}),
getSelection: function(lineSep) {
var this$1 = this;
var ranges = this.sel.ranges, lines
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
lines = lines ? lines.concat(sel) : sel
}
if (lineSep === false) { return lines }
else { return lines.join(lineSep || this.lineSeparator()) }
},
getSelections: function(lineSep) {
var this$1 = this;
var parts = [], ranges = this.sel.ranges
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
parts[i] = sel
}
return parts
},
replaceSelection: function(code, collapse, origin) {
var dup = []
for (var i = 0; i < this.sel.ranges.length; i++)
{ dup[i] = code }
this.replaceSelections(dup, collapse, origin || "+input")
},
replaceSelections: docMethodOp(function(code, collapse, origin) {
var this$1 = this;
var changes = [], sel = this.sel
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i]
changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
}
var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
{ makeChange(this$1, changes[i$1]) }
if (newSel) { setSelectionReplaceHistory(this, newSel) }
else if (this.cm) { ensureCursorVisible(this.cm) }
}),
undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
setExtending: function(val) {this.extend = val},
getExtending: function() {return this.extend},
historySize: function() {
var hist = this.history, done = 0, undone = 0
for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
return {undo: done, redo: undone}
},
clearHistory: function() {this.history = new History(this.history.maxGeneration)},
markClean: function() {
this.cleanGeneration = this.changeGeneration(true)
},
changeGeneration: function(forceSplit) {
if (forceSplit)
{ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
return this.history.generation
},
isClean: function (gen) {
return this.history.generation == (gen || this.cleanGeneration)
},
getHistory: function() {
return {done: copyHistoryArray(this.history.done),
undone: copyHistoryArray(this.history.undone)}
},
setHistory: function(histData) {
var hist = this.history = new History(this.history.maxGeneration)
hist.done = copyHistoryArray(histData.done.slice(0), null, true)
hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
},
setGutterMarker: docMethodOp(function(line, gutterID, value) {
return changeLine(this, line, "gutter", function (line) {
var markers = line.gutterMarkers || (line.gutterMarkers = {})
markers[gutterID] = value
if (!value && isEmpty(markers)) { line.gutterMarkers = null }
return true
})
}),
clearGutter: docMethodOp(function(gutterID) {
var this$1 = this;
this.iter(function (line) {
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
changeLine(this$1, line, "gutter", function () {
line.gutterMarkers[gutterID] = null
if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
return true
})
}
})
}),
lineInfo: function(line) {
var n
if (typeof line == "number") {
if (!isLine(this, line)) { return null }
n = line
line = getLine(this, line)
if (!line) { return null }
} else {
n = lineNo(line)
if (n == null) { return null }
}
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
widgets: line.widgets}
},
addLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass"
if (!line[prop]) { line[prop] = cls }
else if (classTest(cls).test(line[prop])) { return false }
else { line[prop] += " " + cls }
return true
})
}),
removeLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass"
var cur = line[prop]
if (!cur) { return false }
else if (cls == null) { line[prop] = null }
else {
var found = cur.match(classTest(cls))
if (!found) { return false }
var end = found.index + found[0].length
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
}
return true
})
}),
addLineWidget: docMethodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options)
}),
removeLineWidget: function(widget) { widget.clear() },
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared,
handleMouseEvents: options && options.handleMouseEvents}
pos = clipPos(this, pos)
return markText(this, pos, pos, realOpts, "bookmark")
},
findMarksAt: function(pos) {
pos = clipPos(this, pos)
var markers = [], spans = getLine(this, pos.line).markedSpans
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i]
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
{ markers.push(span.marker.parent || span.marker) }
} }
return markers
},
findMarks: function(from, to, filter) {
from = clipPos(this, from); to = clipPos(this, to)
var found = [], lineNo = 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)
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)
if (options.sharedHist) { copy.history = this.history
; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
copySharedMarkers(copy, findSharedMarkers(this))
return copy
},
unlinkDoc: function(other) {
var this$1 = this;
if (other instanceof CodeMirror) { other = other.doc }
if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
var link = this$1.linked[i]
if (link.doc != other) { continue }
this$1.linked.splice(i, 1)
other.unlinkDoc(this$1)
detachSharedMarkers(findSharedMarkers(this$1))
break
} }
// If the histories were shared, split them again
if (other.history == this.history) {
var splitIds = [other.id]
linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
other.history = new History(null)
other.history.done = copyHistoryArray(this.history.done, splitIds)
other.history.undone = copyHistoryArray(this.history.undone, splitIds)
}
},
iterLinkedDocs: function(f) {linkedDocs(this, f)},
getMode: function() {return this.mode},
getEditor: function() {return this.cm},
splitLines: function(str) {
if (this.lineSep) { return str.split(this.lineSep) }
return splitLinesAuto(str)
},
lineSeparator: function() { return this.lineSep || "\n" }
})
// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter
// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0
function onDrop(e) {
var cm = this
clearDragCursor(cm)
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
{ return }
e_preventDefault(e)
if (ie) { lastDrop = +new Date }
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
if (!pos || cm.isReadOnly()) { return }
// Might be a file drop, in which case we simply extract the text
// and insert it.
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0
var loadFile = function (file, i) {
if (cm.options.allowDropFileTypes &&
indexOf(cm.options.allowDropFileTypes, file.type) == -1)
{ return }
var reader = new FileReader
reader.onload = operation(cm, function () {
var content = reader.result
if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
text[i] = content
if (++read == n) {
pos = clipPos(cm.doc, pos)
var change = {from: pos, to: pos,
text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
origin: "paste"}
makeChange(cm.doc, change)
setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
}
})
reader.readAsText(file)
}
for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
} else { // Normal drop
// Don't do a replace if the drop happened inside of the selected text.
if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
cm.state.draggingText(e)
// Ensure the editor is re-focused
setTimeout(function () { return cm.display.input.focus(); }, 20)
return
}
try {
var text$1 = e.dataTransfer.getData("Text")
if (text$1) {
var selected
if (cm.state.draggingText && !cm.state.draggingText.copy)
{ selected = cm.listSelections() }
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
{ replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
cm.replaceSelection(text$1, "around", "paste")
cm.display.input.focus()
}
}
catch(e){}
}
}
function onDragStart(cm, e) {
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
e.dataTransfer.setData("Text", cm.getSelection())
e.dataTransfer.effectAllowed = "copyMove"
// Use dummy image instead of default browsers image.
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
if (e.dataTransfer.setDragImage && !safari) {
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
if (presto) {
img.width = img.height = 1
cm.display.wrapper.appendChild(img)
// Force a relayout, or Opera won't use our image for some obscure reason
img._top = img.offsetTop
}
e.dataTransfer.setDragImage(img, 0, 0)
if (presto) { img.parentNode.removeChild(img) }
}
}
function onDragOver(cm, e) {
var pos = posFromMouse(cm, e)
if (!pos) { return }
var frag = document.createDocumentFragment()
drawSelectionCursor(cm, pos, frag)
if (!cm.display.dragCursor) {
cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
}
removeChildrenAndAdd(cm.display.dragCursor, frag)
}
function clearDragCursor(cm) {
if (cm.display.dragCursor) {
cm.display.lineSpace.removeChild(cm.display.dragCursor)
cm.display.dragCursor = null
}
}
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.body.getElementsByClassName) { return }
var byClass = document.body.getElementsByClassName("CodeMirror")
for (var i = 0; i < byClass.length; i++) {
var cm = byClass[i].CodeMirror
if (cm) { f(cm) }
}
}
var globalsRegistered = false
function ensureGlobalHandlers() {
if (globalsRegistered) { return }
registerGlobalHandlers()
globalsRegistered = true
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
var resizeTimer
on(window, "resize", function () {
if (resizeTimer == null) { resizeTimer = setTimeout(function () {
resizeTimer = null
forEachCodeMirror(onResize)
}, 100) }
})
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", function () { return forEachCodeMirror(onBlur); })
}
// Called when the window resizes
function onResize(cm) {
var d = cm.display
if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
{ return }
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
d.scrollbarsClipped = false
cm.setSize()
}
var keyNames = {
3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
}
// Number keys
for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
// Alphabetic keys
for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
// Function keys
for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
var keyMap = {}
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
"Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
"Tab": "defaultTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
"Esc": "singleSelection"
}
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.pcDefault = {
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
"Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
"Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
fallthrough: "basic"
}
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.emacsy = {
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
"Ctrl-O": "openLine"
}
keyMap.macDefault = {
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
"Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
"Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
fallthrough: ["basic", "emacsy"]
}
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
// KEYMAP DISPATCH
function normalizeKeyName(name) {
var parts = name.split(/-(?!$)/)
name = parts[parts.length - 1]
var alt, ctrl, shift, cmd
for (var i = 0; i < parts.length - 1; i++) {
var mod = parts[i]
if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
else if (/^a(lt)?$/i.test(mod)) { alt = true }
else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
else if (/^s(hift)?$/i.test(mod)) { shift = true }
else { throw new Error("Unrecognized modifier name: " + mod) }
}
if (alt) { name = "Alt-" + name }
if (ctrl) { name = "Ctrl-" + name }
if (cmd) { name = "Cmd-" + name }
if (shift) { name = "Shift-" + name }
return name
}
// This is a kludge to keep keymaps mostly working as raw objects
// (backwards compatibility) while at the same time support features
// like normalization and multi-stroke key bindings. It compiles a
// new normalized keymap, and then updates the old object to reflect
// this.
function normalizeKeyMap(keymap) {
var copy = {}
for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
var value = keymap[keyname]
if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
if (value == "...") { delete keymap[keyname]; continue }
var keys = map(keyname.split(" "), normalizeKeyName)
for (var i = 0; i < keys.length; i++) {
var val = (void 0), name = (void 0)
if (i == keys.length - 1) {
name = keys.join(" ")
val = value
} else {
name = keys.slice(0, i + 1).join(" ")
val = "..."
}
var prev = copy[name]
if (!prev) { copy[name] = val }
else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
}
delete keymap[keyname]
} }
for (var prop in copy) { keymap[prop] = copy[prop] }
return keymap
}
function lookupKey(key, map, 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"
}
// Look up the name of a key as indicated by an event object.
function keyName(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) { return false }
var base = keyNames[event.keyCode], name = base
if (name == null || event.altGraphKey) { return false }
if (event.altKey && base != "Alt") { name = "Alt-" + name }
if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
return name
}
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)
})
}
// 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.charCoords(range.head, "div").top + 5
return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
}, sel_move); },
goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.charCoords(range.head, "div").top + 5
return cm.coordsChar({left: 0, top: top}, "div")
}, sel_move); },
goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.charCoords(range.head, "div").top + 5
var pos = cm.coordsChar({left: 0, top: top}, "div")
if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
return pos
}, sel_move); },
goLineUp: function (cm) { return cm.moveV(-1, "line"); },
goLineDown: function (cm) { return cm.moveV(1, "line"); },
goPageUp: function (cm) { return cm.moveV(-1, "page"); },
goPageDown: function (cm) { return cm.moveV(1, "page"); },
goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
goCharRight: function (cm) { return cm.moveH(1, "char"); },
goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
goColumnRight: function (cm) { return cm.moveH(1, "column"); },
goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
goGroupRight: function (cm) { return cm.moveH(1, "group"); },
goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
goWordRight: function (cm) { return cm.moveH(1, "word"); },
delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
indentAuto: function (cm) { return cm.indentSelection("smart"); },
indentMore: function (cm) { return cm.indentSelection("add"); },
indentLess: function (cm) { return cm.indentSelection("subtract"); },
insertTab: function (cm) { return cm.replaceSelection("\t"); },
insertSoftTab: function (cm) {
var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].from()
var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
spaces.push(spaceStr(tabSize - col % tabSize))
}
cm.replaceSelections(spaces)
},
defaultTab: function (cm) {
if (cm.somethingSelected()) { cm.indentSelection("add") }
else { cm.execCommand("insertTab") }
},
// Swap the two chars left and right of each selection's head.
// Move cursor behind the two swapped characters afterwards.
//
// Doesn't consider line feeds a character.
// Doesn't scan more than one line above to find a character.
// Doesn't do anything on an empty line.
// Doesn't do anything with non-empty selections.
transposeChars: function (cm) { return runInOp(cm, function () {
var ranges = cm.listSelections(), newSel = []
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) { continue }
var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
if (line) {
if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
if (cur.ch > 0) {
cur = new Pos(cur.line, cur.ch + 1)
cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
Pos(cur.line, cur.ch - 2), cur, "+transpose")
} else if (cur.line > cm.doc.first) {
var prev = getLine(cm.doc, cur.line - 1).text
if (prev) {
cur = new Pos(cur.line, 1)
cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
prev.charAt(prev.length - 1),
Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
}
}
}
newSel.push(new Range(cur, cur))
}
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) }
var order = getOrder(visual)
var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual)
return Pos(lineN, ch)
}
function lineEnd(cm, lineN) {
var merged, line = getLine(cm.doc, lineN)
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line
lineN = null
}
var order = getOrder(line)
var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line)
return Pos(lineN == null ? lineNo(line) : lineN, ch)
}
function lineStartSmart(cm, pos) {
var start = lineStart(cm, pos.line)
var line = getLine(cm.doc, start.line)
var order = getOrder(line)
if (!order || order[0].level == 0) {
var firstNonWS = Math.max(0, line.text.search(/\S/))
var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
return Pos(start.line, inWS ? 0 : firstNonWS)
}
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)
}
var stopSeq = new Delayed
function dispatchKey(cm, name, e, handle) {
var seq = cm.state.keySeq
if (seq) {
if (isModifierKey(name)) { return "handled" }
stopSeq.set(50, function () {
if (cm.state.keySeq == seq) {
cm.state.keySeq = null
cm.display.input.reset()
}
})
name = seq + " " + name
}
var result = lookupKeyForEditor(cm, name, handle)
if (result == "multi")
{ cm.state.keySeq = name }
if (result == "handled")
{ signalLater(cm, "keyHandled", cm, name, e) }
if (result == "handled" || result == "multi") {
e_preventDefault(e)
restartBlink(cm)
}
if (seq && !result && /\'$/.test(name)) {
e_preventDefault(e)
return true
}
return !!result
}
// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
var name = keyName(e, true)
if (!name) { return false }
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
|| dispatchKey(cm, name, e, function (b) {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
{ return doHandleBinding(cm, b) }
})
} else {
return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
}
}
// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
}
var lastStoppedKey = null
function onKeyDown(e) {
var cm = this
cm.curOp.focus = activeElt()
if (signalDOMEvent(cm, e)) { return }
// IE does strange things with escape.
if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
var code = e.keyCode
cm.display.shift = code == 16 || e.shiftKey
var handled = handleKeyBinding(cm, e)
if (presto) {
lastStoppedKey = handled ? code : null
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
{ cm.replaceSelection("", null, "cut") }
}
// Turn mouse into crosshair when Alt is held on Mac.
if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
{ showCrossHair(cm) }
}
function showCrossHair(cm) {
var lineDiv = cm.display.lineDiv
addClass(lineDiv, "CodeMirror-crosshair")
function up(e) {
if (e.keyCode == 18 || !e.altKey) {
rmClass(lineDiv, "CodeMirror-crosshair")
off(document, "keyup", up)
off(document, "mouseover", up)
}
}
on(document, "keyup", up)
on(document, "mouseover", up)
}
function onKeyUp(e) {
if (e.keyCode == 16) { this.doc.sel.shift = false }
signalDOMEvent(this, e)
}
function onKeyPress(e) {
var cm = this
if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
var keyCode = e.keyCode, charCode = e.charCode
if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
// Some browsers fire keypress events for backspace
if (ch == "\x08") { return }
if (handleCharBinding(cm, e, ch)) { return }
cm.display.input.onKeyPress(e)
}
// 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 start = posFromMouse(cm, e)
window.focus()
switch (e_button(e)) {
case 1:
// #3261: make sure, that we're not starting a second selection
if (cm.state.selectingText)
{ cm.state.selectingText(e) }
else if (start)
{ leftButtonDown(cm, e, start) }
else if (e_target(e) == display.scroller)
{ e_preventDefault(e) }
break
case 2:
if (webkit) { cm.state.lastMiddleDown = +new Date }
if (start) { extendSelection(cm.doc, start) }
setTimeout(function () { return display.input.focus(); }, 20)
e_preventDefault(e)
break
case 3:
if (captureRightClick) { onContextMenu(cm, e) }
else { delayBlurEvent(cm) }
break
}
}
var lastClick;
var lastDoubleClick;
function leftButtonDown(cm, e, start) {
if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
else { cm.curOp.focus = activeElt() }
var now = +new Date, type
if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
type = "triple"
} else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
type = "double"
lastDoubleClick = {time: now, pos: start}
} else {
type = "single"
lastClick = {time: now, pos: start}
}
var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained
if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
type == "single" && (contained = sel.contains(start)) > -1 &&
(cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
(cmp(contained.to(), start) > 0 || start.xRel < 0))
{ leftButtonStartDrag(cm, e, start, modifier) }
else
{ leftButtonSelect(cm, e, start, type, modifier) }
}
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, e, start, modifier) {
var display = cm.display, startTime = +new Date
var dragEnd = operation(cm, function (e2) {
if (webkit) { display.scroller.draggable = false }
cm.state.draggingText = false
off(document, "mouseup", dragEnd)
off(display.scroller, "drop", dragEnd)
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
e_preventDefault(e2)
if (!modifier && +new Date - 200 < startTime)
{ extendSelection(cm.doc, start) }
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if (webkit || ie && ie_version == 9)
{ setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
else
{ display.input.focus() }
}
})
// Let the drag handler handle this.
if (webkit) { display.scroller.draggable = true }
cm.state.draggingText = dragEnd
dragEnd.copy = mac ? e.altKey : e.ctrlKey
// IE's approach to draggable
if (display.scroller.dragDrop) { display.scroller.dragDrop() }
on(document, "mouseup", dragEnd)
on(display.scroller, "drop", dragEnd)
}
// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, e, start, type, addNew) {
var display = cm.display, doc = cm.doc
e_preventDefault(e)
var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
if (addNew && !e.shiftKey) {
ourIndex = doc.sel.contains(start)
if (ourIndex > -1)
{ ourRange = ranges[ourIndex] }
else
{ ourRange = new Range(start, start) }
} else {
ourRange = doc.sel.primary()
ourIndex = doc.sel.primIndex
}
if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
type = "rect"
if (!addNew) { ourRange = new Range(start, start) }
start = posFromMouse(cm, e, true, true)
ourIndex = -1
} else if (type == "double") {
var word = cm.findWordAt(start)
if (cm.display.shift || doc.extend)
{ ourRange = extendRange(doc, ourRange, word.anchor, word.head) }
else
{ ourRange = word }
} else if (type == "triple") {
var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)))
if (cm.display.shift || doc.extend)
{ ourRange = extendRange(doc, ourRange, line.anchor, line.head) }
else
{ ourRange = line }
} else {
ourRange = extendRange(doc, ourRange, start)
}
if (!addNew) {
ourIndex = 0
setSelection(doc, new Selection([ourRange], 0), sel_mouse)
startSel = doc.sel
} else if (ourIndex == -1) {
ourIndex = ranges.length
setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"})
} else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
{scroll: false, origin: "*mouse"})
startSel = doc.sel
} else {
replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
}
var lastPos = start
function extendTo(pos) {
if (cmp(lastPos, pos) == 0) { return }
lastPos = pos
if (type == "rect") {
var ranges = [], tabSize = cm.options.tabSize
var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
line <= end; line++) {
var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
if (left == right)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
else if (text.length > leftPos)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
}
if (!ranges.length) { ranges.push(new Range(start, start)) }
setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
{origin: "*mouse", scroll: false})
cm.scrollIntoView(pos)
} else {
var oldRange = ourRange
var anchor = oldRange.anchor, head = pos
if (type != "single") {
var range
if (type == "double")
{ range = cm.findWordAt(pos) }
else
{ range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) }
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] = new Range(clipPos(doc, anchor), head)
setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
}
}
var editorSize = display.wrapper.getBoundingClientRect()
// Used to ensure timeout re-tries don't fire when another extend
// happened in the meantime (clearTimeout isn't reliable -- at
// least on Chrome, the timeouts still happen even when cleared,
// if the clear happens after their scheduled firing time).
var counter = 0
function extend(e) {
var curCount = ++counter
var cur = posFromMouse(cm, e, true, type == "rect")
if (!cur) { return }
if (cmp(cur, lastPos) != 0) {
cm.curOp.focus = activeElt()
extendTo(cur)
var visible = visibleLines(display, doc)
if (cur.line >= visible.to || cur.line < visible.from)
{ setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
} else {
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
if (outside) { setTimeout(operation(cm, function () {
if (counter != curCount) { return }
display.scroller.scrollTop += outside
extend(e)
}), 50) }
}
}
function done(e) {
cm.state.selectingText = false
counter = Infinity
e_preventDefault(e)
display.input.focus()
off(document, "mousemove", move)
off(document, "mouseup", up)
doc.history.lastSelOrigin = null
}
var move = operation(cm, function (e) {
if (!e_button(e)) { done(e) }
else { extend(e) }
})
var up = operation(cm, done)
cm.state.selectingText = up
on(document, "mousemove", move)
on(document, "mouseup", up)
}
// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent) {
var mX, mY
try { mX = e.clientX; mY = e.clientY }
catch(e) { return false }
if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
if (prevent) { e_preventDefault(e) }
var display = cm.display
var lineBox = display.lineDiv.getBoundingClientRect()
if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
mY -= lineBox.top - display.viewOffset
for (var i = 0; i < cm.options.gutters.length; ++i) {
var g = display.gutters.childNodes[i]
if (g && g.getBoundingClientRect().right >= mX) {
var line = lineAtHeight(cm.doc, mY)
var gutter = cm.options.gutters[i]
signal(cm, type, cm, line, gutter, e)
return e_defaultPrevented(e)
}
}
}
function clickInGutter(cm, e) {
return gutterEvent(cm, e, "gutterClick", true)
}
// CONTEXT MENU HANDLING
// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
if (signalDOMEvent(cm, e, "contextmenu")) { return }
cm.display.input.onContextMenu(e)
}
function contextMenuInGutter(cm, e) {
if (!hasHandler(cm, "gutterContextMenu")) { return false }
return gutterEvent(cm, e, "gutterContextMenu", false)
}
function themeChanged(cm) {
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
clearCaches(cm)
}
var Init = {toString: function(){return "CodeMirror.Init"}}
var defaults = {}
var optionHandlers = {}
function defineOptions(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt
if (handle) { optionHandlers[name] =
notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
}
CodeMirror.defineOption = option
// Passed to option handlers when there is no old value.
CodeMirror.Init = Init
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", function (cm, val) { return cm.setValue(val); }, true)
option("mode", null, function (cm, val) {
cm.doc.modeOption = val
loadMode(cm)
}, true)
option("indentUnit", 2, loadMode, true)
option("indentWithTabs", false)
option("smartIndent", true)
option("tabSize", 4, function (cm) {
resetModeState(cm)
clearCaches(cm)
regChange(cm)
}, true)
option("lineSeparator", null, function (cm, val) {
cm.doc.lineSep = val
if (!val) { return }
var newBreaks = [], lineNo = cm.doc.first
cm.doc.iter(function (line) {
for (var pos = 0;;) {
var found = line.text.indexOf(val, pos)
if (found == -1) { break }
pos = found + val.length
newBreaks.push(Pos(lineNo, found))
}
lineNo++
})
for (var i = newBreaks.length - 1; i >= 0; i--)
{ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
})
option("specialChars", /[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
if (old != Init) { cm.refresh() }
})
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
option("electricChars", true)
option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
}, true)
option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
option("rtlMoveVisually", !windows)
option("wholeLineUpdateBefore", true)
option("theme", "default", function (cm) {
themeChanged(cm)
guttersChanged(cm)
}, true)
option("keyMap", "default", function (cm, val, old) {
var next = getKeyMap(val)
var prev = old != Init && getKeyMap(old)
if (prev && prev.detach) { prev.detach(cm, next) }
if (next.attach) { next.attach(cm, prev || null) }
})
option("extraKeys", null)
option("lineWrapping", false, wrappingChanged, true)
option("gutters", [], function (cm) {
setGuttersForLineNumbers(cm.options)
guttersChanged(cm)
}, true)
option("fixedGutter", true, function (cm, val) {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
cm.refresh()
}, true)
option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
option("scrollbarStyle", "native", function (cm) {
initScrollbars(cm)
updateScrollbars(cm)
cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
}, true)
option("lineNumbers", false, function (cm) {
setGuttersForLineNumbers(cm.options)
guttersChanged(cm)
}, true)
option("firstLineNumber", 1, guttersChanged, true)
option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
option("showCursorWhenSelecting", false, updateSelection, true)
option("resetSelectionOnContextMenu", true)
option("lineWiseCopyCut", true)
option("readOnly", false, function (cm, val) {
if (val == "nocursor") {
onBlur(cm)
cm.display.input.blur()
cm.display.disabled = true
} else {
cm.display.disabled = false
}
cm.display.input.readOnlyChanged(val)
})
option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
option("dragDrop", true, dragDropChanged)
option("allowDropFileTypes", null)
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)
}
function guttersChanged(cm) {
updateGutters(cm)
regChange(cm)
alignHorizontally(cm)
}
function dragDropChanged(cm, value, old) {
var wasOn = old && old != Init
if (!value != !wasOn) {
var funcs = cm.display.dragFunctions
var toggle = value ? on : off
toggle(cm.display.scroller, "dragstart", funcs.start)
toggle(cm.display.scroller, "dragenter", funcs.enter)
toggle(cm.display.scroller, "dragover", funcs.over)
toggle(cm.display.scroller, "dragleave", funcs.leave)
toggle(cm.display.scroller, "drop", funcs.drop)
}
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap")
cm.display.sizer.style.minWidth = ""
cm.display.sizerWidth = null
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap")
findMaxLine(cm)
}
estimateLineHeights(cm)
regChange(cm)
clearCaches(cm)
setTimeout(function () { return updateScrollbars(cm); }, 100)
}
// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.
function CodeMirror(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)
setGuttersForLineNumbers(options)
var doc = options.value
if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) }
this.doc = doc
var input = new CodeMirror.inputStyles[options.inputStyle](this)
var display = this.display = new Display(place, doc, input)
display.wrapper.CodeMirror = this
updateGutters(this)
themeChanged(this)
if (options.lineWrapping)
{ this.display.wrapper.className += " CodeMirror-wrap" }
initScrollbars(this)
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false,
delayingBlurEvent: false,
focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
selectingText: false,
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null, // Unfinished key sequence
specialChars: null
}
if (options.autofocus && !mobile) { display.input.focus() }
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
registerEventHandlers(this)
ensureGlobalHandlers()
startOperation(this)
this.curOp.forceUpdate = true
attachDoc(this, doc)
if ((options.autofocus && !mobile) || this.hasFocus())
{ setTimeout(bind(onFocus, this), 20) }
else
{ onBlur(this) }
for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
{ optionHandlers[opt](this$1, options[opt], Init) } }
maybeUpdateLineNumberWidth(this)
if (options.finishInit) { options.finishInit(this) }
for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
endOperation(this)
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
{ display.lineDiv.style.textRendering = "auto" }
}
// The default configuration options.
CodeMirror.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.
if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
// Used to suppress mouse event handling when a touch happens
var touchFinished, prevTouch = {end: 0}
function finishTouch() {
if (d.activeTouch) {
touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
prevTouch = d.activeTouch
prevTouch.end = +new Date
}
}
function isMouseLikeTouchEvent(e) {
if (e.touches.length != 1) { return false }
var touch = e.touches[0]
return touch.radiusX <= 1 && touch.radiusY <= 1
}
function farAway(touch, other) {
if (other.left == null) { return true }
var dx = other.left - touch.left, dy = other.top - touch.top
return dx * dx + dy * dy > 20 * 20
}
on(d.scroller, "touchstart", function (e) {
if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
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) {
setScrollTop(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 = getStateBefore(cm, n) }
}
var tabSize = cm.options.tabSize
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
if (line.stateAfter) { line.stateAfter = null }
var curSpaceString = line.text.match(/^\s*/)[0], indentation
if (!aggressive && !/\S/.test(line.text)) {
indentation = 0
how = "not"
} else if (how == "smart") {
indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
if (indentation == Pass || indentation > 150) {
if (!aggressive) { return }
how = "prev"
}
}
if (how == "prev") {
if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
else { indentation = 0 }
} else if (how == "add") {
indentation = curSpace + cm.options.indentUnit
} else if (how == "subtract") {
indentation = curSpace - cm.options.indentUnit
} else if (typeof how == "number") {
indentation = curSpace + how
}
indentation = Math.max(0, indentation)
var indentString = "", pos = 0
if (cm.options.indentWithTabs)
{ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
if (pos < indentation) { indentString += spaceStr(indentation - pos) }
if (indentString != curSpaceString) {
replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
line.stateAfter = null
return true
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
var range = doc.sel.ranges[i$1]
if (range.head.line == n && range.head.ch < curSpaceString.length) {
var pos$1 = Pos(n, curSpaceString.length)
replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
break
}
}
}
}
// This will be set to a {lineWise: bool, text: [string]} object, so
// that, when pasting, we know what kind of selections the copied
// text was made out of.
var lastCopied = null
function setLastCopied(newLastCopied) {
lastCopied = newLastCopied
}
function applyTextInput(cm, inserted, deleted, sel, origin) {
var doc = cm.doc
cm.display.shift = false
if (!sel) { sel = doc.sel }
var paste = cm.state.pasteIncoming || origin == "paste"
var textLines = splitLinesAuto(inserted), multiPaste = null
// When pasing N lines into N selections, insert one line per selection
if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.text.join("\n") == inserted) {
if (sel.ranges.length % lastCopied.text.length == 0) {
multiPaste = []
for (var i = 0; i < lastCopied.text.length; i++)
{ multiPaste.push(doc.splitLines(lastCopied.text[i])) }
}
} else if (textLines.length == sel.ranges.length) {
multiPaste = map(textLines, function (l) { return [l]; })
}
}
var updateInput
// Normal behavior is to insert the new text into every selection
for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
var range = 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 (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
{ from = to = Pos(from.line, 0) }
}
updateInput = cm.curOp.updateInput
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
makeChange(cm.doc, changeEvent)
signalLater(cm, "inputRead", cm, changeEvent)
}
if (inserted && !paste)
{ triggerElectric(cm, inserted) }
ensureCursorVisible(cm)
cm.curOp.updateInput = updateInput
cm.curOp.typing = true
cm.state.pasteIncoming = cm.state.cutIncoming = false
}
function handlePaste(e, cm) {
var pasted = e.clipboardData && e.clipboardData.getData("Text")
if (pasted) {
e.preventDefault()
if (!cm.isReadOnly() && !cm.options.disableInput)
{ runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
return true
}
}
function triggerElectric(cm, inserted) {
// When an 'electric' character is inserted, immediately trigger a reindent
if (!cm.options.electricChars || !cm.options.smartIndent) { return }
var sel = cm.doc.sel
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = 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) {
field.setAttribute("autocorrect", "off")
field.setAttribute("autocapitalize", "off")
field.setAttribute("spellcheck", !!spellcheck)
}
function hiddenTextarea() {
var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
// The textarea is kept positioned near the cursor to prevent the
// fact that it'll be scrolled into view on input from scrolling
// our fake cursor out of view. On webkit, when wrap=off, paste is
// very slow. So make the area wide instead.
if (webkit) { te.style.width = "1000px" }
else { te.setAttribute("wrap", "off") }
// If border: 0; -- iOS fails to open keyboard (issue #1287)
if (ios) { te.style.border = "1px solid black" }
disableBrowserMagic(te)
return div
}
// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.
// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.
function addEditorMethods(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers
var helpers = CodeMirror.helpers = {}
CodeMirror.prototype = {
constructor: CodeMirror,
focus: function(){window.focus(); this.display.input.focus()},
setOption: function(option, value) {
var options = this.options, old = options[option]
if (options[option] == value && option != "mode") { return }
options[option] = value
if (optionHandlers.hasOwnProperty(option))
{ operation(this, optionHandlers[option])(this, value, old) }
signal(this, "optionChange", this, option)
},
getOption: function(option) {return this.options[option]},
getDoc: function() {return this.doc},
addKeyMap: function(map, 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 this$1 = this;
var overlays = this.state.overlays
for (var i = 0; i < overlays.length; ++i) {
var cur = overlays[i].modeSpec
if (cur == spec || typeof spec == "string" && cur.name == spec) {
overlays.splice(i, 1)
this$1.state.modeGen++
regChange(this$1)
return
}
}
}),
indentLine: methodOp(function(n, dir, aggressive) {
if (typeof dir != "string" && typeof dir != "number") {
if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
else { dir = dir ? "add" : "subtract" }
}
if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
}),
indentSelection: methodOp(function(how) {
var this$1 = this;
var ranges = this.doc.sel.ranges, end = -1
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i]
if (!range.empty()) {
var from = range.from(), to = range.to()
var start = Math.max(end, from.line)
end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
for (var j = start; j < end; ++j)
{ indentLine(this$1, j, how) }
var newRanges = this$1.doc.sel.ranges
if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
{ replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
} else if (range.head.line > end) {
indentLine(this$1, range.head.line, how, true)
end = range.head.line
if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
}
}
}),
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(pos, precise) {
return takeToken(this, pos, precise)
},
getLineTokens: function(line, precise) {
return takeToken(this, Pos(line), precise, true)
},
getTokenTypeAt: function(pos) {
pos = clipPos(this.doc, pos)
var styles = getLineStyles(this, getLine(this.doc, pos.line))
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
var type
if (ch == 0) { type = styles[2] }
else { for (;;) {
var mid = (before + after) >> 1
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
else { type = styles[mid * 2 + 2]; break }
} }
var cut = type ? type.indexOf("overlay ") : -1
return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
},
getModeAt: function(pos) {
var mode = this.doc.mode
if (!mode.innerMode) { return mode }
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
},
getHelper: function(pos, type) {
return this.getHelpers(pos, type)[0]
},
getHelpers: function(pos, type) {
var this$1 = this;
var found = []
if (!helpers.hasOwnProperty(type)) { return found }
var help = helpers[type], mode = this.getModeAt(pos)
if (typeof mode[type] == "string") {
if (help[mode[type]]) { found.push(help[mode[type]]) }
} else if (mode[type]) {
for (var i = 0; i < mode[type].length; i++) {
var val = help[mode[type][i]]
if (val) { found.push(val) }
}
} else if (mode.helperType && help[mode.helperType]) {
found.push(help[mode.helperType])
} else if (help[mode.name]) {
found.push(help[mode.name])
}
for (var i$1 = 0; i$1 < help._global.length; i$1++) {
var cur = help._global[i$1]
if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
{ found.push(cur.val) }
}
return found
},
getStateAfter: function(line, precise) {
var doc = this.doc
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
return getStateBefore(this, line + 1, precise)
},
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).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, top, left + node.offsetWidth, top + node.offsetHeight) }
},
triggerOnKeyDown: methodOp(onKeyDown),
triggerOnKeyPress: methodOp(onKeyPress),
triggerOnKeyUp: onKeyUp,
execCommand: function(cmd) {
if (commands.hasOwnProperty(cmd))
{ return commands[cmd].call(null, this) }
},
triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
findPosH: function(from, amount, unit, visually) {
var this$1 = this;
var dir = 1
if (amount < 0) { dir = -1; amount = -amount }
var cur = clipPos(this.doc, from)
for (var i = 0; i < amount; ++i) {
cur = findPosH(this$1.doc, cur, dir, unit, visually)
if (cur.hitSide) { break }
}
return cur
},
moveH: methodOp(function(dir, unit) {
var this$1 = this;
this.extendSelectionsBy(function (range) {
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 this$1 = this;
var dir = 1, x = goalColumn
if (amount < 0) { dir = -1; amount = -amount }
var cur = clipPos(this.doc, from)
for (var i = 0; i < amount; ++i) {
var coords = cursorCoords(this$1, cur, "div")
if (x == null) { x = coords.left }
else { coords.left = x }
cur = findPosV(this$1, coords, dir, unit)
if (cur.hitSide) { break }
}
return cur
},
moveV: methodOp(function(dir, unit) {
var this$1 = this;
var doc = this.doc, goals = []
var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
doc.extendSelectionsBy(function (range) {
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())
{ addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) }
return pos
}, sel_move)
if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
{ doc.sel.ranges[i].goalColumn = goals[i] } }
}),
// 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.xRel < 0 || end == line.length) && start) { --start; } else { ++end }
var startChar = line.charAt(start)
var check = isWordChar(startChar, helper)
? function (ch) { return isWordChar(ch, helper); }
: /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
: function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
while (start > 0 && check(line.charAt(start - 1))) { --start }
while (end < line.length && check(line.charAt(end))) { ++end }
}
return new Range(Pos(pos.line, start), Pos(pos.line, end))
},
toggleOverwrite: function(value) {
if (value != null && value == this.state.overwrite) { return }
if (this.state.overwrite = !this.state.overwrite)
{ addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
else
{ rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
signal(this, "overwriteToggle", this, this.state.overwrite)
},
hasFocus: function() { return this.display.input.getField() == activeElt() },
isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
scrollTo: methodOp(function(x, y) {
if (x != null || y != null) { resolveScrollToPos(this) }
if (x != null) { this.curOp.scrollLeft = x }
if (y != null) { this.curOp.scrollTop = y }
}),
getScrollInfo: function() {
var scroller = this.display.scroller
return {left: scroller.scrollLeft, top: scroller.scrollTop,
height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
},
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) {
resolveScrollToPos(this)
this.curOp.scrollToPos = range
} else {
var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
Math.min(range.from.top, range.to.top) - range.margin,
Math.max(range.from.right, range.to.right),
Math.max(range.from.bottom, range.to.bottom) + range.margin)
this.scrollTo(sPos.scrollLeft, sPos.scrollTop)
}
}),
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)},
refresh: methodOp(function() {
var oldHeight = this.display.cachedTextHeight
regChange(this)
this.curOp.forceUpdate = true
clearCaches(this)
this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop)
updateGutterSpace(this)
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
{ estimateLineHeights(this) }
signal(this, "refresh", this)
}),
swapDoc: methodOp(function(doc) {
var old = this.doc
old.cm = null
attachDoc(this, doc)
clearCaches(this)
this.display.input.reset()
this.scrollTo(doc.scrollLeft, doc.scrollTop)
this.curOp.forceScroll = true
signalLater(this, "swapDoc", this, old)
return old
}),
getInputField: function(){return this.display.input.getField()},
getWrapperElement: function(){return this.display.wrapper},
getScrollerElement: function(){return this.display.scroller},
getGutterElement: function(){return this.display.gutters}
}
eventMixin(CodeMirror)
CodeMirror.registerHelper = function(type, name, value) {
if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
helpers[type][name] = value
}
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
CodeMirror.registerHelper(type, name, value)
helpers[type]._global.push({pred: predicate, val: value})
}
}
// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "char", "column" (like char, but doesn't
// cross line boundaries), "word" (across next word), or "group" (to
// the start of next group of word or non-word-non-whitespace
// chars). The visually param controls whether, in right-to-left
// text, direction 1 means to move towards the next index in the
// string, or towards the character to the right of the current
// position. The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
var line = pos.line, ch = pos.ch, origDir = dir
var lineObj = getLine(doc, line)
function findNextLine() {
var l = line + dir
if (l < doc.first || l >= doc.first + doc.size) { return false }
line = l
return lineObj = getLine(doc, l)
}
function moveOnce(boundToLine) {
var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true)
if (next == null) {
if (!boundToLine && findNextLine()) {
if (visually) { ch = (dir < 0 ? lineRight : lineLeft)(lineObj) }
else { ch = dir < 0 ? lineObj.text.length : 0 }
} else { return false }
} else { ch = next }
return true
}
if (unit == "char") {
moveOnce()
} else if (unit == "column") {
moveOnce(true)
} else if (unit == "word" || unit == "group") {
var sawType = null, group = unit == "group"
var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
for (var first = true;; first = false) {
if (dir < 0 && !moveOnce(!first)) { break }
var cur = lineObj.text.charAt(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()}
break
}
if (type) { sawType = type }
if (dir > 0 && !moveOnce(!first)) { break }
}
}
var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true)
if (!cmp(pos, result)) { result.hitSide = true }
return result
}
// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
var doc = cm.doc, x = pos.left, y
if (unit == "page") {
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
} else if (unit == "line") {
y = dir > 0 ? pos.bottom + 3 : pos.top - 3
}
var target
for (;;) {
target = coordsChar(cm, x, y)
if (!target.outside) { break }
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
y += dir * 5
}
return target
}
// CONTENTEDITABLE INPUT STYLE
var ContentEditableInput = function(cm) {
this.cm = cm
this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
this.polling = new Delayed()
this.composing = null
this.gracePeriod = false
this.readDOMTimeout = null
};
ContentEditableInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = input.cm
var div = input.div = display.lineDiv
disableBrowserMagic(div, cm.options.spellcheck)
on(div, "paste", function (e) {
if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
// IE doesn't fire input events, so we schedule a read for the pasted content in this way
if (ie_version <= 11) { setTimeout(operation(cm, function () {
if (!input.pollContent()) { regChange(cm) }
}), 20) }
})
on(div, "compositionstart", function (e) {
this$1.composing = {data: e.data, done: false}
})
on(div, "compositionupdate", function (e) {
if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
})
on(div, "compositionend", function (e) {
if (this$1.composing) {
if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
this$1.composing.done = true
}
})
on(div, "touchstart", function () { return input.forceCompositionEnd(); })
on(div, "input", function () {
if (!this$1.composing) { this$1.readFromDOMSoon() }
})
function onCopyCut(e) {
if (signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()})
if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm)
setLastCopied({lineWise: true, text: ranges.text})
if (e.type == "cut") {
cm.operation(function () {
cm.setSelections(ranges.ranges, 0, sel_dontScroll)
cm.replaceSelection("", null, "cut")
})
}
}
if (e.clipboardData) {
e.clipboardData.clearData()
var content = lastCopied.text.join("\n")
// iOS exposes the clipboard API, but seems to discard content inserted into it
e.clipboardData.setData("Text", content)
if (e.clipboardData.getData("Text") == content) {
e.preventDefault()
return
}
}
// Old-fashioned briefly-focus-a-textarea hack
var kludge = hiddenTextarea(), te = kludge.firstChild
cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
te.value = lastCopied.text.join("\n")
var hadFocus = document.activeElement
selectInput(te)
setTimeout(function () {
cm.display.lineSpace.removeChild(kludge)
hadFocus.focus()
if (hadFocus == div) { input.showPrimarySelection() }
}, 50)
}
on(div, "copy", onCopyCut)
on(div, "cut", onCopyCut)
};
ContentEditableInput.prototype.prepareSelection = function () {
var result = prepareSelection(this.cm, false)
result.focus = this.cm.state.focused
return result
};
ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
if (!info || !this.cm.display.view.length) { return }
if (info.focus || takeFocus) { this.showPrimarySelection() }
this.showMultipleSelections(info)
};
ContentEditableInput.prototype.showPrimarySelection = function () {
var sel = window.getSelection(), prim = this.cm.doc.sel.primary()
var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset)
var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset)
if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
{ return }
var start = posToDOM(this.cm, prim.from())
var end = posToDOM(this.cm, prim.to())
if (!start && !end) { return }
var view = this.cm.display.view
var old = sel.rangeCount && sel.getRangeAt(0)
if (!start) {
start = {node: view[0].measure.map[2], offset: 0}
} else if (!end) { // FIXME dangerously hacky
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]}
}
var 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 && this.cm.state.focused) {
sel.collapse(start.node, start.offset)
if (!rng.collapsed) {
sel.removeAllRanges()
sel.addRange(rng)
}
} else {
sel.removeAllRanges()
sel.addRange(rng)
}
if (old && sel.anchorNode == null) { sel.addRange(old) }
else if (gecko) { this.startGracePeriod() }
}
this.rememberSelection()
};
ContentEditableInput.prototype.startGracePeriod = function () {
var this$1 = this;
clearTimeout(this.gracePeriod)
this.gracePeriod = setTimeout(function () {
this$1.gracePeriod = false
if (this$1.selectionChanged())
{ this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
}, 20)
};
ContentEditableInput.prototype.showMultipleSelections = function (info) {
removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
};
ContentEditableInput.prototype.rememberSelection = function () {
var sel = window.getSelection()
this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
};
ContentEditableInput.prototype.selectionInEditor = function () {
var sel = window.getSelection()
if (!sel.rangeCount) { return false }
var node = sel.getRangeAt(0).commonAncestorContainer
return contains(this.div, node)
};
ContentEditableInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor") {
if (!this.selectionInEditor())
{ this.showSelection(this.prepareSelection(), true) }
this.div.focus()
}
};
ContentEditableInput.prototype.blur = function () { this.div.blur() };
ContentEditableInput.prototype.getField = function () { return this.div };
ContentEditableInput.prototype.supportsTouch = function () { return true };
ContentEditableInput.prototype.receivedFocus = function () {
var input = this
if (this.selectionInEditor())
{ this.pollSelection() }
else
{ runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
function poll() {
if (input.cm.state.focused) {
input.pollSelection()
input.polling.set(input.cm.options.pollInterval, poll)
}
}
this.polling.set(this.cm.options.pollInterval, poll)
};
ContentEditableInput.prototype.selectionChanged = function () {
var sel = window.getSelection()
return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
};
ContentEditableInput.prototype.pollSelection = function () {
if (!this.composing && this.readDOMTimeout == null && !this.gracePeriod && this.selectionChanged()) {
var sel = window.getSelection(), cm = this.cm
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 }
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
if (!this.pollContent()) { regChange(this.cm) }
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 }
}
if (this$1.cm.isReadOnly() || !this$1.pollContent())
{ runInOp(this$1.cm, function () { return regChange(this$1.cm); }) }
}, 80)
};
ContentEditableInput.prototype.setUneditable = function (node) {
node.contentEditable = "false"
};
ContentEditableInput.prototype.onKeyPress = function (e) {
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), 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 badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
function domTextBetween(cm, from, to, fromLine, toLine) {
var text = "", closing = false, lineSep = cm.doc.lineSeparator()
function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
function walk(node) {
if (node.nodeType == 1) {
var cmText = node.getAttribute("cm-text")
if (cmText != null) {
if (cmText == "") { text += node.textContent.replace(/\u200b/g, "") }
else { text += 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()))
{ text += getBetween(cm.doc, range.from, range.to).join(lineSep) }
return
}
if (node.getAttribute("contenteditable") == "false") { return }
for (var i = 0; i < node.childNodes.length; i++)
{ walk(node.childNodes[i]) }
if (/^(pre|div|p)$/i.test(node.nodeName))
{ closing = true }
} else if (node.nodeType == 3) {
var val = node.nodeValue
if (!val) { return }
if (closing) {
text += lineSep
closing = false
}
text += val
}
}
for (;;) {
walk(from)
if (from == to) { break }
from = from.nextSibling
}
return text
}
function domToPos(cm, node, offset) {
var lineNode
if (node == cm.display.lineDiv) {
lineNode = cm.display.lineDiv.childNodes[offset]
if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
node = null; offset = 0
} else {
for (lineNode = node;; lineNode = lineNode.parentNode) {
if (!lineNode || lineNode == cm.display.lineDiv) { return null }
if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
}
}
for (var i = 0; i < cm.display.view.length; i++) {
var lineView = cm.display.view[i]
if (lineView.node == lineNode)
{ return locateNodeInLineView(lineView, node, offset) }
}
}
function locateNodeInLineView(lineView, node, offset) {
var wrapper = lineView.text.firstChild, bad = false
if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
if (node == wrapper) {
bad = true
node = wrapper.childNodes[offset]
offset = 0
if (!node) {
var line = lineView.rest ? lst(lineView.rest) : lineView.line
return badPos(Pos(lineNo(line), line.text.length), bad)
}
}
var textNode = node.nodeType == 3 ? node : null, topNode = node
if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
textNode = node.firstChild
if (offset) { offset = textNode.nodeValue.length }
}
while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
var measure = lineView.measure, maps = measure.maps
function find(textNode, topNode, offset) {
for (var i = -1; i < (maps ? maps.length : 0); i++) {
var map = 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()
// Tracks when input.reset has punted to just putting a short
// string into the textarea instead of the full selection.
this.inaccurateSelection = false
// Used to work around IE issue with selection being forgotten when focus moves away from textarea
this.hasSelection = false
this.composing = null
};
TextareaInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = this.cm
// Wraps and hides input textarea
var div = this.wrapper = hiddenTextarea()
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
var te = this.textarea = div.firstChild
display.wrapper.insertBefore(div, display.wrapper.firstChild)
// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
if (ios) { te.style.width = "0px" }
on(te, "input", function () {
if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
input.poll()
})
on(te, "paste", function (e) {
if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
cm.state.pasteIncoming = true
input.fastPoll()
})
function prepareCopyCut(e) {
if (signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()})
if (input.inaccurateSelection) {
input.prevInput = ""
input.inaccurateSelection = false
te.value = lastCopied.text.join("\n")
selectInput(te)
}
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm)
setLastCopied({lineWise: true, text: ranges.text})
if (e.type == "cut") {
cm.setSelections(ranges.ranges, null, sel_dontScroll)
} else {
input.prevInput = ""
te.value = ranges.text.join("\n")
selectInput(te)
}
}
if (e.type == "cut") { cm.state.cutIncoming = true }
}
on(te, "cut", prepareCopyCut)
on(te, "copy", prepareCopyCut)
on(display.scroller, "paste", function (e) {
if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
cm.state.pasteIncoming = true
input.focus()
})
// Prevent normal selection in the editor (we handle our own)
on(display.lineSpace, "selectstart", function (e) {
if (!eventInWidget(display, e)) { e_preventDefault(e) }
})
on(te, "compositionstart", function () {
var start = cm.getCursor("from")
if (input.composing) { input.composing.range.clear() }
input.composing = {
start: start,
range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
}
})
on(te, "compositionend", function () {
if (input.composing) {
input.poll()
input.composing.range.clear()
input.composing = null
}
})
};
TextareaInput.prototype.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) { return }
var minimal, selected, cm = this.cm, doc = cm.doc
if (cm.somethingSelected()) {
this.prevInput = ""
var range = doc.sel.primary()
minimal = hasCopyEvent &&
(range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000)
var content = minimal ? "-" : selected || cm.getSelection()
this.textarea.value = content
if (cm.state.focused) { selectInput(this.textarea) }
if (ie && ie_version >= 9) { this.hasSelection = content }
} else if (!typing) {
this.prevInput = this.textarea.value = ""
if (ie && ie_version >= 9) { this.hasSelection = null }
}
this.inaccurateSelection = minimal
};
TextareaInput.prototype.getField = function () { return this.textarea };
TextareaInput.prototype.supportsTouch = function () { return false };
TextareaInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
try { this.textarea.focus() }
catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
}
};
TextareaInput.prototype.blur = function () { this.textarea.blur() };
TextareaInput.prototype.resetPosition = function () {
this.wrapper.style.top = this.wrapper.style.left = 0
};
TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
TextareaInput.prototype.slowPoll = function () {
var this$1 = this;
if (this.pollingFast) { return }
this.polling.set(this.cm.options.pollInterval, function () {
this$1.poll()
if (this$1.cm.state.focused) { this$1.slowPoll() }
})
};
// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
TextareaInput.prototype.fastPoll = function () {
var missed = false, input = this
input.pollingFast = true
function p() {
var changed = input.poll()
if (!changed && !missed) {missed = true; input.polling.set(60, p)}
else {input.pollingFast = false; input.slowPoll()}
}
input.polling.set(20, p)
};
// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
TextareaInput.prototype.poll = function () {
var this$1 = this;
var cm = this.cm, input = this.textarea, prevInput = this.prevInput
// Since this is called a *lot*, try to bail out as cheaply as
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (this.contextMenuPending || !cm.state.focused ||
(hasSelection(input) && !prevInput && !this.composing) ||
cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
{ return false }
var text = input.value
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) { return false }
// Work around nonsensical selection resetting in IE9/10, and
// inexplicable appearance of private area unicode characters on
// some key combos in Mac (#2689).
if (ie && ie_version >= 9 && this.hasSelection === text ||
mac && /[\uf700-\uf7ff]/.test(text)) {
cm.display.input.reset()
return false
}
if (cm.doc.sel == cm.display.selForContextMenu) {
var first = text.charCodeAt(0)
if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
}
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length)
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
runInOp(cm, function () {
applyTextInput(cm, text.slice(same), prevInput.length - same,
null, this$1.composing ? "*compose" : null)
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
else { this$1.prevInput = text }
if (this$1.composing) {
this$1.composing.range.clear()
this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
{className: "CodeMirror-composing"})
}
})
return true
};
TextareaInput.prototype.ensurePolled = function () {
if (this.pollingFast && this.poll()) { this.pollingFast = false }
};
TextareaInput.prototype.onKeyPress = function () {
if (ie && ie_version >= 9) { this.hasSelection = null }
this.fastPoll()
};
TextareaInput.prototype.onContextMenu = function (e) {
var input = this, cm = input.cm, display = cm.display, te = input.textarea
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
if (!pos || presto) { return } // Opera is difficult.
// Reset the current text selection only if the click is done outside of the selection
// and 'resetSelectionOnContextMenu' option is true.
var reset = cm.options.resetSelectionOnContextMenu
if (reset && cm.doc.sel.contains(pos) == -1)
{ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
input.wrapper.style.cssText = "position: absolute"
var wrapperBox = input.wrapper.getBoundingClientRect()
te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"
var oldScrollY
if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
display.input.focus()
if (webkit) { window.scrollTo(null, oldScrollY) }
display.input.reset()
// Adds "Select all" to context menu in FF
if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
input.contextMenuPending = true
display.selForContextMenu = cm.doc.sel
clearTimeout(display.detectingSelectAll)
// Select-all will be greyed out if there's nothing to select, so
// this adds a zero-width space so that we can later check whether
// it got selected.
function prepareSelectAllHack() {
if (te.selectionStart != null) {
var selected = cm.somethingSelected()
var extval = "\u200b" + (selected ? te.value : "")
te.value = "\u21da" // Used to catch context-menu undo
te.value = extval
input.prevInput = selected ? "" : "\u200b"
te.selectionStart = 1; te.selectionEnd = extval.length
// Re-set this, in case some other handler touched the
// selection in the meantime.
display.selForContextMenu = cm.doc.sel
}
}
function rehide() {
input.contextMenuPending = false
input.wrapper.style.cssText = oldWrapperCSS
te.style.cssText = oldCSS
if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
// Try to detect the user choosing select-all
if (te.selectionStart != null) {
if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
var i = 0, poll = function () {
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
te.selectionEnd > 0 && input.prevInput == "\u200b")
{ operation(cm, selectAll)(cm) }
else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) }
else { display.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() }
};
TextareaInput.prototype.setUneditable = function () {};
TextareaInput.prototype.needsContentAttribute = false
function fromTextArea(textarea, options) {
options = options ? copyObj(options) : {}
options.value = textarea.value
if (!options.tabindex && textarea.tabIndex)
{ options.tabindex = textarea.tabIndex }
if (!options.placeholder && textarea.placeholder)
{ options.placeholder = textarea.placeholder }
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = activeElt()
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body
}
function save() {textarea.value = cm.getValue()}
var realSubmit
if (textarea.form) {
on(textarea.form, "submit", save)
// Deplorable hack to make the submit method do the right thing.
if (!options.leaveSubmitMethodAlone) {
var form = textarea.form
realSubmit = form.submit
try {
var wrappedSubmit = form.submit = function () {
save()
form.submit = realSubmit
form.submit()
form.submit = wrappedSubmit
}
} catch(e) {}
}
}
options.finishInit = function (cm) {
cm.save = save
cm.getTextArea = function () { return textarea; }
cm.toTextArea = function () {
cm.toTextArea = isNaN // Prevent this from being ran twice
save()
textarea.parentNode.removeChild(cm.getWrapperElement())
textarea.style.display = ""
if (textarea.form) {
off(textarea.form, "submit", save)
if (typeof textarea.form.submit == "function")
{ textarea.form.submit = realSubmit }
}
}
}
textarea.style.display = "none"
var cm = CodeMirror(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)
// INPUT HANDLING
CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
// MODE DEFINITION AND QUERYING
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror.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.23.0"
return CodeMirror;
})));
},{}],56:[function(require,module,exports){
require('../../modules/es6.object.assign');
module.exports = require('../../modules/$.core').Object.assign;
},{"../../modules/$.core":63,"../../modules/es6.object.assign":76}],57:[function(require,module,exports){
var $ = require('../../modules/$');
module.exports = function create(P, D){
return $.create(P, D);
};
},{"../../modules/$":71}],58:[function(require,module,exports){
require('../../modules/es6.object.keys');
module.exports = require('../../modules/$.core').Object.keys;
},{"../../modules/$.core":63,"../../modules/es6.object.keys":77}],59:[function(require,module,exports){
require('../../modules/es6.object.set-prototype-of');
module.exports = require('../../modules/$.core').Object.setPrototypeOf;
},{"../../modules/$.core":63,"../../modules/es6.object.set-prototype-of":78}],60:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],61:[function(require,module,exports){
var isObject = require('./$.is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./$.is-object":70}],62:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],63:[function(require,module,exports){
var core = module.exports = {version: '1.2.6'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],64:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./$.a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./$.a-function":60}],65:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],66:[function(require,module,exports){
var global = require('./$.global')
, core = require('./$.core')
, ctx = require('./$.ctx')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && key in target;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(param){
return this instanceof C ? new C(param) : C(param);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
module.exports = $export;
},{"./$.core":63,"./$.ctx":64,"./$.global":68}],67:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],68:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],69:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./$.cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./$.cof":62}],70:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],71:[function(require,module,exports){
var $Object = Object;
module.exports = {
create: $Object.create,
getProto: $Object.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: $Object.getOwnPropertyDescriptor,
setDesc: $Object.defineProperty,
setDescs: $Object.defineProperties,
getKeys: $Object.keys,
getNames: $Object.getOwnPropertyNames,
getSymbols: $Object.getOwnPropertySymbols,
each: [].forEach
};
},{}],72:[function(require,module,exports){
// 19.1.2.1 Object.assign(target, source, ...)
var $ = require('./$')
, toObject = require('./$.to-object')
, IObject = require('./$.iobject');
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = require('./$.fails')(function(){
var a = Object.assign
, A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, $$ = arguments
, $$len = $$.length
, index = 1
, getKeys = $.getKeys
, getSymbols = $.getSymbols
, isEnum = $.isEnum;
while($$len > index){
var S = IObject($$[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
}
return T;
} : Object.assign;
},{"./$":71,"./$.fails":67,"./$.iobject":69,"./$.to-object":75}],73:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./$.export')
, core = require('./$.core')
, fails = require('./$.fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./$.core":63,"./$.export":66,"./$.fails":67}],74:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var getDesc = require('./$').getDesc
, isObject = require('./$.is-object')
, anObject = require('./$.an-object');
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = require('./$.ctx')(Function.call, getDesc(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./$":71,"./$.an-object":61,"./$.ctx":64,"./$.is-object":70}],75:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./$.defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./$.defined":65}],76:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./$.export');
$export($export.S + $export.F, 'Object', {assign: require('./$.object-assign')});
},{"./$.export":66,"./$.object-assign":72}],77:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./$.to-object');
require('./$.object-sap')('keys', function($keys){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./$.object-sap":73,"./$.to-object":75}],78:[function(require,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./$.export');
$export($export.S, 'Object', {setPrototypeOf: require('./$.set-proto').set});
},{"./$.export":66,"./$.set-proto":74}],79:[function(require,module,exports){
'use strict';
var babelHelpers = require('./util/babelHelpers.js');
exports.__esModule = true;
/**
* document.activeElement
*/
exports['default'] = activeElement;
var _ownerDocument = require('./ownerDocument');
var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument);
function activeElement() {
var doc = arguments[0] === undefined ? document : arguments[0];
try {
return doc.activeElement;
} catch (e) {}
}
module.exports = exports['default'];
},{"./ownerDocument":88,"./util/babelHelpers.js":101}],80:[function(require,module,exports){
'use strict';
var hasClass = require('./hasClass');
module.exports = function addClass(element, className) {
if (element.classList) element.classList.add(className);else if (!hasClass(element)) element.className = element.className + ' ' + className;
};
},{"./hasClass":81}],81:[function(require,module,exports){
'use strict';
module.exports = function hasClass(element, className) {
if (element.classList) return !!className && element.classList.contains(className);else return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1;
};
},{}],82:[function(require,module,exports){
'use strict';
module.exports = {
addClass: require('./addClass'),
removeClass: require('./removeClass'),
hasClass: require('./hasClass')
};
},{"./addClass":80,"./hasClass":81,"./removeClass":83}],83:[function(require,module,exports){
'use strict';
module.exports = function removeClass(element, className) {
if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
};
},{}],84:[function(require,module,exports){
'use strict';
var contains = require('../query/contains'),
qsa = require('../query/querySelectorAll');
module.exports = function (selector, handler) {
return function (e) {
var top = e.currentTarget,
target = e.target,
matches = qsa(top, selector);
if (matches.some(function (match) {
return contains(match, target);
})) handler.call(this, e);
};
};
},{"../query/contains":89,"../query/querySelectorAll":94}],85:[function(require,module,exports){
'use strict';
var on = require('./on'),
off = require('./off'),
filter = require('./filter');
module.exports = { on: on, off: off, filter: filter };
},{"./filter":84,"./off":86,"./on":87}],86:[function(require,module,exports){
'use strict';
var canUseDOM = require('../util/inDOM');
var off = function off() {};
if (canUseDOM) {
off = (function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.removeEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.detachEvent('on' + eventName, handler);
};
})();
}
module.exports = off;
},{"../util/inDOM":106}],87:[function(require,module,exports){
'use strict';
var canUseDOM = require('../util/inDOM');
var on = function on() {};
if (canUseDOM) {
on = (function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.addEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.attachEvent('on' + eventName, handler);
};
})();
}
module.exports = on;
},{"../util/inDOM":106}],88:[function(require,module,exports){
"use strict";
exports.__esModule = true;
exports["default"] = ownerDocument;
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
module.exports = exports["default"];
},{}],89:[function(require,module,exports){
'use strict';
var canUseDOM = require('../util/inDOM');
var contains = (function () {
var root = canUseDOM && document.documentElement;
return root && root.contains ? function (context, node) {
return context.contains(node);
} : root && root.compareDocumentPosition ? function (context, node) {
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function (context, node) {
if (node) do {
if (node === context) return true;
} while (node = node.parentNode);
return false;
};
})();
module.exports = contains;
},{"../util/inDOM":106}],90:[function(require,module,exports){
'use strict';
module.exports = function getWindow(node) {
return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false;
};
},{}],91:[function(require,module,exports){
'use strict';
var contains = require('./contains'),
getWindow = require('./isWindow'),
ownerDocument = require('../ownerDocument');
module.exports = function offset(node) {
var doc = ownerDocument(node),
win = getWindow(doc),
docElem = doc && doc.documentElement,
box = { top: 0, left: 0, height: 0, width: 0 };
if (!doc) return;
// Make sure it's not a disconnected DOM node
if (!contains(docElem, node)) return box;
if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect();
if (box.width || box.height) {
box = {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0),
width: (box.width == null ? node.offsetWidth : box.width) || 0,
height: (box.height == null ? node.offsetHeight : box.height) || 0
};
}
return box;
};
},{"../ownerDocument":88,"./contains":89,"./isWindow":90}],92:[function(require,module,exports){
'use strict';
var babelHelpers = require('../util/babelHelpers.js');
exports.__esModule = true;
exports['default'] = offsetParent;
var _ownerDocument = require('../ownerDocument');
var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument);
var _style = require('../style');
var _style2 = babelHelpers.interopRequireDefault(_style);
function nodeName(node) {
return node.nodeName && node.nodeName.toLowerCase();
}
function offsetParent(node) {
var doc = (0, _ownerDocument2['default'])(node),
offsetParent = node && node.offsetParent;
while (offsetParent && nodeName(node) !== 'html' && (0, _style2['default'])(offsetParent, 'position') === 'static') {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || doc.documentElement;
}
module.exports = exports['default'];
},{"../ownerDocument":88,"../style":98,"../util/babelHelpers.js":101}],93:[function(require,module,exports){
'use strict';
var babelHelpers = require('../util/babelHelpers.js');
exports.__esModule = true;
exports['default'] = position;
var _offset = require('./offset');
var _offset2 = babelHelpers.interopRequireDefault(_offset);
var _offsetParent = require('./offsetParent');
var _offsetParent2 = babelHelpers.interopRequireDefault(_offsetParent);
var _scrollTop = require('./scrollTop');
var _scrollTop2 = babelHelpers.interopRequireDefault(_scrollTop);
var _scrollLeft = require('./scrollLeft');
var _scrollLeft2 = babelHelpers.interopRequireDefault(_scrollLeft);
var _style = require('../style');
var _style2 = babelHelpers.interopRequireDefault(_style);
function nodeName(node) {
return node.nodeName && node.nodeName.toLowerCase();
}
function position(node, offsetParent) {
var parentOffset = { top: 0, left: 0 },
offset;
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ((0, _style2['default'])(node, 'position') === 'fixed') {
offset = node.getBoundingClientRect();
} else {
offsetParent = offsetParent || (0, _offsetParent2['default'])(node);
offset = (0, _offset2['default'])(node);
if (nodeName(offsetParent) !== 'html') parentOffset = (0, _offset2['default'])(offsetParent);
parentOffset.top += parseInt((0, _style2['default'])(offsetParent, 'borderTopWidth'), 10) - (0, _scrollTop2['default'])(offsetParent) || 0;
parentOffset.left += parseInt((0, _style2['default'])(offsetParent, 'borderLeftWidth'), 10) - (0, _scrollLeft2['default'])(offsetParent) || 0;
}
// Subtract parent offsets and node margins
return babelHelpers._extends({}, offset, {
top: offset.top - parentOffset.top - (parseInt((0, _style2['default'])(node, 'marginTop'), 10) || 0),
left: offset.left - parentOffset.left - (parseInt((0, _style2['default'])(node, 'marginLeft'), 10) || 0)
});
}
module.exports = exports['default'];
},{"../style":98,"../util/babelHelpers.js":101,"./offset":91,"./offsetParent":92,"./scrollLeft":95,"./scrollTop":96}],94:[function(require,module,exports){
'use strict';
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var simpleSelectorRE = /^[\w-]*$/,
toArray = Function.prototype.bind.call(Function.prototype.call, [].slice);
module.exports = function qsa(element, selector) {
var maybeID = selector[0] === '#',
maybeClass = selector[0] === '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector,
isSimple = simpleSelectorRE.test(nameOnly),
found;
if (isSimple) {
if (maybeID) {
element = element.getElementById ? element : document;
return (found = element.getElementById(nameOnly)) ? [found] : [];
}
if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly));
return toArray(element.getElementsByTagName(selector));
}
return toArray(element.querySelectorAll(selector));
};
},{}],95:[function(require,module,exports){
'use strict';
var getWindow = require('./isWindow');
module.exports = function scrollTop(node, val) {
var win = getWindow(node);
if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft;
if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val;
};
},{"./isWindow":90}],96:[function(require,module,exports){
'use strict';
var getWindow = require('./isWindow');
module.exports = function scrollTop(node, val) {
var win = getWindow(node);
if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop;
if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val;
};
},{"./isWindow":90}],97:[function(require,module,exports){
'use strict';
var babelHelpers = require('../util/babelHelpers.js');
var _utilCamelizeStyle = require('../util/camelizeStyle');
var _utilCamelizeStyle2 = babelHelpers.interopRequireDefault(_utilCamelizeStyle);
var rposition = /^(top|right|bottom|left)$/;
var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;
module.exports = function _getComputedStyle(node) {
if (!node) throw new TypeError('No Element passed to `getComputedStyle()`');
var doc = node.ownerDocument;
return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72
getPropertyValue: function getPropertyValue(prop) {
var style = node.style;
prop = (0, _utilCamelizeStyle2['default'])(prop);
if (prop == 'float') prop = 'styleFloat';
var current = node.currentStyle[prop] || null;
if (current == null && style && style[prop]) current = style[prop];
if (rnumnonpx.test(current) && !rposition.test(prop)) {
// Remember the original values
var left = style.left;
var runStyle = node.runtimeStyle;
var rsLeft = runStyle && runStyle.left;
// Put in the new values to get a computed value out
if (rsLeft) runStyle.left = node.currentStyle.left;
style.left = prop === 'fontSize' ? '1em' : current;
current = style.pixelLeft + 'px';
// Revert the changed values
style.left = left;
if (rsLeft) runStyle.left = rsLeft;
}
return current;
}
};
};
},{"../util/babelHelpers.js":101,"../util/camelizeStyle":103}],98:[function(require,module,exports){
'use strict';
var camelize = require('../util/camelizeStyle'),
hyphenate = require('../util/hyphenateStyle'),
_getComputedStyle = require('./getComputedStyle'),
removeStyle = require('./removeStyle');
var has = Object.prototype.hasOwnProperty;
module.exports = function style(node, property, value) {
var css = '',
props = property;
if (typeof property === 'string') {
if (value === undefined) return node.style[camelize(property)] || _getComputedStyle(node).getPropertyValue(hyphenate(property));else (props = {})[property] = value;
}
for (var key in props) if (has.call(props, key)) {
!props[key] && props[key] !== 0 ? removeStyle(node, hyphenate(key)) : css += hyphenate(key) + ':' + props[key] + ';';
}
node.style.cssText += ';' + css;
};
},{"../util/camelizeStyle":103,"../util/hyphenateStyle":105,"./getComputedStyle":97,"./removeStyle":99}],99:[function(require,module,exports){
'use strict';
module.exports = function removeStyle(node, key) {
return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key);
};
},{}],100:[function(require,module,exports){
'use strict';
var canUseDOM = require('../util/inDOM');
var has = Object.prototype.hasOwnProperty,
transform = 'transform',
transition = {},
transitionTiming,
transitionDuration,
transitionProperty,
transitionDelay;
if (canUseDOM) {
transition = getTransitionProperties();
transform = transition.prefix + transform;
transitionProperty = transition.prefix + 'transition-property';
transitionDuration = transition.prefix + 'transition-duration';
transitionDelay = transition.prefix + 'transition-delay';
transitionTiming = transition.prefix + 'transition-timing-function';
}
module.exports = {
transform: transform,
end: transition.end,
property: transitionProperty,
timing: transitionTiming,
delay: transitionDelay,
duration: transitionDuration
};
function getTransitionProperties() {
var endEvent,
prefix = '',
transitions = {
O: 'otransitionend',
Moz: 'transitionend',
Webkit: 'webkitTransitionEnd',
ms: 'MSTransitionEnd'
};
var element = document.createElement('div');
for (var vendor in transitions) if (has.call(transitions, vendor)) {
if (element.style[vendor + 'TransitionProperty'] !== undefined) {
prefix = '-' + vendor.toLowerCase() + '-';
endEvent = transitions[vendor];
break;
}
}
if (!endEvent && element.style.transitionProperty !== undefined) endEvent = 'transitionend';
return { end: endEvent, prefix: prefix };
}
},{"../util/inDOM":106}],101:[function(require,module,exports){
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports === "object") {
factory(exports);
} else {
factory(root.babelHelpers = {});
}
})(this, function (global) {
var babelHelpers = global;
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
babelHelpers._extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
})
},{}],102:[function(require,module,exports){
"use strict";
var rHyphen = /-(.)/g;
module.exports = function camelize(string) {
return string.replace(rHyphen, function (_, chr) {
return chr.toUpperCase();
});
};
},{}],103:[function(require,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js
*/
'use strict';
var camelize = require('./camelize');
var msPattern = /^-ms-/;
module.exports = function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
};
},{"./camelize":102}],104:[function(require,module,exports){
'use strict';
var rUpper = /([A-Z])/g;
module.exports = function hyphenate(string) {
return string.replace(rUpper, '-$1').toLowerCase();
};
},{}],105:[function(require,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js
*/
"use strict";
var hyphenate = require("./hyphenate");
var msPattern = /^ms-/;
module.exports = function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, "-ms-");
};
},{"./hyphenate":104}],106:[function(require,module,exports){
'use strict';
module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
},{}],107:[function(require,module,exports){
'use strict';
var canUseDOM = require('./inDOM');
var size;
module.exports = function (recalc) {
if (!size || recalc) {
if (canUseDOM) {
var scrollDiv = document.createElement('div');
scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
scrollDiv.style.width = '50px';
scrollDiv.style.height = '50px';
scrollDiv.style.overflow = 'scroll';
document.body.appendChild(scrollDiv);
size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
}
}
return size;
};
},{"./inDOM":106}],108:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DocExplorer = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _graphql = require('graphql');
var _FieldDoc = require('./DocExplorer/FieldDoc');
var _FieldDoc2 = _interopRequireDefault(_FieldDoc);
var _SchemaDoc = require('./DocExplorer/SchemaDoc');
var _SchemaDoc2 = _interopRequireDefault(_SchemaDoc);
var _SearchBox = require('./DocExplorer/SearchBox');
var _SearchBox2 = _interopRequireDefault(_SearchBox);
var _SearchResults = require('./DocExplorer/SearchResults');
var _SearchResults2 = _interopRequireDefault(_SearchResults);
var _TypeDoc = require('./DocExplorer/TypeDoc');
var _TypeDoc2 = _interopRequireDefault(_TypeDoc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var initialNav = {
name: 'Schema',
title: 'Documentation Explorer'
};
/**
* DocExplorer
*
* Shows documentations for GraphQL definitions from the schema.
*
* Props:
*
* - schema: A required GraphQLSchema instance that provides GraphQL document
* definitions.
*
* Children:
*
* - Any provided children will be positioned in the right-hand-side of the
* top bar. Typically this will be a "close" button for temporary explorer.
*
*/
var DocExplorer = exports.DocExplorer = function (_React$Component) {
_inherits(DocExplorer, _React$Component);
function DocExplorer() {
_classCallCheck(this, DocExplorer);
var _this = _possibleConstructorReturn(this, (DocExplorer.__proto__ || Object.getPrototypeOf(DocExplorer)).call(this));
_this.handleNavBackClick = function () {
if (_this.state.navStack.length > 1) {
_this.setState({ navStack: _this.state.navStack.slice(0, -1) });
}
};
_this.handleClickTypeOrField = function (typeOrField) {
_this.showDoc(typeOrField);
};
_this.handleSearch = function (value) {
_this.showSearch(value);
};
_this.state = { navStack: [initialNav] };
return _this;
}
_createClass(DocExplorer, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return this.props.schema !== nextProps.schema || this.state.navStack !== nextState.navStack;
}
}, {
key: 'render',
value: function render() {
var schema = this.props.schema;
var navStack = this.state.navStack;
var navItem = navStack[navStack.length - 1];
var content = void 0;
if (schema === undefined) {
// Schema is undefined when it is being loaded via introspection.
content = _react2.default.createElement(
'div',
{ className: 'spinner-container' },
_react2.default.createElement('div', { className: 'spinner' })
);
} else if (!schema) {
// Schema is null when it explicitly does not exist, typically due to
// an error during introspection.
content = _react2.default.createElement(
'div',
{ className: 'error-container' },
'No Schema Available'
);
} else if (navItem.search) {
content = _react2.default.createElement(_SearchResults2.default, {
searchValue: navItem.search,
withinType: navItem.def,
schema: schema,
onClickType: this.handleClickTypeOrField,
onClickField: this.handleClickTypeOrField
});
} else if (navStack.length === 1) {
content = _react2.default.createElement(_SchemaDoc2.default, { schema: schema, onClickType: this.handleClickTypeOrField });
} else if ((0, _graphql.isType)(navItem.def)) {
content = _react2.default.createElement(_TypeDoc2.default, {
schema: schema,
type: navItem.def,
onClickType: this.handleClickTypeOrField,
onClickField: this.handleClickTypeOrField
});
} else {
content = _react2.default.createElement(_FieldDoc2.default, {
field: navItem.def,
onClickType: this.handleClickTypeOrField
});
}
var shouldSearchBoxAppear = navStack.length === 1 || (0, _graphql.isType)(navItem.def) && navItem.def.getFields;
var prevName = void 0;
if (navStack.length > 1) {
prevName = navStack[navStack.length - 2].name;
}
return _react2.default.createElement(
'div',
{ className: 'doc-explorer', key: navItem.name },
_react2.default.createElement(
'div',
{ className: 'doc-explorer-title-bar' },
prevName && _react2.default.createElement(
'div',
{
className: 'doc-explorer-back',
onClick: this.handleNavBackClick },
prevName
),
_react2.default.createElement(
'div',
{ className: 'doc-explorer-title' },
navItem.title || navItem.name
),
_react2.default.createElement(
'div',
{ className: 'doc-explorer-rhs' },
this.props.children
)
),
_react2.default.createElement(
'div',
{ className: 'doc-explorer-contents' },
shouldSearchBoxAppear && _react2.default.createElement(_SearchBox2.default, {
value: navItem.search,
placeholder: 'Search ' + navItem.name + '...',
onSearch: this.handleSearch
}),
content
)
);
}
// Public API
}, {
key: 'showDoc',
value: function showDoc(typeOrField) {
var navStack = this.state.navStack;
var topNav = navStack[navStack.length - 1];
if (topNav.def !== typeOrField) {
this.setState({
navStack: navStack.concat([{
name: typeOrField.name,
def: typeOrField
}])
});
}
}
// Public API
}, {
key: 'showDocForReference',
value: function showDocForReference(reference) {
if (reference.kind === 'Type') {
this.showDoc(reference.type);
} else if (reference.kind === 'Field') {
this.showDoc(reference.field);
} else if (reference.kind === 'Argument' && reference.field) {
this.showDoc(reference.field);
} else if (reference.kind === 'EnumValue' && reference.type) {
this.showDoc(reference.type);
}
}
// Public API
}, {
key: 'showSearch',
value: function showSearch(search) {
var navStack = this.state.navStack.slice();
var topNav = navStack[navStack.length - 1];
navStack[navStack.length - 1] = _extends({}, topNav, { search: search });
this.setState({ navStack: navStack });
}
}, {
key: 'reset',
value: function reset() {
this.setState({ navStack: [initialNav] });
}
}]);
return DocExplorer;
}(_react2.default.Component);
DocExplorer.propTypes = {
schema: _react.PropTypes.instanceOf(_graphql.GraphQLSchema)
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./DocExplorer/FieldDoc":110,"./DocExplorer/SchemaDoc":112,"./DocExplorer/SearchBox":113,"./DocExplorer/SearchResults":114,"./DocExplorer/TypeDoc":115,"graphql":144}],109:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Argument;
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _graphql = require('graphql');
var _TypeLink = require('./TypeLink');
var _TypeLink2 = _interopRequireDefault(_TypeLink);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Argument(_ref) {
var arg = _ref.arg,
onClickType = _ref.onClickType,
showDefaultValue = _ref.showDefaultValue;
return _react2.default.createElement(
'span',
{ className: 'arg' },
_react2.default.createElement(
'span',
{ className: 'arg-name' },
arg.name
),
': ',
_react2.default.createElement(_TypeLink2.default, { type: arg.type, onClick: onClickType }),
arg.defaultValue !== undefined && showDefaultValue !== false && _react2.default.createElement(
'span',
null,
' = ',
_react2.default.createElement(
'span',
{ className: 'arg-default-value' },
(0, _graphql.print)((0, _graphql.astFromValue)(arg.defaultValue, arg.type))
)
)
);
} /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
Argument.propTypes = {
arg: _react.PropTypes.object.isRequired,
onClickType: _react.PropTypes.func.isRequired,
showDefaultValue: _react.PropTypes.bool
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./TypeLink":116,"graphql":144}],110:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _Argument = require('./Argument');
var _Argument2 = _interopRequireDefault(_Argument);
var _MarkdownContent = require('./MarkdownContent');
var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent);
var _TypeLink = require('./TypeLink');
var _TypeLink2 = _interopRequireDefault(_TypeLink);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var FieldDoc = function (_React$Component) {
_inherits(FieldDoc, _React$Component);
function FieldDoc() {
_classCallCheck(this, FieldDoc);
return _possibleConstructorReturn(this, (FieldDoc.__proto__ || Object.getPrototypeOf(FieldDoc)).apply(this, arguments));
}
_createClass(FieldDoc, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.field !== nextProps.field;
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var field = this.props.field;
var argsDef = void 0;
if (field.args && field.args.length > 0) {
argsDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'arguments'
),
field.args.map(function (arg) {
return _react2.default.createElement(
'div',
{ key: arg.name, className: 'doc-category-item' },
_react2.default.createElement(
'div',
null,
_react2.default.createElement(_Argument2.default, { arg: arg, onClickType: _this2.props.onClickType })
),
_react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-value-description',
markdown: arg.description
})
);
})
);
}
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-type-description',
markdown: field.description || 'No Description'
}),
field.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-deprecation',
markdown: field.deprecationReason
}),
_react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'type'
),
_react2.default.createElement(_TypeLink2.default, { type: field.type, onClick: this.props.onClickType })
),
argsDef
);
}
}]);
return FieldDoc;
}(_react2.default.Component);
FieldDoc.propTypes = {
field: _react.PropTypes.object,
onClickType: _react.PropTypes.func
};
exports.default = FieldDoc;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./Argument":109,"./MarkdownContent":111,"./TypeLink":116}],111:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _marked = require('marked');
var _marked2 = _interopRequireDefault(_marked);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var MarkdownContent = function (_React$Component) {
_inherits(MarkdownContent, _React$Component);
function MarkdownContent() {
_classCallCheck(this, MarkdownContent);
return _possibleConstructorReturn(this, (MarkdownContent.__proto__ || Object.getPrototypeOf(MarkdownContent)).apply(this, arguments));
}
_createClass(MarkdownContent, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.markdown !== nextProps.markdown;
}
}, {
key: 'render',
value: function render() {
var markdown = this.props.markdown;
if (!markdown) {
return _react2.default.createElement('div', null);
}
var html = (0, _marked2.default)(markdown, { sanitize: true });
return _react2.default.createElement('div', {
className: this.props.className,
dangerouslySetInnerHTML: { __html: html }
});
}
}]);
return MarkdownContent;
}(_react2.default.Component);
MarkdownContent.propTypes = {
markdown: _react.PropTypes.string,
className: _react.PropTypes.string
};
exports.default = MarkdownContent;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"marked":287}],112:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _TypeLink = require('./TypeLink');
var _TypeLink2 = _interopRequireDefault(_TypeLink);
var _MarkdownContent = require('./MarkdownContent');
var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
// Render the top level Schema
var SchemaDoc = function (_React$Component) {
_inherits(SchemaDoc, _React$Component);
function SchemaDoc() {
_classCallCheck(this, SchemaDoc);
return _possibleConstructorReturn(this, (SchemaDoc.__proto__ || Object.getPrototypeOf(SchemaDoc)).apply(this, arguments));
}
_createClass(SchemaDoc, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.schema !== nextProps.schema;
}
}, {
key: 'render',
value: function render() {
var schema = this.props.schema;
var queryType = schema.getQueryType();
var mutationType = schema.getMutationType && schema.getMutationType();
var subscriptionType = schema.getSubscriptionType && schema.getSubscriptionType();
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-type-description',
markdown: 'A GraphQL schema provides a root type for each kind of operation.'
}),
_react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'root types'
),
_react2.default.createElement(
'div',
{ className: 'doc-category-item' },
_react2.default.createElement(
'span',
{ className: 'keyword' },
'query'
),
': ',
_react2.default.createElement(_TypeLink2.default, { type: queryType, onClick: this.props.onClickType })
),
mutationType && _react2.default.createElement(
'div',
{ className: 'doc-category-item' },
_react2.default.createElement(
'span',
{ className: 'keyword' },
'mutation'
),
': ',
_react2.default.createElement(_TypeLink2.default, { type: mutationType, onClick: this.props.onClickType })
),
subscriptionType && _react2.default.createElement(
'div',
{ className: 'doc-category-item' },
_react2.default.createElement(
'span',
{ className: 'keyword' },
'subscription'
),
': ',
_react2.default.createElement(_TypeLink2.default, {
type: subscriptionType,
onClick: this.props.onClickType
})
)
)
);
}
}]);
return SchemaDoc;
}(_react2.default.Component);
SchemaDoc.propTypes = {
schema: _react.PropTypes.object,
onClickType: _react.PropTypes.func
};
exports.default = SchemaDoc;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./MarkdownContent":111,"./TypeLink":116}],113:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _debounce = require('../../utility/debounce');
var _debounce2 = _interopRequireDefault(_debounce);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var SearchBox = function (_React$Component) {
_inherits(SearchBox, _React$Component);
function SearchBox(props) {
_classCallCheck(this, SearchBox);
var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this, props));
_this.handleChange = function (event) {
var value = event.target.value;
_this.setState({ value: value });
_this.debouncedOnSearch(value);
};
_this.handleClear = function () {
_this.setState({ value: '' });
_this.props.onSearch('');
};
_this.state = { value: props.value || '' };
_this.debouncedOnSearch = (0, _debounce2.default)(200, _this.props.onSearch);
return _this;
}
_createClass(SearchBox, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'label',
{ className: 'search-box' },
_react2.default.createElement('input', {
value: this.state.value,
onChange: this.handleChange,
type: 'text',
placeholder: this.props.placeholder
}),
this.state.value && _react2.default.createElement(
'div',
{ className: 'search-box-clear', onClick: this.handleClear },
'\u2715'
)
);
}
}]);
return SearchBox;
}(_react2.default.Component);
SearchBox.propTypes = {
value: _react.PropTypes.string,
placeholder: _react.PropTypes.string,
onSearch: _react.PropTypes.func
};
exports.default = SearchBox;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../../utility/debounce":127}],114:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _Argument = require('./Argument');
var _Argument2 = _interopRequireDefault(_Argument);
var _TypeLink = require('./TypeLink');
var _TypeLink2 = _interopRequireDefault(_TypeLink);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var SearchResults = function (_React$Component) {
_inherits(SearchResults, _React$Component);
function SearchResults() {
_classCallCheck(this, SearchResults);
return _possibleConstructorReturn(this, (SearchResults.__proto__ || Object.getPrototypeOf(SearchResults)).apply(this, arguments));
}
_createClass(SearchResults, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.schema !== nextProps.schema || this.props.searchValue !== nextProps.searchValue;
}
}, {
key: 'render',
value: function render() {
var searchValue = this.props.searchValue;
var withinType = this.props.withinType;
var schema = this.props.schema;
var onClickType = this.props.onClickType;
var onClickField = this.props.onClickField;
var matchedWithin = [];
var matchedTypes = [];
var matchedFields = [];
var typeMap = schema.getTypeMap();
var typeNames = Object.keys(typeMap);
// Move the within type name to be the first searched.
if (withinType) {
typeNames = typeNames.filter(function (n) {
return n !== withinType.name;
});
typeNames.unshift(withinType.name);
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function _loop() {
var typeName = _step.value;
if (matchedWithin.length + matchedTypes.length + matchedFields.length >= 100) {
return 'break';
}
var type = typeMap[typeName];
if (withinType !== type && isMatch(typeName, searchValue)) {
matchedTypes.push(_react2.default.createElement(
'div',
{ className: 'doc-category-item', key: typeName },
_react2.default.createElement(_TypeLink2.default, { type: type, onClick: onClickType })
));
}
if (type.getFields) {
(function () {
var fields = type.getFields();
Object.keys(fields).forEach(function (fieldName) {
var field = fields[fieldName];
var matchingArgs = void 0;
if (!isMatch(fieldName, searchValue)) {
if (field.args && field.args.length) {
matchingArgs = field.args.filter(function (arg) {
return isMatch(arg.name, searchValue);
});
if (matchingArgs.length === 0) {
return;
}
} else {
return;
}
}
var match = _react2.default.createElement(
'div',
{ className: 'doc-category-item', key: typeName + '.' + fieldName },
withinType !== type && [_react2.default.createElement(_TypeLink2.default, { key: 'type', type: type, onClick: onClickType }), '.'],
_react2.default.createElement(
'a',
{ className: 'field-name',
onClick: function onClick(event) {
return onClickField(field, type, event);
} },
field.name
),
matchingArgs && ['(', _react2.default.createElement(
'span',
{ key: 'args' },
matchingArgs.map(function (arg) {
return _react2.default.createElement(_Argument2.default, {
key: arg.name,
arg: arg,
onClickType: onClickType,
showDefaultValue: false
});
})
), ')']
);
if (withinType === type) {
matchedWithin.push(match);
} else {
matchedFields.push(match);
}
});
})();
}
};
for (var _iterator = typeNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ret = _loop();
if (_ret === 'break') break;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (matchedWithin.length + matchedTypes.length + matchedFields.length === 0) {
return _react2.default.createElement(
'span',
{ className: 'doc-alert-text' },
'No results found.'
);
}
if (withinType && matchedTypes.length + matchedFields.length > 0) {
return _react2.default.createElement(
'div',
null,
matchedWithin,
_react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'other results'
),
matchedTypes,
matchedFields
)
);
}
return _react2.default.createElement(
'div',
null,
matchedWithin,
matchedTypes,
matchedFields
);
}
}]);
return SearchResults;
}(_react2.default.Component);
SearchResults.propTypes = {
schema: _react.PropTypes.object,
withinType: _react.PropTypes.object,
searchValue: _react.PropTypes.string,
onClickType: _react.PropTypes.func,
onClickField: _react.PropTypes.func
};
exports.default = SearchResults;
function isMatch(sourceText, searchValue) {
try {
var escaped = searchValue.replace(/[^_0-9A-Za-z]/g, function (ch) {
return '\\' + ch;
});
return sourceText.search(new RegExp(escaped, 'i')) !== -1;
} catch (e) {
return sourceText.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./Argument":109,"./TypeLink":116}],115:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _graphql = require('graphql');
var _Argument = require('./Argument');
var _Argument2 = _interopRequireDefault(_Argument);
var _MarkdownContent = require('./MarkdownContent');
var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent);
var _TypeLink = require('./TypeLink');
var _TypeLink2 = _interopRequireDefault(_TypeLink);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var TypeDoc = function (_React$Component) {
_inherits(TypeDoc, _React$Component);
function TypeDoc(props) {
_classCallCheck(this, TypeDoc);
var _this = _possibleConstructorReturn(this, (TypeDoc.__proto__ || Object.getPrototypeOf(TypeDoc)).call(this, props));
_this.handleShowDeprecated = function () {
return _this.setState({ showDeprecated: true });
};
_this.state = { showDeprecated: false };
return _this;
}
_createClass(TypeDoc, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return this.props.type !== nextProps.type || this.props.schema !== nextProps.schema || this.state.showDeprecated !== nextState.showDeprecated;
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var schema = this.props.schema;
var type = this.props.type;
var onClickType = this.props.onClickType;
var onClickField = this.props.onClickField;
var typesTitle = void 0;
var types = void 0;
if (type instanceof _graphql.GraphQLUnionType) {
typesTitle = 'possible types';
types = schema.getPossibleTypes(type);
} else if (type instanceof _graphql.GraphQLInterfaceType) {
typesTitle = 'implementations';
types = schema.getPossibleTypes(type);
} else if (type instanceof _graphql.GraphQLObjectType) {
typesTitle = 'implements';
types = type.getInterfaces();
}
var typesDef = void 0;
if (types && types.length > 0) {
typesDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
typesTitle
),
types.map(function (subtype) {
return _react2.default.createElement(
'div',
{ key: subtype.name, className: 'doc-category-item' },
_react2.default.createElement(_TypeLink2.default, { type: subtype, onClick: onClickType })
);
})
);
}
// InputObject and Object
var fieldsDef = void 0;
var deprecatedFieldsDef = void 0;
if (type.getFields) {
(function () {
var fieldMap = type.getFields();
var fields = Object.keys(fieldMap).map(function (name) {
return fieldMap[name];
});
fieldsDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'fields'
),
fields.filter(function (field) {
return !field.isDeprecated;
}).map(function (field) {
return _react2.default.createElement(Field, {
key: field.name,
type: type,
field: field,
onClickType: onClickType,
onClickField: onClickField
});
})
);
var deprecatedFields = fields.filter(function (field) {
return field.isDeprecated;
});
if (deprecatedFields.length > 0) {
deprecatedFieldsDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'deprecated fields'
),
!_this2.state.showDeprecated ? _react2.default.createElement(
'button',
{ className: 'show-btn', onClick: _this2.handleShowDeprecated },
'Show deprecated fields...'
) : deprecatedFields.map(function (field) {
return _react2.default.createElement(Field, {
key: field.name,
type: type,
field: field,
onClickType: onClickType,
onClickField: onClickField
});
})
);
}
})();
}
var valuesDef = void 0;
var deprecatedValuesDef = void 0;
if (type instanceof _graphql.GraphQLEnumType) {
var values = type.getValues();
valuesDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'values'
),
values.filter(function (value) {
return !value.isDeprecated;
}).map(function (value) {
return _react2.default.createElement(EnumValue, { key: value.name, value: value });
})
);
var deprecatedValues = values.filter(function (value) {
return value.isDeprecated;
});
if (deprecatedValues.length > 0) {
deprecatedValuesDef = _react2.default.createElement(
'div',
{ className: 'doc-category' },
_react2.default.createElement(
'div',
{ className: 'doc-category-title' },
'deprecated values'
),
!this.state.showDeprecated ? _react2.default.createElement(
'button',
{ className: 'show-btn', onClick: this.handleShowDeprecated },
'Show deprecated values...'
) : deprecatedValues.map(function (value) {
return _react2.default.createElement(EnumValue, { key: value.name, value: value });
})
);
}
}
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-type-description',
markdown: type.description || 'No Description'
}),
type instanceof _graphql.GraphQLObjectType && typesDef,
fieldsDef,
deprecatedFieldsDef,
valuesDef,
deprecatedValuesDef,
!(type instanceof _graphql.GraphQLObjectType) && typesDef
);
}
}]);
return TypeDoc;
}(_react2.default.Component);
TypeDoc.propTypes = {
schema: _react.PropTypes.instanceOf(_graphql.GraphQLSchema),
type: _react.PropTypes.object,
onClickType: _react.PropTypes.func,
onClickField: _react.PropTypes.func
};
exports.default = TypeDoc;
function Field(_ref) {
var type = _ref.type,
field = _ref.field,
onClickType = _ref.onClickType,
onClickField = _ref.onClickField;
return _react2.default.createElement(
'div',
{ className: 'doc-category-item' },
_react2.default.createElement(
'a',
{
className: 'field-name',
onClick: function onClick(event) {
return onClickField(field, type, event);
} },
field.name
),
field.args && field.args.length > 0 && ['(', _react2.default.createElement(
'span',
{ key: 'args' },
field.args.map(function (arg) {
return _react2.default.createElement(_Argument2.default, {
key: arg.name,
arg: arg,
onClickType: onClickType
});
})
), ')'],
': ',
_react2.default.createElement(_TypeLink2.default, { type: field.type, onClick: onClickType }),
field.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-deprecation',
markdown: field.deprecationReason
})
);
}
Field.propTypes = {
type: _react.PropTypes.object,
field: _react.PropTypes.object,
onClickType: _react.PropTypes.func,
onClickField: _react.PropTypes.func
};
function EnumValue(_ref2) {
var value = _ref2.value;
return _react2.default.createElement(
'div',
{ className: 'doc-category-item' },
_react2.default.createElement(
'div',
{ className: 'enum-value' },
value.name
),
_react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-value-description',
markdown: value.description
}),
value.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, {
className: 'doc-deprecation',
markdown: value.deprecationReason
})
);
}
EnumValue.propTypes = {
value: _react.PropTypes.object
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./Argument":109,"./MarkdownContent":111,"./TypeLink":116,"graphql":144}],116:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _graphql = require('graphql');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
var TypeLink = function (_React$Component) {
_inherits(TypeLink, _React$Component);
function TypeLink() {
_classCallCheck(this, TypeLink);
return _possibleConstructorReturn(this, (TypeLink.__proto__ || Object.getPrototypeOf(TypeLink)).apply(this, arguments));
}
_createClass(TypeLink, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.type !== nextProps.type;
}
}, {
key: 'render',
value: function render() {
return renderType(this.props.type, this.props.onClick);
}
}]);
return TypeLink;
}(_react2.default.Component);
TypeLink.propTypes = {
type: _react.PropTypes.object,
onClick: _react.PropTypes.func
};
exports.default = TypeLink;
function renderType(type, _onClick) {
if (type instanceof _graphql.GraphQLNonNull) {
return _react2.default.createElement(
'span',
null,
renderType(type.ofType, _onClick),
'!'
);
}
if (type instanceof _graphql.GraphQLList) {
return _react2.default.createElement(
'span',
null,
'[',
renderType(type.ofType, _onClick),
']'
);
}
return _react2.default.createElement(
'a',
{ className: 'type-name', onClick: function onClick(event) {
return _onClick(type, event);
} },
type.name
);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"graphql":144}],117:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ExecuteButton = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ExecuteButton
*
* What a nice round shiny button. Shows a drop-down when there are multiple
* queries to run.
*/
var ExecuteButton = exports.ExecuteButton = function (_React$Component) {
_inherits(ExecuteButton, _React$Component);
function ExecuteButton(props) {
_classCallCheck(this, ExecuteButton);
var _this = _possibleConstructorReturn(this, (ExecuteButton.__proto__ || Object.getPrototypeOf(ExecuteButton)).call(this, props));
_this._onClick = function () {
if (_this.props.isRunning) {
_this.props.onStop();
} else {
_this.props.onRun();
}
};
_this._onOptionSelected = function (operation) {
_this.setState({ optionsOpen: false });
_this.props.onRun(operation.name && operation.name.value);
};
_this._onOptionsOpen = function (downEvent) {
var initialPress = true;
var downTarget = downEvent.target;
_this.setState({ highlight: null, optionsOpen: true });
var _onMouseUp = function onMouseUp(upEvent) {
if (initialPress && upEvent.target === downTarget) {
initialPress = false;
} else {
document.removeEventListener('mouseup', _onMouseUp);
_onMouseUp = null;
var isOptionsMenuClicked = downTarget.parentNode.compareDocumentPosition(upEvent.target) & Node.DOCUMENT_POSITION_CONTAINED_BY;
if (!isOptionsMenuClicked) {
// menu calls setState if it was clicked
_this.setState({ optionsOpen: false });
}
}
};
document.addEventListener('mouseup', _onMouseUp);
};
_this.state = {
optionsOpen: false,
highlight: null
};
return _this;
}
_createClass(ExecuteButton, [{
key: 'render',
value: function render() {
var _this2 = this;
var operations = this.props.operations;
var optionsOpen = this.state.optionsOpen;
var hasOptions = operations && operations.length > 1;
var options = null;
if (hasOptions && optionsOpen) {
(function () {
var highlight = _this2.state.highlight;
options = _react2.default.createElement(
'ul',
{ className: 'execute-options' },
operations.map(function (operation) {
return _react2.default.createElement(
'li',
{
key: operation.name ? operation.name.value : '*',
className: operation === highlight && 'selected',
onMouseOver: function onMouseOver() {
return _this2.setState({ highlight: operation });
},
onMouseOut: function onMouseOut() {
return _this2.setState({ highlight: null });
},
onMouseUp: function onMouseUp() {
return _this2._onOptionSelected(operation);
} },
operation.name ? operation.name.value : '<Unnamed>'
);
})
);
})();
}
// Allow click event if there is a running query or if there are not options
// for which operation to run.
var onClick = void 0;
if (this.props.isRunning || !hasOptions) {
onClick = this._onClick;
}
// Allow mouse down if there is no running query, there are options for
// which operation to run, and the dropdown is currently closed.
var onMouseDown = void 0;
if (!this.props.isRunning && hasOptions && !optionsOpen) {
onMouseDown = this._onOptionsOpen;
}
var pathJSX = this.props.isRunning ? _react2.default.createElement('path', { d: 'M 10 10 L 23 10 L 23 23 L 10 23 z' }) : _react2.default.createElement('path', { d: 'M 11 9 L 24 16 L 11 23 z' });
return _react2.default.createElement(
'div',
{ className: 'execute-button-wrap' },
_react2.default.createElement(
'button',
{
type: 'button',
className: 'execute-button',
onMouseDown: onMouseDown,
onClick: onClick,
title: 'Execute Query (Ctrl-Enter)' },
_react2.default.createElement(
'svg',
{ width: '34', height: '34' },
pathJSX
)
),
options
);
}
}]);
return ExecuteButton;
}(_react2.default.Component);
ExecuteButton.propTypes = {
onRun: _react.PropTypes.func,
onStop: _react.PropTypes.func,
isRunning: _react.PropTypes.bool,
operations: _react.PropTypes.array
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],118:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphiQL = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _reactDom = (typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _graphql = require('graphql');
var _ExecuteButton = require('./ExecuteButton');
var _ToolbarButton = require('./ToolbarButton');
var _ToolbarGroup = require('./ToolbarGroup');
var _ToolbarMenu = require('./ToolbarMenu');
var _ToolbarSelect = require('./ToolbarSelect');
var _QueryEditor = require('./QueryEditor');
var _VariableEditor = require('./VariableEditor');
var _ResultViewer = require('./ResultViewer');
var _DocExplorer = require('./DocExplorer');
var _CodeMirrorSizer = require('../utility/CodeMirrorSizer');
var _CodeMirrorSizer2 = _interopRequireDefault(_CodeMirrorSizer);
var _getQueryFacts = require('../utility/getQueryFacts');
var _getQueryFacts2 = _interopRequireDefault(_getQueryFacts);
var _getSelectedOperationName = require('../utility/getSelectedOperationName');
var _getSelectedOperationName2 = _interopRequireDefault(_getSelectedOperationName);
var _debounce = require('../utility/debounce');
var _debounce2 = _interopRequireDefault(_debounce);
var _find = require('../utility/find');
var _find2 = _interopRequireDefault(_find);
var _fillLeafs2 = require('../utility/fillLeafs');
var _elementPosition = require('../utility/elementPosition');
var _introspectionQueries = require('../utility/introspectionQueries');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* The top-level React component for GraphiQL, intended to encompass the entire
* browser viewport.
*
* @see https://github.com/graphql/graphiql#usage
*/
var GraphiQL = exports.GraphiQL = function (_React$Component) {
_inherits(GraphiQL, _React$Component);
function GraphiQL(props) {
_classCallCheck(this, GraphiQL);
// Ensure props are correct
var _this = _possibleConstructorReturn(this, (GraphiQL.__proto__ || Object.getPrototypeOf(GraphiQL)).call(this, props));
_initialiseProps.call(_this);
if (typeof props.fetcher !== 'function') {
throw new TypeError('GraphiQL requires a fetcher function.');
}
// Cache the storage instance
_this._storage = props.storage || window.localStorage;
// Determine the initial query to display.
var query = props.query !== undefined ? props.query : _this._storageGet('query') !== null ? _this._storageGet('query') : props.defaultQuery !== undefined ? props.defaultQuery : defaultQuery;
// Get the initial query facts.
var queryFacts = (0, _getQueryFacts2.default)(props.schema, query);
// Determine the initial variables to display.
var variables = props.variables !== undefined ? props.variables : _this._storageGet('variables');
// Determine the initial operationName to use.
var operationName = props.operationName !== undefined ? props.operationName : (0, _getSelectedOperationName2.default)(null, _this._storageGet('operationName'), queryFacts && queryFacts.operations);
// Initialize state
_this.state = _extends({
schema: props.schema,
query: query,
variables: variables,
operationName: operationName,
response: props.response,
editorFlex: Number(_this._storageGet('editorFlex')) || 1,
variableEditorOpen: Boolean(variables),
variableEditorHeight: Number(_this._storageGet('variableEditorHeight')) || 200,
docExplorerOpen: _this._storageGet('docExplorerOpen') === 'true' || false,
docExplorerWidth: Number(_this._storageGet('docExplorerWidth')) || 350,
isWaitingForResponse: false,
subscription: null
}, queryFacts);
// Ensure only the last executed editor query is rendered.
_this._editorQueryID = 0;
// Subscribe to the browser window closing, treating it as an unmount.
if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object') {
window.addEventListener('beforeunload', function () {
return _this.componentWillUnmount();
});
}
return _this;
}
_createClass(GraphiQL, [{
key: 'componentDidMount',
value: function componentDidMount() {
// Only fetch schema via introspection if a schema has not been
// provided, including if `null` was provided.
if (this.state.schema === undefined) {
this._fetchSchema();
}
// Utility for keeping CodeMirror correctly sized.
this.codeMirrorSizer = new _CodeMirrorSizer2.default();
global.g = this;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
var nextSchema = this.state.schema;
var nextQuery = this.state.query;
var nextVariables = this.state.variables;
var nextOperationName = this.state.operationName;
var nextResponse = this.state.response;
if (nextProps.schema !== undefined) {
nextSchema = nextProps.schema;
}
if (nextProps.query !== undefined) {
nextQuery = nextProps.query;
}
if (nextProps.variables !== undefined) {
nextVariables = nextProps.variables;
}
if (nextProps.operationName !== undefined) {
nextOperationName = nextProps.operationName;
}
if (nextProps.response !== undefined) {
nextResponse = nextProps.response;
}
if (nextSchema !== this.state.schema || nextQuery !== this.state.query || nextOperationName !== this.state.operationName) {
this._updateQueryFacts(nextQuery);
}
// If schema is not supplied via props and the fetcher changed, then
// remove the schema so fetchSchema() will be called with the new fetcher.
if (nextProps.schema === undefined && nextProps.fetcher !== this.props.fetcher) {
nextSchema = undefined;
}
this.setState({
schema: nextSchema,
query: nextQuery,
variables: nextVariables,
operationName: nextOperationName,
response: nextResponse
}, function () {
if (_this2.state.schema === undefined) {
_this2.docExplorerComponent.reset();
_this2._fetchSchema();
}
});
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
// If this update caused DOM nodes to have changed sizes, update the
// corresponding CodeMirror instance sizes to match.
this.codeMirrorSizer.updateSizes([this.queryEditorComponent, this.variableEditorComponent, this.resultComponent]);
}
// When the component is about to unmount, store any persistable state, such
// that when the component is remounted, it will use the last used values.
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._storageSet('query', this.state.query);
this._storageSet('variables', this.state.variables);
this._storageSet('operationName', this.state.operationName);
this._storageSet('editorFlex', this.state.editorFlex);
this._storageSet('variableEditorHeight', this.state.variableEditorHeight);
this._storageSet('docExplorerWidth', this.state.docExplorerWidth);
this._storageSet('docExplorerOpen', this.state.docExplorerOpen);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var children = _react2.default.Children.toArray(this.props.children);
var logo = (0, _find2.default)(children, function (child) {
return child.type === GraphiQL.Logo;
}) || _react2.default.createElement(GraphiQL.Logo, null);
var toolbar = (0, _find2.default)(children, function (child) {
return child.type === GraphiQL.Toolbar;
}) || _react2.default.createElement(
GraphiQL.Toolbar,
null,
_react2.default.createElement(_ToolbarButton.ToolbarButton, {
onClick: this.handlePrettifyQuery,
title: 'Prettify Query',
label: 'Prettify'
})
);
var footer = (0, _find2.default)(children, function (child) {
return child.type === GraphiQL.Footer;
});
var queryWrapStyle = {
WebkitFlex: this.state.editorFlex,
flex: this.state.editorFlex
};
var docWrapStyle = {
display: this.state.docExplorerOpen ? 'block' : 'none',
width: this.state.docExplorerWidth
};
var docExplorerWrapClasses = 'docExplorerWrap' + (this.state.docExplorerWidth < 200 ? ' doc-explorer-narrow' : '');
var variableOpen = this.state.variableEditorOpen;
var variableStyle = {
height: variableOpen ? this.state.variableEditorHeight : null
};
return _react2.default.createElement(
'div',
{ className: 'graphiql-container' },
_react2.default.createElement(
'div',
{ className: 'editorWrap' },
_react2.default.createElement(
'div',
{ className: 'topBarWrap' },
_react2.default.createElement(
'div',
{ className: 'topBar' },
logo,
_react2.default.createElement(_ExecuteButton.ExecuteButton, {
isRunning: Boolean(this.state.subscription),
onRun: this.handleRunQuery,
onStop: this.handleStopQuery,
operations: this.state.operations
}),
toolbar
),
!this.state.docExplorerOpen && _react2.default.createElement(
'button',
{
className: 'docExplorerShow',
onClick: this.handleToggleDocs },
'Docs'
)
),
_react2.default.createElement(
'div',
{
ref: function ref(n) {
_this3.editorBarComponent = n;
},
className: 'editorBar',
onMouseDown: this.handleResizeStart },
_react2.default.createElement(
'div',
{ className: 'queryWrap', style: queryWrapStyle },
_react2.default.createElement(_QueryEditor.QueryEditor, {
ref: function ref(n) {
_this3.queryEditorComponent = n;
},
schema: this.state.schema,
value: this.state.query,
onEdit: this.handleEditQuery,
onHintInformationRender: this.handleHintInformationRender,
onClickReference: this.handleClickReference,
onRunQuery: this.handleEditorRunQuery,
editorTheme: this.props.editorTheme
}),
_react2.default.createElement(
'div',
{ className: 'variable-editor', style: variableStyle },
_react2.default.createElement(
'div',
{
className: 'variable-editor-title',
style: { cursor: variableOpen ? 'row-resize' : 'n-resize' },
onMouseDown: this.handleVariableResizeStart },
'Query Variables'
),
_react2.default.createElement(_VariableEditor.VariableEditor, {
ref: function ref(n) {
_this3.variableEditorComponent = n;
},
value: this.state.variables,
variableToType: this.state.variableToType,
onEdit: this.handleEditVariables,
onHintInformationRender: this.handleHintInformationRender,
onRunQuery: this.handleEditorRunQuery,
editorTheme: this.props.editorTheme
})
)
),
_react2.default.createElement(
'div',
{ className: 'resultWrap' },
this.state.isWaitingForResponse && _react2.default.createElement(
'div',
{ className: 'spinner-container' },
_react2.default.createElement('div', { className: 'spinner' })
),
_react2.default.createElement(_ResultViewer.ResultViewer, {
ref: function ref(c) {
_this3.resultComponent = c;
},
value: this.state.response,
editorTheme: this.props.editorTheme
}),
footer
)
)
),
_react2.default.createElement(
'div',
{ className: docExplorerWrapClasses, style: docWrapStyle },
_react2.default.createElement('div', {
className: 'docExplorerResizer',
onMouseDown: this.handleDocsResizeStart
}),
_react2.default.createElement(
_DocExplorer.DocExplorer,
{
ref: function ref(c) {
_this3.docExplorerComponent = c;
},
schema: this.state.schema },
_react2.default.createElement(
'div',
{ className: 'docExplorerHide', onClick: this.handleToggleDocs },
'\u2715'
)
)
)
);
}
/**
* Get the query editor CodeMirror instance.
*
* @public
*/
}, {
key: 'getQueryEditor',
value: function getQueryEditor() {
return this.queryEditorComponent.getCodeMirror();
}
/**
* Get the variable editor CodeMirror instance.
*
* @public
*/
}, {
key: 'getVariableEditor',
value: function getVariableEditor() {
return this.variableEditorComponent.getCodeMirror();
}
/**
* Refresh all CodeMirror instances.
*
* @public
*/
}, {
key: 'refresh',
value: function refresh() {
this.queryEditorComponent.getCodeMirror().refresh();
this.variableEditorComponent.getCodeMirror().refresh();
this.resultComponent.getCodeMirror().refresh();
}
/**
* Inspect the query, automatically filling in selection sets for non-leaf
* fields which do not yet have them.
*
* @public
*/
}, {
key: 'autoCompleteLeafs',
value: function autoCompleteLeafs() {
var _this4 = this;
var _fillLeafs = (0, _fillLeafs2.fillLeafs)(this.state.schema, this.state.query, this.props.getDefaultFieldNames),
insertions = _fillLeafs.insertions,
result = _fillLeafs.result;
if (insertions && insertions.length > 0) {
(function () {
var editor = _this4.getQueryEditor();
editor.operation(function () {
var cursor = editor.getCursor();
var cursorIndex = editor.indexFromPos(cursor);
editor.setValue(result);
var added = 0;
var markers = insertions.map(function (_ref) {
var index = _ref.index,
string = _ref.string;
return editor.markText(editor.posFromIndex(index + added), editor.posFromIndex(index + (added += string.length)), {
className: 'autoInsertedLeaf',
clearOnEnter: true,
title: 'Automatically added leaf fields'
});
});
setTimeout(function () {
return markers.forEach(function (marker) {
return marker.clear();
});
}, 7000);
var newCursorIndex = cursorIndex;
insertions.forEach(function (_ref2) {
var index = _ref2.index,
string = _ref2.string;
if (index < cursorIndex) {
newCursorIndex += string.length;
}
});
editor.setCursor(editor.posFromIndex(newCursorIndex));
});
})();
}
return result;
}
// Private methods
}, {
key: '_fetchSchema',
value: function _fetchSchema() {
var _this5 = this;
var fetcher = this.props.fetcher;
var fetch = observableToPromise(fetcher({ query: _introspectionQueries.introspectionQuery }));
if (!isPromise(fetch)) {
this.setState({
response: 'Fetcher did not return a Promise for introspection.'
});
return;
}
fetch.then(function (result) {
if (result.data) {
return result;
}
// Try the stock introspection query first, falling back on the
// sans-subscriptions query for services which do not yet support it.
var fetch2 = observableToPromise(fetcher({
query: _introspectionQueries.introspectionQuerySansSubscriptions
}));
if (!isPromise(fetch)) {
throw new Error('Fetcher did not return a Promise for introspection.');
}
return fetch2;
}).then(function (result) {
// If a schema was provided while this fetch was underway, then
// satisfy the race condition by respecting the already
// provided schema.
if (_this5.state.schema !== undefined) {
return;
}
if (result && result.data) {
var schema = (0, _graphql.buildClientSchema)(result.data);
var queryFacts = (0, _getQueryFacts2.default)(schema, _this5.state.query);
_this5.setState(_extends({ schema: schema }, queryFacts));
} else {
var responseString = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
_this5.setState({
// Set schema to `null` to explicitly indicate that no schema exists.
schema: null,
response: responseString
});
}
}).catch(function (error) {
_this5.setState({
schema: null,
response: error && String(error.stack || error)
});
});
}
}, {
key: '_storageGet',
value: function _storageGet(name) {
if (this._storage) {
var value = this._storage.getItem('graphiql:' + name);
// Clean up any inadvertently saved null/undefined values.
if (value === 'null' || value === 'undefined') {
this._storage.removeItem('graphiql:' + name);
} else {
return value;
}
}
}
}, {
key: '_storageSet',
value: function _storageSet(name, value) {
if (this._storage) {
if (value) {
this._storage.setItem('graphiql:' + name, value);
} else {
this._storage.removeItem('graphiql:' + name);
}
}
}
}, {
key: '_fetchQuery',
value: function _fetchQuery(query, variables, operationName, cb) {
var _this6 = this;
var fetcher = this.props.fetcher;
var jsonVariables = null;
try {
jsonVariables = variables && variables.trim() !== '' ? JSON.parse(variables) : null;
} catch (error) {
throw new Error('Variables are invalid JSON: ' + error.message + '.');
}
if ((typeof jsonVariables === 'undefined' ? 'undefined' : _typeof(jsonVariables)) !== 'object') {
throw new Error('Variables are not a JSON object.');
}
var fetch = fetcher({
query: query,
variables: jsonVariables,
operationName: operationName
});
if (isPromise(fetch)) {
// If fetcher returned a Promise, then call the callback when the promise
// resolves, otherwise handle the error.
fetch.then(cb).catch(function (error) {
_this6.setState({
isWaitingForResponse: false,
response: error && String(error.stack || error)
});
});
} else if (isObservable(fetch)) {
// If the fetcher returned an Observable, then subscribe to it, calling
// the callback on each next value, and handling both errors and the
// completion of the Observable. Returns a Subscription object.
var subscription = fetch.subscribe({
next: cb,
error: function error(_error) {
_this6.setState({
isWaitingForResponse: false,
response: _error && String(_error.stack || _error),
subscription: null
});
},
complete: function complete() {
_this6.setState({
isWaitingForResponse: false,
subscription: null
});
}
});
return subscription;
} else {
throw new Error('Fetcher did not return Promise or Observable.');
}
}
}, {
key: '_runQueryAtCursor',
value: function _runQueryAtCursor() {
if (this.state.subscription) {
this.handleStopQuery();
return;
}
var operationName = void 0;
var operations = this.state.operations;
if (operations) {
var editor = this.getQueryEditor();
if (editor.hasFocus()) {
var cursor = editor.getCursor();
var cursorIndex = editor.indexFromPos(cursor);
// Loop through all operations to see if one contains the cursor.
for (var i = 0; i < operations.length; i++) {
var operation = operations[i];
if (operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) {
operationName = operation.name && operation.name.value;
break;
}
}
}
}
this.handleRunQuery(operationName);
}
}, {
key: '_didClickDragBar',
value: function _didClickDragBar(event) {
// Only for primary unmodified clicks
if (event.button !== 0 || event.ctrlKey) {
return false;
}
var target = event.target;
// We use codemirror's gutter as the drag bar.
if (target.className.indexOf('CodeMirror-gutter') !== 0) {
return false;
}
// Specifically the result window's drag bar.
var resultWindow = _reactDom2.default.findDOMNode(this.resultComponent);
while (target) {
if (target === resultWindow) {
return true;
}
target = target.parentNode;
}
return false;
}
}]);
return GraphiQL;
}(_react2.default.Component);
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.propTypes = {
fetcher: _react.PropTypes.func.isRequired,
schema: _react.PropTypes.instanceOf(_graphql.GraphQLSchema),
query: _react.PropTypes.string,
variables: _react.PropTypes.string,
operationName: _react.PropTypes.string,
response: _react.PropTypes.string,
storage: _react.PropTypes.shape({
getItem: _react.PropTypes.func,
setItem: _react.PropTypes.func
}),
defaultQuery: _react.PropTypes.string,
onEditQuery: _react.PropTypes.func,
onEditVariables: _react.PropTypes.func,
onEditOperationName: _react.PropTypes.func,
onToggleDocs: _react.PropTypes.func,
getDefaultFieldNames: _react.PropTypes.func,
editorTheme: _react.PropTypes.string
};
var _initialiseProps = function _initialiseProps() {
var _this7 = this;
this.handleClickReference = function (reference) {
_this7.setState({ docExplorerOpen: true }, function () {
_this7.docExplorerComponent.showDocForReference(reference);
});
};
this.handleRunQuery = function (selectedOperationName) {
_this7._editorQueryID++;
var queryID = _this7._editorQueryID;
// Use the edited query after autoCompleteLeafs() runs or,
// in case autoCompletion fails (the function returns undefined),
// the current query from the editor.
var editedQuery = _this7.autoCompleteLeafs() || _this7.state.query;
var variables = _this7.state.variables;
var operationName = _this7.state.operationName;
// If an operation was explicitly provided, different from the current
// operation name, then report that it changed.
if (selectedOperationName && selectedOperationName !== operationName) {
operationName = selectedOperationName;
var onEditOperationName = _this7.props.onEditOperationName;
if (onEditOperationName) {
onEditOperationName(operationName);
}
}
try {
_this7.setState({
isWaitingForResponse: true,
response: null,
operationName: operationName
});
// _fetchQuery may return a subscription.
var subscription = _this7._fetchQuery(editedQuery, variables, operationName, function (result) {
if (queryID === _this7._editorQueryID) {
_this7.setState({
isWaitingForResponse: false,
response: JSON.stringify(result, null, 2)
});
}
});
_this7.setState({ subscription: subscription });
} catch (error) {
_this7.setState({
isWaitingForResponse: false,
response: error.message
});
}
};
this.handleStopQuery = function () {
var subscription = _this7.state.subscription;
_this7.setState({
isWaitingForResponse: false,
subscription: null
});
if (subscription) {
subscription.unsubscribe();
}
};
this.handlePrettifyQuery = function () {
var editor = _this7.getQueryEditor();
editor.setValue((0, _graphql.print)((0, _graphql.parse)(editor.getValue())));
};
this.handleEditQuery = (0, _debounce2.default)(100, function (value) {
if (_this7.state.schema) {
_this7._updateQueryFacts(value);
}
_this7.setState({ query: value });
if (_this7.props.onEditQuery) {
return _this7.props.onEditQuery(value);
}
});
this._updateQueryFacts = function (query) {
var queryFacts = (0, _getQueryFacts2.default)(_this7.state.schema, query);
if (queryFacts) {
// Update operation name should any query names change.
var operationName = (0, _getSelectedOperationName2.default)(_this7.state.operations, _this7.state.operationName, queryFacts.operations);
// Report changing of operationName if it changed.
var onEditOperationName = _this7.props.onEditOperationName;
if (onEditOperationName && operationName !== _this7.state.operationName) {
onEditOperationName(operationName);
}
_this7.setState(_extends({
operationName: operationName
}, queryFacts));
}
};
this.handleEditVariables = function (value) {
_this7.setState({ variables: value });
if (_this7.props.onEditVariables) {
_this7.props.onEditVariables(value);
}
};
this.handleHintInformationRender = function (elem) {
elem.addEventListener('click', _this7._onClickHintInformation);
var _onRemoveFn = void 0;
elem.addEventListener('DOMNodeRemoved', _onRemoveFn = function onRemoveFn() {
elem.removeEventListener('DOMNodeRemoved', _onRemoveFn);
elem.removeEventListener('click', _this7._onClickHintInformation);
});
};
this.handleEditorRunQuery = function () {
_this7._runQueryAtCursor();
};
this._onClickHintInformation = function (event) {
if (event.target.className === 'typeName') {
var typeName = event.target.innerHTML;
var schema = _this7.state.schema;
if (schema) {
(function () {
var type = schema.getType(typeName);
if (type) {
_this7.setState({ docExplorerOpen: true }, function () {
_this7.docExplorerComponent.showDoc(type);
});
}
})();
}
}
};
this.handleToggleDocs = function () {
if (typeof _this7.props.onToggleDocs === 'function') {
_this7.props.onToggleDocs(!_this7.state.docExplorerOpen);
}
_this7.setState({ docExplorerOpen: !_this7.state.docExplorerOpen });
};
this.handleResizeStart = function (downEvent) {
if (!_this7._didClickDragBar(downEvent)) {
return;
}
downEvent.preventDefault();
var offset = downEvent.clientX - (0, _elementPosition.getLeft)(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
var editorBar = _reactDom2.default.findDOMNode(_this7.editorBarComponent);
var leftSize = moveEvent.clientX - (0, _elementPosition.getLeft)(editorBar) - offset;
var rightSize = editorBar.clientWidth - leftSize;
_this7.setState({ editorFlex: leftSize / rightSize });
};
var onMouseUp = function (_onMouseUp) {
function onMouseUp() {
return _onMouseUp.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp.toString();
};
return onMouseUp;
}(function () {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
this.handleDocsResizeStart = function (downEvent) {
downEvent.preventDefault();
var hadWidth = _this7.state.docExplorerWidth;
var offset = downEvent.clientX - (0, _elementPosition.getLeft)(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
var app = _reactDom2.default.findDOMNode(_this7);
var cursorPos = moveEvent.clientX - (0, _elementPosition.getLeft)(app) - offset;
var docsSize = app.clientWidth - cursorPos;
if (docsSize < 100) {
_this7.setState({ docExplorerOpen: false });
} else {
_this7.setState({
docExplorerOpen: true,
docExplorerWidth: Math.min(docsSize, 650)
});
}
};
var onMouseUp = function (_onMouseUp2) {
function onMouseUp() {
return _onMouseUp2.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp2.toString();
};
return onMouseUp;
}(function () {
if (!_this7.state.docExplorerOpen) {
_this7.setState({ docExplorerWidth: hadWidth });
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
this.handleVariableResizeStart = function (downEvent) {
downEvent.preventDefault();
var didMove = false;
var wasOpen = _this7.state.variableEditorOpen;
var hadHeight = _this7.state.variableEditorHeight;
var offset = downEvent.clientY - (0, _elementPosition.getTop)(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
didMove = true;
var editorBar = _reactDom2.default.findDOMNode(_this7.editorBarComponent);
var topSize = moveEvent.clientY - (0, _elementPosition.getTop)(editorBar) - offset;
var bottomSize = editorBar.clientHeight - topSize;
if (bottomSize < 60) {
_this7.setState({
variableEditorOpen: false,
variableEditorHeight: hadHeight
});
} else {
_this7.setState({
variableEditorOpen: true,
variableEditorHeight: bottomSize
});
}
};
var onMouseUp = function (_onMouseUp3) {
function onMouseUp() {
return _onMouseUp3.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp3.toString();
};
return onMouseUp;
}(function () {
if (!didMove) {
_this7.setState({ variableEditorOpen: !wasOpen });
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
};
GraphiQL.Logo = function GraphiQLLogo(props) {
return _react2.default.createElement(
'div',
{ className: 'title' },
props.children || _react2.default.createElement(
'span',
null,
'Graph',
_react2.default.createElement(
'em',
null,
'i'
),
'QL'
)
);
};
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.Toolbar = function GraphiQLToolbar(props) {
return _react2.default.createElement(
'div',
{ className: 'toolbar' },
props.children
);
};
// Add a button to the Toolbar.
GraphiQL.Button = _ToolbarButton.ToolbarButton;
GraphiQL.ToolbarButton = _ToolbarButton.ToolbarButton; // Don't break existing API.
// Add a group of buttons to the Toolbar
GraphiQL.Group = _ToolbarGroup.ToolbarGroup;
// Add a menu of items to the Toolbar.
GraphiQL.Menu = _ToolbarMenu.ToolbarMenu;
GraphiQL.MenuItem = _ToolbarMenu.ToolbarMenuItem;
// Add a select-option input to the Toolbar.
GraphiQL.Select = _ToolbarSelect.ToolbarSelect;
GraphiQL.SelectOption = _ToolbarSelect.ToolbarSelectOption;
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.Footer = function GraphiQLFooter(props) {
return _react2.default.createElement(
'div',
{ className: 'footer' },
props.children
);
};
var defaultQuery = '# Welcome to GraphiQL\n#\n# GraphiQL is an in-browser tool for writing, validating, and\n# testing GraphQL queries.\n#\n# Type queries into this side of the screen, and you will see intelligent\n# typeaheads aware of the current GraphQL type schema and live syntax and\n# validation errors highlighted within the text.\n#\n# GraphQL queries typically start with a "{" character. Lines that starts\n# with a # are ignored.\n#\n# An example GraphQL query might look like:\n#\n# {\n# field(arg: "value") {\n# subField\n# }\n# }\n#\n# Keyboard shortcuts:\n#\n# Run Query: Ctrl-Enter (or press the play button above)\n#\n# Auto Complete: Ctrl-Space (or just start typing)\n#\n\n';
// Duck-type promise detection.
function isPromise(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && typeof value.then === 'function';
}
// Duck-type Observable.take(1).toPromise()
function observableToPromise(observable) {
if (!isObservable(observable)) {
return observable;
}
return new Promise(function (resolve, reject) {
var subscription = observable.subscribe(function (v) {
resolve(v);
subscription.unsubscribe();
}, reject, function () {
reject(new Error('no value resolved'));
});
});
}
// Duck-type observable detection.
function isObservable(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && typeof value.subscribe === 'function';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../utility/CodeMirrorSizer":126,"../utility/debounce":127,"../utility/elementPosition":128,"../utility/fillLeafs":129,"../utility/find":130,"../utility/getQueryFacts":131,"../utility/getSelectedOperationName":132,"../utility/introspectionQueries":133,"./DocExplorer":108,"./ExecuteButton":117,"./QueryEditor":119,"./ResultViewer":120,"./ToolbarButton":121,"./ToolbarGroup":122,"./ToolbarMenu":123,"./ToolbarSelect":124,"./VariableEditor":125,"graphql":144}],119:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.QueryEditor = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _graphql = require('graphql');
var _marked = require('marked');
var _marked2 = _interopRequireDefault(_marked);
var _onHasCompletion = require('../utility/onHasCompletion');
var _onHasCompletion2 = _interopRequireDefault(_onHasCompletion);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* QueryEditor
*
* Maintains an instance of CodeMirror responsible for editing a GraphQL query.
*
* Props:
*
* - schema: A GraphQLSchema instance enabling editor linting and hinting.
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
var QueryEditor = exports.QueryEditor = function (_React$Component) {
_inherits(QueryEditor, _React$Component);
function QueryEditor(props) {
_classCallCheck(this, QueryEditor);
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
var _this = _possibleConstructorReturn(this, (QueryEditor.__proto__ || Object.getPrototypeOf(QueryEditor)).call(this));
_this._onKeyUp = function (cm, event) {
var code = event.keyCode;
if (code >= 65 && code <= 90 || // letters
!event.shiftKey && code >= 48 && code <= 57 || // numbers
event.shiftKey && code === 189 || // underscore
event.shiftKey && code === 50 || // @
event.shiftKey && code === 57 // (
) {
_this.editor.execCommand('autocomplete');
}
};
_this._onEdit = function () {
if (!_this.ignoreChangeEvent) {
_this.cachedValue = _this.editor.getValue();
if (_this.props.onEdit) {
_this.props.onEdit(_this.cachedValue);
}
}
};
_this._onHasCompletion = function (cm, data) {
(0, _onHasCompletion2.default)(cm, data, _this.props.onHintInformationRender);
};
_this.cachedValue = props.value || '';
return _this;
}
_createClass(QueryEditor, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
// Lazily require to ensure requiring GraphiQL outside of a Browser context
// does not produce an error.
var CodeMirror = require('codemirror');
require('codemirror/addon/hint/show-hint');
require('codemirror/addon/comment/comment');
require('codemirror/addon/edit/matchbrackets');
require('codemirror/addon/edit/closebrackets');
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/fold/brace-fold');
require('codemirror/addon/lint/lint');
require('codemirror/keymap/sublime');
require('codemirror-graphql/hint');
require('codemirror-graphql/lint');
require('codemirror-graphql/info');
require('codemirror-graphql/jump');
require('codemirror-graphql/mode');
this.editor = CodeMirror(this._node, {
value: this.props.value || '',
lineNumbers: true,
tabSize: 2,
mode: 'graphql',
theme: this.props.editorTheme || 'graphiql',
keyMap: 'sublime',
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
foldGutter: {
minFoldSize: 4
},
lint: {
schema: this.props.schema
},
hintOptions: {
schema: this.props.schema,
closeOnUnfocus: false,
completeSingle: false
},
info: {
schema: this.props.schema,
renderDescription: function renderDescription(text) {
return (0, _marked2.default)(text, { sanitize: true });
},
onClick: function onClick(reference) {
return _this2.props.onClickReference(reference);
}
},
jump: {
schema: this.props.schema,
onClick: function onClick(reference) {
return _this2.props.onClickReference(reference);
}
},
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
extraKeys: {
'Cmd-Space': function CmdSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
'Ctrl-Space': function CtrlSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
'Alt-Space': function AltSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
'Shift-Space': function ShiftSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
'Cmd-Enter': function CmdEnter() {
if (_this2.props.onRunQuery) {
_this2.props.onRunQuery();
}
},
'Ctrl-Enter': function CtrlEnter() {
if (_this2.props.onRunQuery) {
_this2.props.onRunQuery();
}
},
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
this.editor.on('change', this._onEdit);
this.editor.on('keyup', this._onKeyUp);
this.editor.on('hasCompletion', this._onHasCompletion);
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var CodeMirror = require('codemirror');
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true;
if (this.props.schema !== prevProps.schema) {
this.editor.options.lint.schema = this.props.schema;
this.editor.options.hintOptions.schema = this.props.schema;
this.editor.options.info.schema = this.props.schema;
this.editor.options.jump.schema = this.props.schema;
CodeMirror.signal(this.editor, 'change', this.editor);
}
if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
this.cachedValue = this.props.value;
this.editor.setValue(this.props.value);
}
this.ignoreChangeEvent = false;
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.editor.off('change', this._onEdit);
this.editor.off('keyup', this._onKeyUp);
this.editor.off('hasCompletion', this._onHasCompletion);
this.editor = null;
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
return _react2.default.createElement('div', {
className: 'query-editor',
ref: function ref(node) {
_this3._node = node;
}
});
}
/**
* Public API for retrieving the CodeMirror instance from this
* React component.
*/
}, {
key: 'getCodeMirror',
value: function getCodeMirror() {
return this.editor;
}
/**
* Public API for retrieving the DOM client height for this component.
*/
}, {
key: 'getClientHeight',
value: function getClientHeight() {
return this._node && this._node.clientHeight;
}
/**
* Render a custom UI for CodeMirror's hint which includes additional info
* about the type and description for the selected context.
*/
}]);
return QueryEditor;
}(_react2.default.Component);
QueryEditor.propTypes = {
schema: _react.PropTypes.instanceOf(_graphql.GraphQLSchema),
value: _react.PropTypes.string,
onEdit: _react.PropTypes.func,
onHintInformationRender: _react.PropTypes.func,
onClickReference: _react.PropTypes.func,
onRunQuery: _react.PropTypes.func,
editorTheme: _react.PropTypes.string
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../utility/onHasCompletion":134,"codemirror":55,"codemirror-graphql/hint":20,"codemirror-graphql/info":21,"codemirror-graphql/jump":22,"codemirror-graphql/lint":23,"codemirror-graphql/mode":24,"codemirror/addon/comment/comment":43,"codemirror/addon/edit/closebrackets":45,"codemirror/addon/edit/matchbrackets":46,"codemirror/addon/fold/brace-fold":47,"codemirror/addon/fold/foldgutter":49,"codemirror/addon/hint/show-hint":50,"codemirror/addon/lint/lint":51,"codemirror/keymap/sublime":54,"graphql":144,"marked":287}],120:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ResultViewer = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ResultViewer
*
* Maintains an instance of CodeMirror for viewing a GraphQL response.
*
* Props:
*
* - value: The text of the editor.
*
*/
var ResultViewer = exports.ResultViewer = function (_React$Component) {
_inherits(ResultViewer, _React$Component);
function ResultViewer() {
_classCallCheck(this, ResultViewer);
return _possibleConstructorReturn(this, (ResultViewer.__proto__ || Object.getPrototypeOf(ResultViewer)).apply(this, arguments));
}
_createClass(ResultViewer, [{
key: 'componentDidMount',
value: function componentDidMount() {
// Lazily require to ensure requiring GraphiQL outside of a Browser context
// does not produce an error.
var CodeMirror = require('codemirror');
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/fold/brace-fold');
require('codemirror/addon/dialog/dialog');
require('codemirror/addon/search/search');
require('codemirror/keymap/sublime');
require('codemirror-graphql/results/mode');
this.viewer = CodeMirror(this._node, {
lineWrapping: true,
value: this.props.value || '',
readOnly: true,
theme: this.props.editorTheme || 'graphiql',
mode: 'graphql-results',
keyMap: 'sublime',
foldGutter: {
minFoldSize: 4
},
gutters: ['CodeMirror-foldgutter'],
extraKeys: {
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.value !== nextProps.value;
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this.viewer.setValue(this.props.value || '');
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.viewer = null;
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return _react2.default.createElement('div', {
className: 'result-window',
ref: function ref(node) {
_this2._node = node;
}
});
}
/**
* Public API for retrieving the CodeMirror instance from this
* React component.
*/
}, {
key: 'getCodeMirror',
value: function getCodeMirror() {
return this.viewer;
}
/**
* Public API for retrieving the DOM client height for this component.
*/
}, {
key: 'getClientHeight',
value: function getClientHeight() {
return this._node && this._node.clientHeight;
}
}]);
return ResultViewer;
}(_react2.default.Component);
ResultViewer.propTypes = {
value: _react.PropTypes.string,
editorTheme: _react.PropTypes.string
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"codemirror":55,"codemirror-graphql/results/mode":25,"codemirror/addon/dialog/dialog":44,"codemirror/addon/fold/brace-fold":47,"codemirror/addon/fold/foldgutter":49,"codemirror/addon/search/search":52,"codemirror/keymap/sublime":54}],121:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToolbarButton = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ToolbarButton
*
* A button to use within the Toolbar.
*/
var ToolbarButton = exports.ToolbarButton = function (_React$Component) {
_inherits(ToolbarButton, _React$Component);
function ToolbarButton(props) {
_classCallCheck(this, ToolbarButton);
var _this = _possibleConstructorReturn(this, (ToolbarButton.__proto__ || Object.getPrototypeOf(ToolbarButton)).call(this, props));
_this.handleClick = function (e) {
e.preventDefault();
try {
_this.props.onClick();
_this.setState({ error: null });
} catch (error) {
_this.setState({ error: error });
}
};
_this.state = { error: null };
return _this;
}
_createClass(ToolbarButton, [{
key: 'render',
value: function render() {
var error = this.state.error;
return _react2.default.createElement(
'a',
{
className: 'toolbar-button' + (error ? ' error' : ''),
onMouseDown: preventDefault,
onClick: this.handleClick,
title: error ? error.message : this.props.title },
this.props.label
);
}
}]);
return ToolbarButton;
}(_react2.default.Component);
ToolbarButton.propTypes = {
onClick: _react.PropTypes.func,
title: _react.PropTypes.string,
label: _react.PropTypes.string
};
function preventDefault(e) {
e.preventDefault();
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],122:[function(require,module,exports){
(function (global){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToolbarGroup = ToolbarGroup;
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* ToolbarGroup
*
* A group of associated controls.
*/
function ToolbarGroup(_ref) {
var children = _ref.children;
return _react2.default.createElement(
"div",
{ className: "toolbar-button-group" },
children
);
} /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],123:[function(require,module,exports){
(function (global){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToolbarMenu = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.ToolbarMenuItem = ToolbarMenuItem;
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ToolbarMenu
*
* A menu style button to use within the Toolbar.
*/
var ToolbarMenu = exports.ToolbarMenu = function (_React$Component) {
_inherits(ToolbarMenu, _React$Component);
function ToolbarMenu(props) {
_classCallCheck(this, ToolbarMenu);
var _this = _possibleConstructorReturn(this, (ToolbarMenu.__proto__ || Object.getPrototypeOf(ToolbarMenu)).call(this, props));
_this.handleOpen = function (e) {
preventDefault(e);
_this.setState({ visible: true });
_this._subscribe();
};
_this.state = { visible: false };
return _this;
}
_createClass(ToolbarMenu, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._release();
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var visible = this.state.visible;
return _react2.default.createElement(
"a",
{
className: "toolbar-menu toolbar-button",
onClick: this.handleOpen.bind(this),
onMouseDown: preventDefault,
ref: function ref(node) {
_this2._node = node;
},
title: this.props.title },
this.props.label,
_react2.default.createElement(
"svg",
{ width: "14", height: "8" },
_react2.default.createElement("path", { fill: "#666", d: "M 5 1.5 L 14 1.5 L 9.5 7 z" })
),
_react2.default.createElement(
"ul",
{ className: 'toolbar-menu-items' + (visible ? ' open' : '') },
this.props.children
)
);
}
}, {
key: "_subscribe",
value: function _subscribe() {
if (!this._listener) {
this._listener = this.handleClick.bind(this);
document.addEventListener('click', this._listener);
}
}
}, {
key: "_release",
value: function _release() {
if (this._listener) {
document.removeEventListener('click', this._listener);
this._listener = null;
}
}
}, {
key: "handleClick",
value: function handleClick(e) {
if (this._node !== e.target) {
preventDefault(e);
this.setState({ visible: false });
this._release();
}
}
}]);
return ToolbarMenu;
}(_react2.default.Component);
ToolbarMenu.propTypes = {
title: _react.PropTypes.string,
label: _react.PropTypes.string
};
function ToolbarMenuItem(_ref) {
var onSelect = _ref.onSelect,
title = _ref.title,
label = _ref.label;
return _react2.default.createElement(
"li",
{
onMouseOver: function onMouseOver(e) {
e.target.className = 'hover';
},
onMouseOut: function onMouseOut(e) {
e.target.className = null;
},
onMouseDown: preventDefault,
onMouseUp: onSelect,
title: title },
label
);
}
ToolbarMenuItem.propTypes = {
onSelect: _react.PropTypes.func,
title: _react.PropTypes.string,
label: _react.PropTypes.string
};
function preventDefault(e) {
e.preventDefault();
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],124:[function(require,module,exports){
(function (global){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToolbarSelect = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.ToolbarSelectOption = ToolbarSelectOption;
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ToolbarSelect
*
* A select-option style button to use within the Toolbar.
*
*/
var ToolbarSelect = exports.ToolbarSelect = function (_React$Component) {
_inherits(ToolbarSelect, _React$Component);
function ToolbarSelect(props) {
_classCallCheck(this, ToolbarSelect);
var _this = _possibleConstructorReturn(this, (ToolbarSelect.__proto__ || Object.getPrototypeOf(ToolbarSelect)).call(this, props));
_this.handleOpen = function (e) {
preventDefault(e);
_this.setState({ visible: true });
_this._subscribe();
};
_this.state = { visible: false };
return _this;
}
_createClass(ToolbarSelect, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._release();
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var selectedChild = void 0;
var visible = this.state.visible;
var optionChildren = _react2.default.Children.map(this.props.children, function (child, i) {
if (!selectedChild || child.props.selected) {
selectedChild = child;
}
var onChildSelect = child.props.onSelect || _this2.props.onSelect && _this2.props.onSelect.bind(null, child.props.value, i);
return _react2.default.createElement(ToolbarSelectOption, _extends({}, child.props, { onSelect: onChildSelect }));
});
return _react2.default.createElement(
"a",
{
className: "toolbar-select toolbar-button",
onClick: this.handleOpen.bind(this),
onMouseDown: preventDefault,
ref: function ref(node) {
_this2._node = node;
},
title: this.props.title },
selectedChild.props.label,
_react2.default.createElement(
"svg",
{ width: "13", height: "10" },
_react2.default.createElement("path", { fill: "#666", d: "M 5 5 L 13 5 L 9 1 z" }),
_react2.default.createElement("path", { fill: "#666", d: "M 5 6 L 13 6 L 9 10 z" })
),
_react2.default.createElement(
"ul",
{ className: 'toolbar-select-options' + (visible ? ' open' : '') },
optionChildren
)
);
}
}, {
key: "_subscribe",
value: function _subscribe() {
if (!this._listener) {
this._listener = this.handleClick.bind(this);
document.addEventListener('click', this._listener);
}
}
}, {
key: "_release",
value: function _release() {
if (this._listener) {
document.removeEventListener('click', this._listener);
this._listener = null;
}
}
}, {
key: "handleClick",
value: function handleClick(e) {
if (this._node !== e.target) {
preventDefault(e);
this.setState({ visible: false });
this._release();
}
}
}]);
return ToolbarSelect;
}(_react2.default.Component);
ToolbarSelect.propTypes = {
title: _react.PropTypes.string,
label: _react.PropTypes.string,
onSelect: _react.PropTypes.func
};
function ToolbarSelectOption(_ref) {
var onSelect = _ref.onSelect,
label = _ref.label,
selected = _ref.selected;
return _react2.default.createElement(
"li",
{
onMouseOver: function onMouseOver(e) {
e.target.className = 'hover';
},
onMouseOut: function onMouseOut(e) {
e.target.className = null;
},
onMouseDown: preventDefault,
onMouseUp: onSelect },
label,
selected && _react2.default.createElement(
"svg",
{ width: "13", height: "13" },
_react2.default.createElement("polygon", { points: "4.851,10.462 0,5.611 2.314,3.297 4.851,5.835 10.686,0 13,2.314 4.851,10.462"
})
)
);
}
ToolbarSelectOption.propTypes = {
onSelect: _react.PropTypes.func,
selected: _react.PropTypes.bool,
label: _react.PropTypes.string,
value: _react.PropTypes.any
};
function preventDefault(e) {
e.preventDefault();
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],125:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VariableEditor = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _onHasCompletion = require('../utility/onHasCompletion');
var _onHasCompletion2 = _interopRequireDefault(_onHasCompletion);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* VariableEditor
*
* An instance of CodeMirror for editing variables defined in QueryEditor.
*
* Props:
*
* - variableToType: A mapping of variable name to GraphQLType.
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
var VariableEditor = exports.VariableEditor = function (_React$Component) {
_inherits(VariableEditor, _React$Component);
function VariableEditor(props) {
_classCallCheck(this, VariableEditor);
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
var _this = _possibleConstructorReturn(this, (VariableEditor.__proto__ || Object.getPrototypeOf(VariableEditor)).call(this));
_this._onKeyUp = function (cm, event) {
var code = event.keyCode;
if (code >= 65 && code <= 90 || // letters
!event.shiftKey && code >= 48 && code <= 57 || // numbers
event.shiftKey && code === 189 || // underscore
event.shiftKey && code === 222 // "
) {
_this.editor.execCommand('autocomplete');
}
};
_this._onEdit = function () {
if (!_this.ignoreChangeEvent) {
_this.cachedValue = _this.editor.getValue();
if (_this.props.onEdit) {
_this.props.onEdit(_this.cachedValue);
}
}
};
_this._onHasCompletion = function (cm, data) {
(0, _onHasCompletion2.default)(cm, data, _this.props.onHintInformationRender);
};
_this.cachedValue = props.value || '';
return _this;
}
_createClass(VariableEditor, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
// Lazily require to ensure requiring GraphiQL outside of a Browser context
// does not produce an error.
var CodeMirror = require('codemirror');
require('codemirror/addon/hint/show-hint');
require('codemirror/addon/edit/matchbrackets');
require('codemirror/addon/edit/closebrackets');
require('codemirror/addon/fold/brace-fold');
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/lint/lint');
require('codemirror/keymap/sublime');
require('codemirror-graphql/variables/hint');
require('codemirror-graphql/variables/lint');
require('codemirror-graphql/variables/mode');
this.editor = CodeMirror(this._node, {
value: this.props.value || '',
lineNumbers: true,
tabSize: 2,
mode: 'graphql-variables',
theme: this.props.editorTheme || 'graphiql',
keyMap: 'sublime',
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
foldGutter: {
minFoldSize: 4
},
lint: {
variableToType: this.props.variableToType
},
hintOptions: {
variableToType: this.props.variableToType
},
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
extraKeys: {
'Cmd-Space': function CmdSpace() {
return _this2.editor.showHint({ completeSingle: false });
},
'Ctrl-Space': function CtrlSpace() {
return _this2.editor.showHint({ completeSingle: false });
},
'Alt-Space': function AltSpace() {
return _this2.editor.showHint({ completeSingle: false });
},
'Shift-Space': function ShiftSpace() {
return _this2.editor.showHint({ completeSingle: false });
},
'Cmd-Enter': function CmdEnter() {
if (_this2.props.onRunQuery) {
_this2.props.onRunQuery();
}
},
'Ctrl-Enter': function CtrlEnter() {
if (_this2.props.onRunQuery) {
_this2.props.onRunQuery();
}
},
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
this.editor.on('change', this._onEdit);
this.editor.on('keyup', this._onKeyUp);
this.editor.on('hasCompletion', this._onHasCompletion);
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var CodeMirror = require('codemirror');
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true;
if (this.props.variableToType !== prevProps.variableToType) {
this.editor.options.lint.variableToType = this.props.variableToType;
this.editor.options.hintOptions.variableToType = this.props.variableToType;
CodeMirror.signal(this.editor, 'change', this.editor);
}
if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
this.cachedValue = this.props.value;
this.editor.setValue(this.props.value);
}
this.ignoreChangeEvent = false;
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.editor.off('change', this._onEdit);
this.editor.off('keyup', this._onKeyUp);
this.editor.off('hasCompletion', this._onHasCompletion);
this.editor = null;
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
return _react2.default.createElement('div', {
className: 'codemirrorWrap',
ref: function ref(node) {
_this3._node = node;
}
});
}
/**
* Public API for retrieving the CodeMirror instance from this
* React component.
*/
}, {
key: 'getCodeMirror',
value: function getCodeMirror() {
return this.editor;
}
/**
* Public API for retrieving the DOM client height for this component.
*/
}, {
key: 'getClientHeight',
value: function getClientHeight() {
return this._node && this._node.clientHeight;
}
}]);
return VariableEditor;
}(_react2.default.Component);
VariableEditor.propTypes = {
variableToType: _react.PropTypes.object,
value: _react.PropTypes.string,
onEdit: _react.PropTypes.func,
onHintInformationRender: _react.PropTypes.func,
onRunQuery: _react.PropTypes.func,
editorTheme: _react.PropTypes.string
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../utility/onHasCompletion":134,"codemirror":55,"codemirror-graphql/variables/hint":40,"codemirror-graphql/variables/lint":41,"codemirror-graphql/variables/mode":42,"codemirror/addon/edit/closebrackets":45,"codemirror/addon/edit/matchbrackets":46,"codemirror/addon/fold/brace-fold":47,"codemirror/addon/fold/foldgutter":49,"codemirror/addon/hint/show-hint":50,"codemirror/addon/lint/lint":51,"codemirror/keymap/sublime":54}],126:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* When a containing DOM node's height has been altered, trigger a resize of
* the related CodeMirror instance so that it is always correctly sized.
*/
var CodeMirrorSizer = function () {
function CodeMirrorSizer() {
_classCallCheck(this, CodeMirrorSizer);
this.sizes = [];
}
_createClass(CodeMirrorSizer, [{
key: "updateSizes",
value: function updateSizes(components) {
var _this = this;
components.forEach(function (component, i) {
var size = component.getClientHeight();
if (i <= _this.sizes.length && size !== _this.sizes[i]) {
component.getCodeMirror().setSize();
}
_this.sizes[i] = size;
});
}
}]);
return CodeMirrorSizer;
}();
exports.default = CodeMirrorSizer;
},{}],127:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = debounce;
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Provided a duration and a function, returns a new function which is called
* `duration` milliseconds after the last call.
*/
function debounce(duration, fn) {
var timeout = void 0;
return function () {
var _this = this,
_arguments = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
timeout = null;
fn.apply(_this, _arguments);
}, duration);
};
}
},{}],128:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLeft = getLeft;
exports.getTop = getTop;
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Utility functions to get a pixel distance from left/top of the window.
*/
function getLeft(initialElem) {
var pt = 0;
var elem = initialElem;
while (elem.offsetParent) {
pt += elem.offsetLeft;
elem = elem.offsetParent;
}
return pt;
}
function getTop(initialElem) {
var pt = 0;
var elem = initialElem;
while (elem.offsetParent) {
pt += elem.offsetTop;
elem = elem.offsetParent;
}
return pt;
}
},{}],129:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fillLeafs = fillLeafs;
var _graphql = require('graphql');
/**
* Given a document string which may not be valid due to terminal fields not
* representing leaf values (Spec Section: "Leaf Field Selections"), and a
* function which provides reasonable default field names for a given type,
* this function will attempt to produce a schema which is valid after filling
* in selection sets for the invalid fields.
*
* Note that there is no guarantee that the result will be a valid query, this
* utility represents a "best effort" which may be useful within IDE tools.
*/
function fillLeafs(schema, docString, getDefaultFieldNames) {
var insertions = [];
if (!schema) {
return { insertions: insertions, result: docString };
}
var ast = void 0;
try {
ast = (0, _graphql.parse)(docString);
} catch (error) {
return { insertions: insertions, result: docString };
}
var fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames;
var typeInfo = new _graphql.TypeInfo(schema);
(0, _graphql.visit)(ast, {
leave: function leave(node) {
typeInfo.leave(node);
},
enter: function enter(node) {
typeInfo.enter(node);
if (node.kind === 'Field' && !node.selectionSet) {
var fieldType = typeInfo.getType();
var selectionSet = buildSelectionSet(fieldType, fieldNameFn);
if (selectionSet) {
var indent = getIndentation(docString, node.loc.start);
insertions.push({
index: node.loc.end,
string: ' ' + (0, _graphql.print)(selectionSet).replace(/\n/g, '\n' + indent)
});
}
}
}
});
// Apply the insertions, but also return the insertions metadata.
return {
insertions: insertions,
result: withInsertions(docString, insertions)
};
}
// The default function to use for producing the default fields from a type.
// This function first looks for some common patterns, and falls back to
// including all leaf-type fields.
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
function defaultGetDefaultFieldNames(type) {
// If this type cannot access fields, then return an empty set.
if (!type.getFields) {
return [];
}
var fields = type.getFields();
// Is there an `id` field?
if (fields['id']) {
return ['id'];
}
// Is there an `edges` field?
if (fields['edges']) {
return ['edges'];
}
// Is there an `node` field?
if (fields['node']) {
return ['node'];
}
// Include all leaf-type fields.
var leafFieldNames = [];
Object.keys(fields).forEach(function (fieldName) {
if ((0, _graphql.isLeafType)(fields[fieldName].type)) {
leafFieldNames.push(fieldName);
}
});
return leafFieldNames;
}
// Given a GraphQL type, and a function which produces field names, recursively
// generate a SelectionSet which includes default fields.
function buildSelectionSet(type, getDefaultFieldNames) {
// Unwrap any non-null or list types.
var namedType = (0, _graphql.getNamedType)(type);
// Unknown types and leaf types do not have selection sets.
if (!type || (0, _graphql.isLeafType)(type)) {
return;
}
// Get an array of field names to use.
var fieldNames = getDefaultFieldNames(namedType);
// If there are no field names to use, return no selection set.
if (!Array.isArray(fieldNames) || fieldNames.length === 0) {
return;
}
// Build a selection set of each field, calling buildSelectionSet recursively.
return {
kind: 'SelectionSet',
selections: fieldNames.map(function (fieldName) {
var fieldDef = namedType.getFields()[fieldName];
var fieldType = fieldDef ? fieldDef.type : null;
return {
kind: 'Field',
name: {
kind: 'Name',
value: fieldName
},
selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames)
};
})
};
}
// Given an initial string, and a list of "insertion" { index, string } objects,
// return a new string with these insertions applied.
function withInsertions(initial, insertions) {
if (insertions.length === 0) {
return initial;
}
var edited = '';
var prevIndex = 0;
insertions.forEach(function (_ref) {
var index = _ref.index,
string = _ref.string;
edited += initial.slice(prevIndex, index) + string;
prevIndex = index;
});
edited += initial.slice(prevIndex);
return edited;
}
// Given a string and an index, look backwards to find the string of whitespace
// following the next previous line break.
function getIndentation(str, index) {
var indentStart = index;
var indentEnd = index;
while (indentStart) {
var c = str.charCodeAt(indentStart - 1);
// line break
if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) {
break;
}
indentStart--;
// not white space
if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) {
indentEnd = indentStart;
}
}
return str.substring(indentStart, indentEnd);
}
},{"graphql":144}],130:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = find;
/* eslint-disable no-undef */
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
function find(list, predicate) {
for (var i = 0; i < list.length; i++) {
if (predicate(list[i])) {
return list[i];
}
}
}
},{}],131:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getQueryFacts;
exports.collectVariables = collectVariables;
var _graphql = require('graphql');
/**
* Provided previous "queryFacts", a GraphQL schema, and a query document
* string, return a set of facts about that query useful for GraphiQL features.
*
* If the query cannot be parsed, returns undefined.
*/
function getQueryFacts(schema, documentStr) {
if (!documentStr) {
return;
}
var documentAST = void 0;
try {
documentAST = (0, _graphql.parse)(documentStr);
} catch (e) {
return;
}
var variableToType = schema ? collectVariables(schema, documentAST) : null;
// Collect operations by their names.
var operations = [];
documentAST.definitions.forEach(function (def) {
if (def.kind === 'OperationDefinition') {
operations.push(def);
}
});
return { variableToType: variableToType, operations: operations };
}
/**
* Provided a schema and a document, produces a `variableToType` Object.
*/
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
function collectVariables(schema, documentAST) {
var variableToType = Object.create(null);
documentAST.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition') {
var variableDefinitions = definition.variableDefinitions;
if (variableDefinitions) {
variableDefinitions.forEach(function (_ref) {
var variable = _ref.variable,
type = _ref.type;
var inputType = (0, _graphql.typeFromAST)(schema, type);
if (inputType) {
variableToType[variable.name.value] = inputType;
}
});
}
}
});
return variableToType;
}
},{"graphql":144}],132:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getSelectedOperationName;
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Provided optional previous operations and selected name, and a next list of
* operations, determine what the next selected operation should be.
*/
function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) {
// If there are not enough operations to bother with, return nothing.
if (!operations || operations.length < 1) {
return;
}
// If a previous selection still exists, continue to use it.
var names = operations.map(function (op) {
return op.name && op.name.value;
});
if (prevSelectedOperationName && names.indexOf(prevSelectedOperationName) !== -1) {
return prevSelectedOperationName;
}
// If a previous selection was the Nth operation, use the same Nth.
if (prevSelectedOperationName && prevOperations) {
var prevNames = prevOperations.map(function (op) {
return op.name && op.name.value;
});
var prevIndex = prevNames.indexOf(prevSelectedOperationName);
if (prevIndex && prevIndex < names.length) {
return names[prevIndex];
}
}
// Use the first operation.
return names[0];
}
},{}],133:[function(require,module,exports){
arguments[4][9][0].apply(exports,arguments)
},{"dup":9,"graphql":144}],134:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = onHasCompletion;
var _graphql = require('graphql');
var _marked = require('marked');
var _marked2 = _interopRequireDefault(_marked);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Render a custom UI for CodeMirror's hint which includes additional info
* about the type and description for the selected context.
*/
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
function onHasCompletion(cm, data, onHintInformationRender) {
var CodeMirror = require('codemirror');
var information = void 0;
var deprecation = void 0;
// When a hint result is selected, we augment the UI with information.
CodeMirror.on(data, 'select', function (ctx, el) {
// Only the first time (usually when the hint UI is first displayed)
// do we create the information nodes.
if (!information) {
(function () {
var hintsUl = el.parentNode;
// This "information" node will contain the additional info about the
// highlighted typeahead option.
information = document.createElement('div');
information.className = 'CodeMirror-hint-information';
hintsUl.appendChild(information);
// This "deprecation" node will contain info about deprecated usage.
deprecation = document.createElement('div');
deprecation.className = 'CodeMirror-hint-deprecation';
hintsUl.appendChild(deprecation);
// When CodeMirror attempts to remove the hint UI, we detect that it was
// removed and in turn remove the information nodes.
var _onRemoveFn = void 0;
hintsUl.addEventListener('DOMNodeRemoved', _onRemoveFn = function onRemoveFn(event) {
if (event.target === hintsUl) {
hintsUl.removeEventListener('DOMNodeRemoved', _onRemoveFn);
information = null;
deprecation = null;
_onRemoveFn = null;
}
});
})();
}
// Now that the UI has been set up, add info to information.
var description = ctx.description ? (0, _marked2.default)(ctx.description, { sanitize: true }) : 'Self descriptive.';
var type = ctx.type ? '<span class="infoType">' + renderType(ctx.type) + '</span>' : '';
information.innerHTML = '<div class="content">' + (description.slice(0, 3) === '<p>' ? '<p>' + type + description.slice(3) : type + description) + '</div>';
if (ctx.isDeprecated) {
var reason = ctx.deprecationReason ? (0, _marked2.default)(ctx.deprecationReason, { sanitize: true }) : '';
deprecation.innerHTML = '<span class="deprecation-label">Deprecated</span>' + reason;
deprecation.style.display = 'block';
} else {
deprecation.style.display = 'none';
}
// Additional rendering?
if (onHintInformationRender) {
onHintInformationRender(information);
}
});
}
function renderType(type) {
if (type instanceof _graphql.GraphQLNonNull) {
return renderType(type.ofType) + '!';
}
if (type instanceof _graphql.GraphQLList) {
return '[' + renderType(type.ofType) + ']';
}
return '<a class="typeName">' + type.name + '</a>';
}
},{"codemirror":55,"graphql":144,"marked":287}],135:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GraphQLError = GraphQLError;
var _location = require('../language/location');
/**
* A GraphQLError describes an Error found during the parse, validate, or
* execute phases of performing a GraphQL operation. In addition to a message
* and stack trace, it also includes information about the locations in a
* GraphQL document and/or execution result that correspond to the Error.
*/
function GraphQLError( // eslint-disable-line no-redeclare
message, nodes, source, positions, path, originalError) {
// Include (non-enumerable) stack trace.
if (originalError && originalError.stack) {
Object.defineProperty(this, 'stack', {
value: originalError.stack,
writable: true,
configurable: true
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, GraphQLError);
} else {
Object.defineProperty(this, 'stack', {
value: Error().stack,
writable: true,
configurable: true
});
}
// Compute locations in the source for the given nodes/positions.
var _source = source;
if (!_source && nodes && nodes.length > 0) {
var node = nodes[0];
_source = node && node.loc && node.loc.source;
}
var _positions = positions;
if (!_positions && nodes) {
_positions = nodes.filter(function (node) {
return Boolean(node.loc);
}).map(function (node) {
return node.loc.start;
});
}
if (_positions && _positions.length === 0) {
_positions = undefined;
}
var _locations = void 0;
var _source2 = _source; // seems here Flow need a const to resolve type.
if (_source2 && _positions) {
_locations = _positions.map(function (pos) {
return (0, _location.getLocation)(_source2, pos);
});
}
Object.defineProperties(this, {
message: {
value: message,
// By being enumerable, JSON.stringify will include `message` in the
// resulting output. This ensures that the simplist possible GraphQL
// service adheres to the spec.
enumerable: true,
writable: true
},
locations: {
// Coercing falsey values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: _locations || undefined,
// By being enumerable, JSON.stringify will include `locations` in the
// resulting output. This ensures that the simplist possible GraphQL
// service adheres to the spec.
enumerable: true
},
path: {
// Coercing falsey values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: path || undefined,
// By being enumerable, JSON.stringify will include `path` in the
// resulting output. This ensures that the simplist possible GraphQL
// service adheres to the spec.
enumerable: true
},
nodes: {
value: nodes || undefined
},
source: {
value: _source || undefined
},
positions: {
value: _positions || undefined
},
originalError: {
value: originalError
}
});
}
/**
* Copyright (c) 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.
*/
GraphQLError.prototype = Object.create(Error.prototype, {
constructor: { value: GraphQLError },
name: { value: 'GraphQLError' }
});
},{"../language/location":156}],136:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.formatError = formatError;
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*/
function formatError(error) {
(0, _invariant2.default)(error, 'Received null or undefined error.');
return {
message: error.message,
locations: error.locations,
path: error.path
};
}
/**
* Copyright (c) 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.
*/
},{"../jsutils/invariant":146}],137:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _GraphQLError = require('./GraphQLError');
Object.defineProperty(exports, 'GraphQLError', {
enumerable: true,
get: function get() {
return _GraphQLError.GraphQLError;
}
});
var _syntaxError = require('./syntaxError');
Object.defineProperty(exports, 'syntaxError', {
enumerable: true,
get: function get() {
return _syntaxError.syntaxError;
}
});
var _locatedError = require('./locatedError');
Object.defineProperty(exports, 'locatedError', {
enumerable: true,
get: function get() {
return _locatedError.locatedError;
}
});
var _formatError = require('./formatError');
Object.defineProperty(exports, 'formatError', {
enumerable: true,
get: function get() {
return _formatError.formatError;
}
});
},{"./GraphQLError":135,"./formatError":136,"./locatedError":138,"./syntaxError":139}],138:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.locatedError = locatedError;
var _GraphQLError = require('./GraphQLError');
/**
* Given an arbitrary Error, presumably thrown while attempting to execute a
* GraphQL operation, produce a new GraphQLError aware of the location in the
* document responsible for the original Error.
*/
function locatedError(originalError, nodes, path) {
// Note: this uses a brand-check to support GraphQL errors originating from
// other contexts.
if (originalError && originalError.path) {
return originalError;
}
var message = originalError ? originalError.message || String(originalError) : 'An unknown error occurred.';
return new _GraphQLError.GraphQLError(message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
}
/**
* Copyright (c) 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.
*/
},{"./GraphQLError":135}],139:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.syntaxError = syntaxError;
var _location = require('../language/location');
var _GraphQLError = require('./GraphQLError');
/**
* Produces a GraphQLError representing a syntax error, containing useful
* descriptive information about the syntax error's position in the source.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function syntaxError(source, position, description) {
var location = (0, _location.getLocation)(source, position);
var error = new _GraphQLError.GraphQLError('Syntax Error ' + source.name + ' (' + location.line + ':' + location.column + ') ' + description + '\n\n' + highlightSourceAtLocation(source, location), undefined, source, [position]);
return error;
}
/**
* Render a helpful description of the location of the error in the GraphQL
* Source document.
*/
function highlightSourceAtLocation(source, location) {
var line = location.line;
var prevLineNum = (line - 1).toString();
var lineNum = line.toString();
var nextLineNum = (line + 1).toString();
var padLen = nextLineNum.length;
var lines = source.body.split(/\r\n|[\n\r]/g);
return (line >= 2 ? lpad(padLen, prevLineNum) + ': ' + lines[line - 2] + '\n' : '') + lpad(padLen, lineNum) + ': ' + lines[line - 1] + '\n' + Array(2 + padLen + location.column).join(' ') + '^\n' + (line < lines.length ? lpad(padLen, nextLineNum) + ': ' + lines[line] + '\n' : '');
}
function lpad(len, str) {
return Array(len - str.length + 1).join(' ') + str;
}
},{"../language/location":156,"./GraphQLError":135}],140:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defaultFieldResolver = undefined;
exports.execute = execute;
exports.responsePathAsArray = responsePathAsArray;
var _iterall = require('iterall');
var _error = require('../error');
var _find = require('../jsutils/find');
var _find2 = _interopRequireDefault(_find);
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _typeFromAST = require('../utilities/typeFromAST');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _values = require('./values');
var _definition = require('../type/definition');
var _schema = require('../type/schema');
var _introspection = require('../type/introspection');
var _directives = require('../type/directives');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Implements the "Evaluating requests" section of the GraphQL specification.
*
* Returns a Promise that will eventually be resolved and never rejected.
*
* If the arguments to this function do not result in a legal execution context,
* a GraphQLError will be thrown immediately explaining the invalid input.
*/
/**
* Terminology
*
* "Definitions" are the generic name for top-level statements in the document.
* Examples of this include:
* 1) Operations (such as a query)
* 2) Fragments
*
* "Operations" are a generic name for requests in the document.
* Examples of this include:
* 1) query,
* 2) mutation
*
* "Selections" are the definitions that can appear legally and at
* single level of the query. These include:
* 1) field references e.g "a"
* 2) fragment "spreads" e.g. "...c"
* 3) inline fragment "spreads" e.g. "...on Type { a }"
*/
/**
* Data that must be available at all points during query execution.
*
* Namely, schema of the type system that is currently executing,
* and the fragments defined in the query document
*/
/**
* The result of GraphQL execution.
*
* - `data` is the result of a successful execution of the query.
* - `errors` is included when any errors occurred as a non-empty array.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function execute(schema, document, rootValue, contextValue, variableValues, operationName) {
(0, _invariant2.default)(schema, 'Must provide schema');
(0, _invariant2.default)(document, 'Must provide document');
(0, _invariant2.default)(schema instanceof _schema.GraphQLSchema, 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + 'not multiple versions of GraphQL installed in your node_modules directory.');
// Variables, if provided, must be an object.
(0, _invariant2.default)(!variableValues || typeof variableValues === 'object', 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.');
// If a valid context cannot be created due to incorrect arguments,
// this will throw an error.
var context = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName);
// Return a Promise that will eventually resolve to the data described by
// The "Response" section of the GraphQL specification.
//
// If errors are encountered while executing a GraphQL field, only that
// field and its descendants will be omitted, and sibling fields will still
// be executed. An execution which encounters errors will still result in a
// resolved Promise.
return new Promise(function (resolve) {
resolve(executeOperation(context, context.operation, rootValue));
}).then(undefined, function (error) {
// Errors from sub-fields of a NonNull type may propagate to the top level,
// at which point we still log the error and null the parent field, which
// in this case is the entire response.
context.errors.push(error);
return null;
}).then(function (data) {
if (!context.errors.length) {
return { data: data };
}
return { data: data, errors: context.errors };
});
}
/**
* Given a ResponsePath (found in the `path` entry in the information provided
* as the last argument to a field resolver), return an Array of the path keys.
*/
function responsePathAsArray(path) {
var flattened = [];
var curr = path;
while (curr) {
flattened.push(curr.key);
curr = curr.prev;
}
return flattened.reverse();
}
function addPath(prev, key) {
return { prev: prev, key: key };
}
/**
* Constructs a ExecutionContext object from the arguments passed to
* execute, which we will pass throughout the other execution methods.
*
* Throws a GraphQLError if a valid execution context cannot be created.
*/
function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName) {
var errors = [];
var operation = void 0;
var fragments = Object.create(null);
document.definitions.forEach(function (definition) {
switch (definition.kind) {
case Kind.OPERATION_DEFINITION:
if (!operationName && operation) {
throw new _error.GraphQLError('Must provide operation name if query contains multiple operations.');
}
if (!operationName || definition.name && definition.name.value === operationName) {
operation = definition;
}
break;
case Kind.FRAGMENT_DEFINITION:
fragments[definition.name.value] = definition;
break;
default:
throw new _error.GraphQLError('GraphQL cannot execute a request containing a ' + definition.kind + '.', [definition]);
}
});
if (!operation) {
if (operationName) {
throw new _error.GraphQLError('Unknown operation named "' + operationName + '".');
} else {
throw new _error.GraphQLError('Must provide an operation.');
}
}
var variableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {});
return {
schema: schema,
fragments: fragments,
rootValue: rootValue,
contextValue: contextValue,
operation: operation,
variableValues: variableValues,
errors: errors
};
}
/**
* Implements the "Evaluating operations" section of the spec.
*/
function executeOperation(exeContext, operation, rootValue) {
var type = getOperationRootType(exeContext.schema, operation);
var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
var path = undefined;
if (operation.operation === 'mutation') {
return executeFieldsSerially(exeContext, type, rootValue, path, fields);
}
return executeFields(exeContext, type, rootValue, path, fields);
}
/**
* Extracts the root type of the operation from the schema.
*/
function getOperationRootType(schema, operation) {
switch (operation.operation) {
case 'query':
return schema.getQueryType();
case 'mutation':
var mutationType = schema.getMutationType();
if (!mutationType) {
throw new _error.GraphQLError('Schema is not configured for mutations', [operation]);
}
return mutationType;
case 'subscription':
var subscriptionType = schema.getSubscriptionType();
if (!subscriptionType) {
throw new _error.GraphQLError('Schema is not configured for subscriptions', [operation]);
}
return subscriptionType;
default:
throw new _error.GraphQLError('Can only execute queries, mutations and subscriptions', [operation]);
}
}
/**
* Implements the "Evaluating selection sets" section of the spec
* for "write" mode.
*/
function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
return Object.keys(fields).reduce(function (prevPromise, responseName) {
return prevPromise.then(function (results) {
var fieldNodes = fields[responseName];
var fieldPath = addPath(path, responseName);
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
if (result === undefined) {
return results;
}
if (isThenable(result)) {
return result.then(function (resolvedResult) {
results[responseName] = resolvedResult;
return results;
});
}
results[responseName] = result;
return results;
});
}, Promise.resolve({}));
}
/**
* Implements the "Evaluating selection sets" section of the spec
* for "read" mode.
*/
function executeFields(exeContext, parentType, sourceValue, path, fields) {
var containsPromise = false;
var finalResults = Object.keys(fields).reduce(function (results, responseName) {
var fieldNodes = fields[responseName];
var fieldPath = addPath(path, responseName);
var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
if (result === undefined) {
return results;
}
results[responseName] = result;
if (isThenable(result)) {
containsPromise = true;
}
return results;
}, Object.create(null));
// If there are no promises, we can just return the object
if (!containsPromise) {
return finalResults;
}
// Otherwise, results is a map from field name to the result
// of resolving that field, which is possibly a promise. Return
// a promise that will return this same map, but with any
// promises replaced with the values they resolved to.
return promiseForObject(finalResults);
}
/**
* Given a selectionSet, adds all of the fields in that selection to
* the passed in map of fields, and returns it at the end.
*
* CollectFields requires the "runtime type" of an object. For a field which
* returns and Interface or Union type, the "runtime type" will be the actual
* Object type returned by that field.
*/
function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
for (var i = 0; i < selectionSet.selections.length; i++) {
var selection = selectionSet.selections[i];
switch (selection.kind) {
case Kind.FIELD:
if (!shouldIncludeNode(exeContext, selection.directives)) {
continue;
}
var _name = getFieldEntryKey(selection);
if (!fields[_name]) {
fields[_name] = [];
}
fields[_name].push(selection);
break;
case Kind.INLINE_FRAGMENT:
if (!shouldIncludeNode(exeContext, selection.directives) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
continue;
}
collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
break;
case Kind.FRAGMENT_SPREAD:
var fragName = selection.name.value;
if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection.directives)) {
continue;
}
visitedFragmentNames[fragName] = true;
var fragment = exeContext.fragments[fragName];
if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
continue;
}
collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
break;
}
}
return fields;
}
/**
* Determines if a field should be included based on the @include and @skip
* directives, where @skip has higher precidence than @include.
*/
function shouldIncludeNode(exeContext, directives) {
var skipNode = directives && (0, _find2.default)(directives, function (directive) {
return directive.name.value === _directives.GraphQLSkipDirective.name;
});
if (skipNode) {
var _getArgumentValues = (0, _values.getArgumentValues)(_directives.GraphQLSkipDirective, skipNode, exeContext.variableValues),
skipIf = _getArgumentValues.if;
if (skipIf === true) {
return false;
}
}
var includeNode = directives && (0, _find2.default)(directives, function (directive) {
return directive.name.value === _directives.GraphQLIncludeDirective.name;
});
if (includeNode) {
var _getArgumentValues2 = (0, _values.getArgumentValues)(_directives.GraphQLIncludeDirective, includeNode, exeContext.variableValues),
includeIf = _getArgumentValues2.if;
if (includeIf === false) {
return false;
}
}
return true;
}
/**
* Determines if a fragment is applicable to the given type.
*/
function doesFragmentConditionMatch(exeContext, fragment, type) {
var typeConditionNode = fragment.typeCondition;
if (!typeConditionNode) {
return true;
}
var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode);
if (conditionalType === type) {
return true;
}
if ((0, _definition.isAbstractType)(conditionalType)) {
var abstractType = conditionalType;
return exeContext.schema.isPossibleType(abstractType, type);
}
return false;
}
/**
* This function transforms a JS object `{[key: string]: Promise<T>}` into
* a `Promise<{[key: string]: T}>`
*
* This is akin to bluebird's `Promise.props`, but implemented only using
* `Promise.all` so it will work with any implementation of ES6 promises.
*/
function promiseForObject(object) {
var keys = Object.keys(object);
var valuesAndPromises = keys.map(function (name) {
return object[name];
});
return Promise.all(valuesAndPromises).then(function (values) {
return values.reduce(function (resolvedObject, value, i) {
resolvedObject[keys[i]] = value;
return resolvedObject;
}, Object.create(null));
});
}
/**
* Implements the logic to compute the key of a given field's entry
*/
function getFieldEntryKey(node) {
return node.alias ? node.alias.value : node.name.value;
}
/**
* Resolves the field on the given source object. In particular, this
* figures out the value that the field returns by calling its resolve function,
* then calls completeValue to complete promises, serialize scalars, or execute
* the sub-selection-set for objects.
*/
function resolveField(exeContext, parentType, source, fieldNodes, path) {
var fieldNode = fieldNodes[0];
var fieldName = fieldNode.name.value;
var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
if (!fieldDef) {
return;
}
var returnType = fieldDef.type;
var resolveFn = fieldDef.resolve || defaultFieldResolver;
// The resolve function's optional third argument is a context value that
// is provided to every resolve function within an execution. It is commonly
// used to represent an authenticated user, or request-specific caches.
var context = exeContext.contextValue;
// The resolve function's optional fourth argument is a collection of
// information about the current execution state.
var info = {
fieldName: fieldName,
fieldNodes: fieldNodes,
returnType: returnType,
parentType: parentType,
path: path,
schema: exeContext.schema,
fragments: exeContext.fragments,
rootValue: exeContext.rootValue,
operation: exeContext.operation,
variableValues: exeContext.variableValues
};
// Get the resolve function, regardless of if its result is normal
// or abrupt (error).
var result = resolveOrError(exeContext, fieldDef, fieldNode, resolveFn, source, context, info);
return completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result);
}
// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
// function. Returns the result of resolveFn or the abrupt-return Error object.
function resolveOrError(exeContext, fieldDef, fieldNode, resolveFn, source, context, info) {
try {
// Build a JS object of arguments from the field.arguments AST, using the
// variables scope to fulfill any variable references.
// TODO: find a way to memoize, in case this field is within a List type.
var args = (0, _values.getArgumentValues)(fieldDef, fieldNode, exeContext.variableValues);
return resolveFn(source, args, context, info);
} catch (error) {
// Sometimes a non-error is thrown, wrap it as an Error for a
// consistent interface.
return error instanceof Error ? error : new Error(error);
}
}
// This is a small wrapper around completeValue which detects and logs errors
// in the execution context.
function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {
// If the field type is non-nullable, then it is resolved without any
// protection from errors, however it still properly locates the error.
if (returnType instanceof _definition.GraphQLNonNull) {
return completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result);
}
// Otherwise, error protection is applied, logging the error and resolving
// a null value for this field if one is encountered.
try {
var completed = completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result);
if (isThenable(completed)) {
// If `completeValueWithLocatedError` returned a rejected promise, log
// the rejection error and resolve to null.
// Note: we don't rely on a `catch` method, but we do expect "thenable"
// to take a second callback for the error case.
return completed.then(undefined, function (error) {
exeContext.errors.push(error);
return Promise.resolve(null);
});
}
return completed;
} catch (error) {
// If `completeValueWithLocatedError` returned abruptly (threw an error),
// log the error and return null.
exeContext.errors.push(error);
return null;
}
}
// This is a small wrapper around completeValue which annotates errors with
// location information.
function completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result) {
try {
var completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
if (isThenable(completed)) {
return completed.then(undefined, function (error) {
return Promise.reject((0, _error.locatedError)(error, fieldNodes, responsePathAsArray(path)));
});
}
return completed;
} catch (error) {
throw (0, _error.locatedError)(error, fieldNodes, responsePathAsArray(path));
}
}
/**
* Implements the instructions for completeValue as defined in the
* "Field entries" section of the spec.
*
* If the field type is Non-Null, then this recursively completes the value
* for the inner type. It throws a field error if that completion returns null,
* as per the "Nullability" section of the spec.
*
* If the field type is a List, then this recursively completes the value
* for the inner type on each item in the list.
*
* If the field type is a Scalar or Enum, ensures the completed value is a legal
* value of the type by calling the `serialize` method of GraphQL type
* definition.
*
* If the field is an abstract type, determine the runtime type of the value
* and then complete based on that type
*
* Otherwise, the field type expects a sub-selection set, and will complete the
* value by evaluating all sub-selections.
*/
function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
// If result is a Promise, apply-lift over completeValue.
if (isThenable(result)) {
return result.then(function (resolved) {
return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
});
}
// If result is an Error, throw a located error.
if (result instanceof Error) {
throw result;
}
// If field type is NonNull, complete for inner type, and throw field error
// if result is null.
if (returnType instanceof _definition.GraphQLNonNull) {
var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
if (completed === null) {
throw new Error('Cannot return null for non-nullable field ' + info.parentType.name + '.' + info.fieldName + '.');
}
return completed;
}
// If result value is null-ish (null, undefined, or NaN) then return null.
if ((0, _isNullish2.default)(result)) {
return null;
}
// If field type is List, complete each item in the list with the inner type
if (returnType instanceof _definition.GraphQLList) {
return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
}
// If field type is a leaf type, Scalar or Enum, serialize to a valid value,
// returning null if serialization is not possible.
if (returnType instanceof _definition.GraphQLScalarType || returnType instanceof _definition.GraphQLEnumType) {
return completeLeafValue(returnType, result);
}
// If field type is an abstract type, Interface or Union, determine the
// runtime Object type and complete for that type.
if (returnType instanceof _definition.GraphQLInterfaceType || returnType instanceof _definition.GraphQLUnionType) {
return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
}
// If field type is Object, execute and complete all sub-selections.
if (returnType instanceof _definition.GraphQLObjectType) {
return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
}
// Not reachable. All possible output types have been considered.
throw new Error('Cannot complete value of unexpected type "' + String(returnType) + '".');
}
/**
* Complete a list value by completing each item in the list with the
* inner type
*/
function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
(0, _invariant2.default)((0, _iterall.isCollection)(result), 'Expected Iterable, but did not find one for field ' + info.parentType.name + '.' + info.fieldName + '.');
// This is specified as a simple map, however we're optimizing the path
// where the list contains no Promises by avoiding creating another Promise.
var itemType = returnType.ofType;
var containsPromise = false;
var completedResults = [];
(0, _iterall.forEach)(result, function (item, index) {
// No need to modify the info object containing the path,
// since from here on it is not ever accessed by resolver functions.
var fieldPath = addPath(path, index);
var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);
if (!containsPromise && isThenable(completedItem)) {
containsPromise = true;
}
completedResults.push(completedItem);
});
return containsPromise ? Promise.all(completedResults) : completedResults;
}
/**
* Complete a Scalar or Enum by serializing to a valid value, returning
* null if serialization is not possible.
*/
function completeLeafValue(returnType, result) {
(0, _invariant2.default)(returnType.serialize, 'Missing serialize method on type');
var serializedResult = returnType.serialize(result);
if ((0, _isNullish2.default)(serializedResult)) {
throw new Error('Expected a value of type "' + String(returnType) + '" but ' + ('received: ' + String(result)));
}
return serializedResult;
}
/**
* Complete a value of an abstract type by determining the runtime object type
* of that value, then complete the value for that type.
*/
function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);
if (isThenable(runtimeType)) {
// Cast to Promise
var runtimeTypePromise = runtimeType;
return runtimeTypePromise.then(function (resolvedRuntimeType) {
return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
});
}
return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
}
function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;
if (!(runtimeType instanceof _definition.GraphQLObjectType)) {
throw new _error.GraphQLError('Abstract type ' + returnType.name + ' must resolve to an Object type at ' + ('runtime for field ' + info.parentType.name + '.' + info.fieldName + ' with ') + ('value "' + String(result) + '", received "' + String(runtimeType) + '".'), fieldNodes);
}
if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
throw new _error.GraphQLError('Runtime Object type "' + runtimeType.name + '" is not a possible type ' + ('for "' + returnType.name + '".'), fieldNodes);
}
return runtimeType;
}
/**
* Complete an Object value by executing all sub-selections.
*/
function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
// If there is an isTypeOf predicate function, call it with the
// current result. If isTypeOf returns false, then raise an error rather
// than continuing execution.
if (returnType.isTypeOf) {
var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
if (isThenable(isTypeOf)) {
return isTypeOf.then(function (isTypeOfResult) {
if (!isTypeOfResult) {
throw invalidReturnTypeError(returnType, result, fieldNodes);
}
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result);
});
}
if (!isTypeOf) {
throw invalidReturnTypeError(returnType, result, fieldNodes);
}
}
return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result);
}
function invalidReturnTypeError(returnType, result, fieldNodes) {
return new _error.GraphQLError('Expected value of type "' + returnType.name + '" but got: ' + String(result) + '.', fieldNodes);
}
function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result) {
// Collect sub-fields to execute to complete this value.
var subFieldNodes = Object.create(null);
var visitedFragmentNames = Object.create(null);
for (var i = 0; i < fieldNodes.length; i++) {
var selectionSet = fieldNodes[i].selectionSet;
if (selectionSet) {
subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames);
}
}
return executeFields(exeContext, returnType, result, path, subFieldNodes);
}
/**
* If a resolveType function is not given, then a default resolve behavior is
* used which tests each possible type for the abstract type by calling
* isTypeOf for the object being coerced, returning the first type that matches.
*/
function defaultResolveTypeFn(value, context, info, abstractType) {
var possibleTypes = info.schema.getPossibleTypes(abstractType);
var promisedIsTypeOfResults = [];
for (var i = 0; i < possibleTypes.length; i++) {
var type = possibleTypes[i];
if (type.isTypeOf) {
var isTypeOfResult = type.isTypeOf(value, context, info);
if (isThenable(isTypeOfResult)) {
promisedIsTypeOfResults[i] = isTypeOfResult;
} else if (isTypeOfResult) {
return type;
}
}
}
if (promisedIsTypeOfResults.length) {
return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
for (var _i = 0; _i < isTypeOfResults.length; _i++) {
if (isTypeOfResults[_i]) {
return possibleTypes[_i];
}
}
});
}
}
/**
* If a resolve function is not given, then a default resolve behavior is used
* which takes the property of the source object of the same name as the field
* and returns it as the result, or if it's a function, returns the result
* of calling that function while passing along args and context.
*/
var defaultFieldResolver = exports.defaultFieldResolver = function defaultFieldResolver(source, args, context, info) {
// ensure source is a value for which property access is acceptable.
if (typeof source === 'object' || typeof source === 'function') {
var property = source[info.fieldName];
if (typeof property === 'function') {
return source[info.fieldName](args, context, info);
}
return property;
}
};
/**
* Checks to see if this object acts like a Promise, i.e. has a "then"
* function.
*/
function isThenable(value) {
return typeof value === 'object' && value !== null && typeof value.then === 'function';
}
/**
* This method looks up the field on the given type defintion.
* It has special casing for the two introspection fields, __schema
* and __typename. __typename is special because it can always be
* queried as a field, even in situations where no other fields
* are allowed, like on a Union. __schema could get automatically
* added to the query type, but that would require mutating type
* definitions, which would cause issues.
*/
function getFieldDef(schema, parentType, fieldName) {
if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
return _introspection.SchemaMetaFieldDef;
} else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
return _introspection.TypeMetaFieldDef;
} else if (fieldName === _introspection.TypeNameMetaFieldDef.name) {
return _introspection.TypeNameMetaFieldDef;
}
return parentType.getFields()[fieldName];
}
},{"../error":137,"../jsutils/find":145,"../jsutils/invariant":146,"../jsutils/isNullish":148,"../language/kinds":154,"../type/definition":161,"../type/directives":162,"../type/introspection":164,"../type/schema":166,"../utilities/typeFromAST":184,"./values":142,"iterall":215}],141:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _execute = require('./execute');
Object.defineProperty(exports, 'execute', {
enumerable: true,
get: function get() {
return _execute.execute;
}
});
Object.defineProperty(exports, 'defaultFieldResolver', {
enumerable: true,
get: function get() {
return _execute.defaultFieldResolver;
}
});
Object.defineProperty(exports, 'responsePathAsArray', {
enumerable: true,
get: function get() {
return _execute.responsePathAsArray;
}
});
},{"./execute":140}],142:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getVariableValues = getVariableValues;
exports.getArgumentValues = getArgumentValues;
var _iterall = require('iterall');
var _error = require('../error');
var _invariant = require('../jsutils/invariant');
var _invariant2 = _interopRequireDefault(_invariant);
var _isNullish = require('../jsutils/isNullish');
var _isNullish2 = _interopRequireDefault(_isNullish);
var _isInvalid = require('../jsutils/isInvalid');
var _isInvalid2 = _interopRequireDefault(_isInvalid);
var _keyMap = require('../jsutils/keyMap');
var _keyMap2 = _interopRequireDefault(_keyMap);
var _typeFromAST = require('../utilities/typeFromAST');
var _valueFromAST = require('../utilities/valueFromAST');
var _isValidJSValue = require('../utilities/isValidJSValue');
var _isValidLiteralValue = require('../utilities/isValidLiteralValue');
var _kinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_kinds);
var _printer = require('../language/printer');
var _definition = require('../type/definition');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Prepares an object map of variableValues of the correct type based on the
* provided variable definitions and arbitrary input. If the input cannot be
* parsed to match the variable definitions, a GraphQLError will be thrown.
*/
function getVariableValues(schema, varDefNodes, inputs) {
var coercedValues = Object.create(null);
for (var i = 0; i < varDefNodes.length; i++) {
var varDefNode = varDefNodes[i];
var varName = varDefNode.variable.name.value;
var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type);
if (!(0, _definition.isInputType)(varType)) {
throw new _error.GraphQLError('Variable "$' + varName + '" expected value of type ' + ('"' + (0, _printer.print)(varDefNode.type) + '" which cannot be used as an input type.'), [varDefNode.type]);
}
varType = varType;
var value = inputs[varName];
if ((0, _isInvalid2.default)(value)) {
var defaultValue = varDefNode.defaultValue;
if (defaultValue) {
coercedValues[varName] = (0, _valueFromAST.valueFromAST)(defaultValue, varType);
}
if (varType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Variable "$' + varName + '" of required type ' + ('"' + String(varType) + '" was not provided.'), [varDefNode]);
}
} else {
var errors = (0, _isValidJSValue.isValidJSValue)(value, varType);
if (errors.length) {
var message = errors ? '\n' + errors.join('\n') : '';
throw new _error.GraphQLError('Variable "$' + varName + '" got invalid value ' + (JSON.stringify(value) + '.' + message), [varDefNode]);
}
var coercedValue = coerceValue(varType, value);
(0, _invariant2.default)(!(0, _isInvalid2.default)(coercedValue), 'Should have reported error.');
coercedValues[varName] = coercedValue;
}
}
return coercedValues;
}
/**
* Prepares an object map of argument values given a list of argument
* definitions and list of argument AST nodes.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function getArgumentValues(def, node, variableValues) {
var argDefs = def.args;
var argNodes = node.arguments;
if (!argDefs || !argNodes) {
return {};
}
var coercedValues = Object.create(null);
var argNodeMap = (0, _keyMap2.default)(argNodes, function (arg) {
return arg.name.value;
});
for (var i = 0; i < argDefs.length; i++) {
var argDef = argDefs[i];
var name = argDef.name;
var argType = argDef.type;
var argumentNode = argNodeMap[name];
var defaultValue = argDef.defaultValue;
if (!argumentNode) {
if (!(0, _isInvalid2.default)(defaultValue)) {
coercedValues[name] = defaultValue;
} else if (argType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Argument "' + name + '" of required type ' + ('"' + String(argType) + '" was not provided.'), [node]);
}
} else if (argumentNode.value.kind === Kind.VARIABLE) {
var variableName = argumentNode.value.name.value;
if (variableValues && !(0, _isInvalid2.default)(variableValues[variableName])) {
// Note: this does not check that this variable value is correct.
// This assumes that this query has been validated and the variable
// usage here is of the correct type.
coercedValues[name] = variableValues[variableName];
} else if (!(0, _isInvalid2.default)(defaultValue)) {
coercedValues[name] = defaultValue;
} else if (argType instanceof _definition.GraphQLNonNull) {
throw new _error.GraphQLError('Argument "' + name + '" of required type "' + String(argType) + '" was ' + ('provided the variable "$' + variableName + '" which was not provided ') + 'a runtime value.', [argumentNode.value]);
}
} else {
var valueNode = argumentNode.value;
var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues);
if ((0, _isInvalid2.default)(coercedValue)) {
var errors = (0, _isValidLiteralValue.isValidLiteralValue)(argType, valueNode);
var message = errors ? '\n' + errors.join('\n') : '';
throw new _error.GraphQLError('Argument "' + name + '" got invalid value ' + (0, _printer.print)(valueNode) + '.' + message, [argumentNode.value]);
}
coercedValues[name] = coercedValue;
}
}
return coercedValues;
}
/**
* Given a type and any value, return a runtime value coerced to match the type.
*/
function coerceValue(type, value) {
// Ensure flow knows that we treat function params as const.
var _value = value;
if ((0, _isInvalid2.default)(_value)) {
return; // Intentionally return no value.
}
if (type instanceof _definition.GraphQLNonNull) {
if (_value === null) {
return; // Intentionally return no value.
}
return coerceValue(type.ofType, _value);
}
if (_value === null) {
// Intentionally return the value null.
return null;
}
if (type instanceof _definition.GraphQLList) {
var itemType = type.ofType;
if ((0, _iterall.isCollection)(_value)) {
var coercedValues = [];
var valueIter = (0, _iterall.createIterator)(_value);
if (!valueIter) {
return; // Intentionally return no value.
}
var step = void 0;
while (!(step = valueIter.next()).done) {
var itemValue = coerceValue(itemType, step.value);
if ((0, _isInvalid2.default)(itemValue)) {
return; // Intentionally return no value.
}
coercedValues.push(itemValue);
}
return coercedValues;
}
var coercedValue = coerceValue(itemType, _value);
if ((0, _isInvalid2.default)(coercedValue)) {
return; // Intentionally return no value.
}
return [coerceValue(itemType, _value)];
}
if (type instanceof _definition.GraphQLInputObjectType) {
if (typeof _value !== 'object') {
return; // Intentionally return no value.
}
var coercedObj = Object.create(null);
var fields = type.getFields();
var fieldNames = Object.keys(fields);
for (var i = 0; i < fieldNames.length; i++) {
var fieldName = fieldNames[i];
var field = fields[fieldName];
if ((0, _isInvalid2.default)(_value[fieldName])) {
if (!(0, _isInvalid2.default)(field.defaultValue)) {
coercedObj[fieldName] = field.defaultValue;
} else if (field.type instanceof _definition.GraphQLNonNull) {
return; // Intentionally return no value.
}
continue;
}
var fieldValue = coerceValue(field.type, _value[fieldName]);
if ((0, _isInvalid2.default)(fieldValue)) {
return; // Intentionally return no value.
}
coercedObj[fieldName] = fieldValue;
}
return coercedObj;
}
(0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type');
var parsed = type.parseValue(_value);
if ((0, _isNullish2.default)(parsed)) {
// null or invalid values represent a failure to parse correctly,
// in which case no value is returned.
return;
}
return parsed;
}
},{"../error":137,"../jsutils/invariant":146,"../jsutils/isInvalid":147,"../jsutils/isNullish":148,"../jsutils/keyMap":149,"../language/kinds":154,"../language/printer":158,"../type/definition":161,"../utilities/isValidJSValue":179,"../utilities/isValidLiteralValue":180,"../utilities/typeFromAST":184,"../utilities/valueFromAST":185,"iterall":215}],143:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.graphql = graphql;
var _source = require('./language/source');
var _parser = require('./language/parser');
var _validate = require('./validation/validate');
var _execute = require('./execution/execute');
/**
* This is the primary entry point function for fulfilling GraphQL operations
* by parsing, validating, and executing a GraphQL document along side a
* GraphQL schema.
*
* More sophisticated GraphQL servers, such as those which persist queries,
* may wish to separate the validation and execution phases to a static time
* tooling step, and a server runtime step.
*
* schema:
* The GraphQL type system to use when validating and executing a query.
* requestString:
* A GraphQL language formatted string representing the requested operation.
* rootValue:
* The value provided as the first argument to resolver functions on the top
* level type (e.g. the query object type).
* variableValues:
* A mapping of variable name to runtime value to use for all variables
* defined in the requestString.
* operationName:
* The name of the operation to use if requestString contains multiple
* possible operations. Can be omitted if requestString contains only
* one operation.
*/
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function graphql(schema, requestString, rootValue, contextValue, variableValues, operationName) {
return new Promise(function (resolve) {
var source = new _source.Source(requestString || '', 'GraphQL request');
var documentAST = (0, _parser.parse)(source);
var validationErrors = (0, _validate.validate)(schema, documentAST);
if (validationErrors.length > 0) {
resolve({ errors: validationErrors });
} else {
resolve((0, _execute.execute)(schema, documentAST, rootValue, contextValue, variableValues, operationName));
}
}).then(undefined, function (error) {
return { errors: [error] };
});
}
},{"./execution/execute":140,"./language/parser":157,"./language/source":159,"./validation/validate":213}],144:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _graphql = require('./graphql');
Object.defineProperty(exports, 'graphql', {
enumerable: true,
get: function get() {
return _graphql.graphql;
}
});
var _type = require('./type');
Object.defineProperty(exports, 'GraphQLSchema', {
enumerable: true,
get: function get() {
return _type.GraphQLSchema;
}
});
Object.defineProperty(exports, 'GraphQLScalarType', {
enumerable: true,
get: function get() {
return _type.GraphQLScalarType;
}
});
Object.defineProperty(exports, 'GraphQLObjectType', {
enumerable: true,
get: function get() {
return _type.GraphQLObjectType;
}
});
Object.defineProperty(exports, 'GraphQLInterfaceType', {
enumerable: true,
get: function get() {
return _type.GraphQLInterfaceType;
}
});
Object.defineProperty(exports, 'GraphQLUnionType', {
enumerable: true,
get: function get() {
return _type.GraphQLUnionType;
}
});
Object.defineProperty(exports, 'GraphQLEnumType', {
enumerable: true,
get: function get() {
return _type.GraphQLEnumType;
}
});
Object.defineProperty(exports, 'GraphQLInputObjectType', {
enumerable: true,
get: function get() {
return _type.GraphQLInputObjectType;
}
});
Object.defineProperty(exports, 'GraphQLList', {
enumerable: true,
get: function get() {
return _type.GraphQLList;
}
});
Object.defineProperty(exports, 'GraphQLNonNull', {
enumerable: true,
get: function get() {
return _type.GraphQLNonNull;
}
});
Object.defineProperty(exports, 'GraphQLDirective', {
enumerable: true,
get: function get() {
return _type.GraphQLDirective;
}
});
Object.defineProperty(exports, 'TypeKind', {
enumerable: true,
get: function get() {
return _type.TypeKind;
}
});
Object.defineProperty(exports, 'DirectiveLocation', {
enumerable: true,
get: function get() {
return _type.DirectiveLocation;
}
});
Object.defineProperty(exports, 'GraphQLInt', {
enumerable: true,
get: function get() {
return _type.GraphQLInt;
}
});
Object.defineProperty(exports, 'GraphQLFloat', {
enumerable: true,
get: function get() {
return _type.GraphQLFloat;
}
});
Object.defineProperty(exports, 'GraphQLString', {
enumerable: true,
get: function get() {
return _type.GraphQLString;
}
});
Object.defineProperty(exports, 'GraphQLBoolean', {
enumerable: true,
get: function get() {
return _type.GraphQLBoolean;
}
});
Object.defineProperty(exports, 'GraphQLID', {
enumerable: true,
get: function get() {
return _type.GraphQLID;
}
});
Object.defineProperty(exports, 'specifiedDirectives', {
enumerable: true,
get: function get() {
return _type.specifiedDirectives;
}
});
Object.defineProperty(exports, 'GraphQLIncludeDirective', {
enumerable: true,
get: function get() {
return _type.GraphQLIncludeDirective;
}
});
Object.defineProperty(exports, 'GraphQLSkipDirective', {
enumerable: true,
get: function get() {
return _type.GraphQLSkipDirective;
}
});
Object.defineProperty(exports, 'GraphQLDeprecatedDirective', {
enumerable: true,
get: function get() {
return _type.GraphQLDeprecatedDirective;
}
});
Object.defineProperty(exports, 'DEFAULT_DEPRECATION_REASON', {
enumerable: true,
get: function get() {
return _type.DEFAULT_DEPRECATION_REASON;
}
});
Object.defineProperty(exports, 'SchemaMetaFieldDef', {
enumerable: true,
get: function get() {
return _type.SchemaMetaFieldDef;
}
});
Object.defineProperty(exports, 'TypeMetaFieldDef', {
enumerable: true,
get: function get() {
return _type.TypeMetaFieldDef;
}
});
Object.defineProperty(exports, 'TypeNameMetaFieldDef', {
enumerable: true,
get: function get() {
return _type.TypeNameMetaFieldDef;
}
});
Object.defineProperty(exports, '__Schema', {
enumerable: true,
get: function get() {
return _type.__Schema;
}
});
Object.defineProperty(exports, '__Directive', {
enumerable: true,
get: function get() {
return _type.__Directive;
}
});
Object.defineProperty(exports, '__DirectiveLocation', {
enumerable: true,
get: function get() {
return _type.__DirectiveLocation;
}
});
Object.defineProperty(exports, '__Type', {
enumerable: true,
get: function get() {
return _type.__Type;
}
});
Object.defineProperty(exports, '__Field', {
enumerable: true,
get: function get() {
return _type.__Field;
}
});
Object.defineProperty(exports, '__InputValue', {
enumerable: true,
get: function get() {
return _type.__InputValue;
}
});
Object.defineProperty(exports, '__EnumValue', {
enumerable: true,
get: function get() {
return _type.__EnumValue;
}
});
Object.defineProperty(exports, '__TypeKind', {
enumerable: true,
get: function get() {
return _type.__TypeKind;
}
});
Object.defineProperty(exports, 'isType', {
enumerable: true,
get: function get() {
return _type.isType;
}
});
Object.defineProperty(exports, 'isInputType', {
enumerable: true,
get: function get() {
return _type.isInputType;
}
});
Object.defineProperty(exports, 'isOutputType', {
enumerable: true,
get: function get() {
return _type.isOutputType;
}
});
Object.defineProperty(exports, 'isLeafType', {
enumerable: true,
get: function get() {
return _type.isLeafType;
}
});
Object.defineProperty(exports, 'isCompositeType', {
enumerable: true,
get: function get() {
return _type.isCompositeType;
}
});
Object.defineProperty(exports, 'isAbstractType', {
enumerable: true,
get: function get() {
return _type.isAbstractType;
}
});
Object.defineProperty(exports, 'isNamedType', {
enumerable: true,
get: function get() {
return _type.isNamedType;
}
});
Object.defineProperty(exports, 'assertType', {
enumerable: true,
get: function get() {
return _type.assertType;
}
});
Object.defineProperty(exports, 'assertInputType', {
enumerable: true,
get: function get() {
return _type.assertInputType;
}
});
Object.defineProperty(exports, 'assertOutputType', {
enumerable: true,
get: function get() {
return _type.assertOutputType;
}
});
Object.defineProperty(exports, 'assertLeafType', {
enumerable: true,
get: function get() {
return _type.assertLeafType;
}
});
Object.defineProperty(exports, 'assertCompositeType', {
enumerable: true,
get: function get() {
return _type.assertCompositeType;
}
});
Object.defineProperty(exports, 'assertAbstractType', {
enumerable: true,
get: function get() {
return _type.assertAbstractType;
}
});
Object.defineProperty(exports, 'assertNamedType', {
enumerable: true,
get: function get() {
return _type.assertNamedType;
}
});
Object.defineProperty(exports, 'getNullableType', {
enumerable: true,
get: function get() {
return _type.getNullableType;
}
});
Object.defineProperty(exports, 'getNamedType', {
enumerable: true,
get: function get() {
return _type.getNamedType;
}
});
var _language = require('./language');
Object.defineProperty(exports, 'Source', {
enumerable: true,
get: function get() {
return _language.Source;
}
});
Object.defineProperty(exports, 'getLocation', {
enumerable: true,
get: function get() {
return _language.getLocation;
}
});
Object.defineProperty(exports, 'parse', {
enumerable: true,
get: function get() {
return _language.parse;
}
});
Object.defineProperty(exports, 'parseValue', {
enumerable: true,
get: function get() {
return _language.parseValue;
}
});
Object.defineProperty(exports, 'parseType', {
enumerable: true,
get: function get() {
return _language.parseType;
}
});
Object.defineProperty(exports, 'print', {
enumerable: true,
get: function get() {
return _language.print;
}
});
Object.defineProperty(exports, 'visit', {
enumerable: true,
get: function get() {
return _language.visit;
}
});
Object.defineProperty(exports, 'visitInParallel', {
enumerable: true,
get: function get() {
return _language.visitInParallel;
}
});
Object.defineProperty(exports, 'visitWithTypeInfo', {
enumerable: true,
get: function get() {
return _language.visitWithTypeInfo;
}
});
Object.defineProperty(exports, 'Kind', {
enumerable: true,
get: function get() {
return _language.Kind;
}
});
Object.defineProperty(exports, 'TokenKind', {
enumerable: true,
get: function get() {
return _language.TokenKind;
}
});
Object.defineProperty(exports, 'BREAK', {
enumerable: true,
get: function get() {
return _language.BREAK;
}
});
var _execution = require('./execution');
Object.defineProperty(exports, 'execute', {
enumerable: true,
get: function get() {
return _execution.execute;
}
});
Object.defineProperty(exports, 'defaultFieldResolver', {
enumerable: true,
get: function get() {
return _execution.defaultFieldResolver;
}
});
Object.defineProperty(exports, 'responsePathAsArray', {
enumerable: true,
get: function get() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment