insomnia/app/ui/components/codemirror/editor.js

685 lines
18 KiB
JavaScript
Raw Normal View History

import React, {PureComponent, PropTypes} from 'react';
import autobind from 'autobind-decorator';
2016-03-16 20:02:47 +00:00
import CodeMirror from 'codemirror';
2016-07-19 22:28:29 +00:00
import classnames from 'classnames';
import jq from 'jsonpath';
2016-09-15 03:46:23 +00:00
import vkBeautify from 'vkbeautify';
2016-09-13 21:18:22 +00:00
import {DOMParser} from 'xmldom';
import xpath from 'xpath';
2016-08-31 05:37:21 +00:00
import 'codemirror/mode/css/css';
import 'codemirror/mode/htmlmixed/htmlmixed';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/go/go';
import 'codemirror/mode/shell/shell';
import 'codemirror/mode/clike/clike';
import 'codemirror/mode/mllike/mllike';
import 'codemirror/mode/php/php';
2016-11-10 07:34:26 +00:00
import 'codemirror/mode/markdown/markdown';
2016-08-31 05:37:21 +00:00
import 'codemirror/mode/python/python';
import 'codemirror/mode/ruby/ruby';
import 'codemirror/mode/swift/swift';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/display/autorefresh';
2016-08-31 05:37:21 +00:00
import 'codemirror/addon/dialog/dialog';
import 'codemirror/addon/dialog/dialog.css';
import 'codemirror/addon/fold/foldcode';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/foldgutter.css';
2016-08-31 05:37:21 +00:00
import 'codemirror/addon/fold/brace-fold';
import 'codemirror/addon/fold/comment-fold';
import 'codemirror/addon/fold/indent-fold';
import 'codemirror/addon/fold/xml-fold';
import 'codemirror/addon/search/search';
import 'codemirror/addon/search/searchcursor';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';
2016-08-31 05:37:21 +00:00
import 'codemirror/addon/search/matchesonscrollbar';
import 'codemirror/addon/search/matchesonscrollbar.css';
import 'codemirror/addon/selection/active-line';
import 'codemirror/addon/selection/selection-pointer';
2016-08-31 05:37:21 +00:00
import 'codemirror/addon/display/placeholder';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/json-lint';
import 'codemirror/addon/lint/lint.css';
2017-01-24 22:18:11 +00:00
import 'codemirror/keymap/vim';
import 'codemirror/keymap/emacs';
import 'codemirror/keymap/sublime';
import './modes/nunjucks';
import './extensions/clickable';
import './extensions/nunjucks-tags';
2016-08-31 05:37:21 +00:00
import '../../css/components/editor.less';
import {showModal} from '../modals/index';
import AlertModal from '../modals/alert-modal';
import Link from '../base/link';
2016-11-10 21:03:12 +00:00
import * as misc from '../../../common/misc';
import {trackEvent} from '../../../analytics/index';
// Make jsonlint available to the jsonlint plugin
import {parser as jsonlint} from 'jsonlint';
import {prettifyJson} from '../../../common/prettify';
import {DEBOUNCE_MILLIS} from '../../../common/constants';
global.jsonlint = jsonlint;
const TAB_KEY = 9;
2016-03-16 20:02:47 +00:00
2016-03-20 20:42:27 +00:00
const BASE_CODEMIRROR_OPTIONS = {
lineNumbers: true,
2016-03-23 18:34:39 +00:00
placeholder: 'Start Typing...',
2016-03-20 20:42:27 +00:00
foldGutter: true,
2016-03-23 05:58:16 +00:00
height: 'auto',
autoRefresh: 1000,
2016-06-20 06:31:32 +00:00
lineWrapping: true,
scrollbarStyle: 'native',
2016-06-18 22:57:23 +00:00
lint: true,
2016-04-15 02:13:49 +00:00
tabSize: 4,
2016-07-29 20:37:23 +00:00
matchBrackets: true,
autoCloseBrackets: true,
2016-06-18 22:57:23 +00:00
indentUnit: 4,
dragDrop: true,
viewportMargin: 30, // default 10
selectionPointer: 'default',
styleActiveLine: true,
2016-07-14 22:48:56 +00:00
indentWithTabs: true,
showCursorWhenSelecting: false,
cursorScrollMargin: 12, // NOTE: This is px
2017-01-24 22:18:11 +00:00
keyMap: 'default',
2016-03-20 20:42:27 +00:00
extraKeys: {
2016-09-13 02:09:35 +00:00
'Ctrl-Q': function (cm) {
2016-03-20 20:42:27 +00:00
cm.foldCode(cm.getCursor());
}
2016-03-21 05:47:49 +00:00
}
2016-03-20 20:42:27 +00:00
};
@autobind
class Editor extends PureComponent {
2016-09-09 00:32:36 +00:00
constructor (props) {
super(props);
2016-09-08 22:04:25 +00:00
this.state = {
2016-09-09 00:32:36 +00:00
filter: props.filter || ''
2016-09-08 22:04:25 +00:00
};
2016-09-08 22:04:25 +00:00
this._originalCode = '';
2016-03-16 20:02:47 +00:00
}
2016-07-14 22:48:56 +00:00
componentWillUnmount () {
2016-03-16 20:02:47 +00:00
if (this.codeMirror) {
this.codeMirror.toTextArea();
}
}
componentDidUpdate () {
this._codemirrorSetOptions();
}
shouldComponentUpdate (nextProps) {
// Update if any properties changed, except value. We ignore value.
for (const key of Object.keys(nextProps)) {
if (key === 'defaultValue') {
continue;
}
if (this.props[key] !== nextProps[key]) {
return true;
}
}
return false;
}
selectAll () {
if (this.codeMirror) {
this.codeMirror.setSelection(
{line: 0, ch: 0},
{line: this.codeMirror.lineCount(), ch: 0}
);
}
}
2016-07-14 22:48:56 +00:00
focus () {
2016-03-16 20:02:47 +00:00
if (this.codeMirror) {
this.codeMirror.focus();
}
}
setCursor (ch, line = 0) {
if (this.codeMirror) {
if (!this.hasFocus()) {
this.focus();
}
this.codeMirror.setCursor({line, ch});
}
}
setSelection (chStart, chEnd, line = 0) {
if (this.codeMirror) {
if (!this.hasFocus()) {
this.focus();
}
this.codeMirror.setSelection(
{line, ch: chStart},
{line, ch: chEnd}
);
}
}
focusEnd () {
if (this.codeMirror) {
if (!this.hasFocus()) {
this.focus();
}
const doc = this.codeMirror.getDoc();
doc.setCursor(doc.lineCount(), 0);
}
}
2017-03-01 03:09:04 +00:00
hasFocus () {
if (this.codeMirror) {
return this.codeMirror.hasFocus();
} else {
return false;
}
}
clearSelection () {
if (this.codeMirror) {
this.codeMirror.setSelection(
{line: -1, ch: -1},
{line: -1, ch: -1}
);
}
}
getValue () {
if (this.codeMirror) {
return this.codeMirror.getValue();
} else {
return '';
}
}
_handleInitTextarea (textarea) {
2016-08-31 05:37:21 +00:00
if (!textarea) {
// Not mounted
return;
}
if (this.codeMirror) {
// Already initialized
return;
}
const {defaultValue, debounceMillis: ms} = this.props;
this.codeMirror = CodeMirror.fromTextArea(textarea, BASE_CODEMIRROR_OPTIONS);
2016-08-31 05:37:21 +00:00
// Set default listeners
const debounceMillis = typeof ms === 'number' ? ms : DEBOUNCE_MILLIS;
this.codeMirror.on('changes', misc.debounce(this._codemirrorValueChanged, debounceMillis));
this.codeMirror.on('beforeChange', this._codemirrorValueBeforeChange);
this.codeMirror.on('keydown', this._codemirrorKeyDown);
this.codeMirror.on('focus', this._codemirrorFocus);
this.codeMirror.on('blur', this._codemirrorBlur);
this.codeMirror.on('paste', this._codemirrorValueChanged);
// this.codeMirror.setCursor({line: -1, ch: -1});
2016-08-31 05:37:21 +00:00
if (!this.codeMirror.getOption('indentWithTabs')) {
this.codeMirror.setOption('extraKeys', {
Tab: cm => {
const spaces = Array(this.codeMirror.getOption('indentUnit') + 1).join(' ');
2016-08-31 05:37:21 +00:00
cm.replaceSelection(spaces);
}
});
}
// Set editor options
this._codemirrorSetOptions();
const setup = () => {
// Actually set the value
this._codemirrorSetValue(defaultValue || '');
// Setup nunjucks listeners
if (this.props.render) {
this.codeMirror.enableNunjucksTags(this.props.render);
}
// Make URLs clickable
if (this.props.onClickLink) {
this.codeMirror.makeLinksClickable(this.props.onClickLink);
}
};
// Do this a bit later for big values so we don't block the render process
if (defaultValue && defaultValue.length > 10000) {
setTimeout(setup, 100);
} else {
setup();
}
}
2016-09-08 22:04:25 +00:00
_isJSON (mode) {
if (!mode) {
return false;
}
return mode.indexOf('json') !== -1;
2016-09-08 22:04:25 +00:00
}
2016-09-10 01:51:49 +00:00
_isXML (mode) {
if (!mode) {
return false;
}
return mode.indexOf('xml') !== -1;
2016-09-10 01:51:49 +00:00
}
_handleBeautify () {
trackEvent('Request', 'Beautify');
2016-09-13 17:35:49 +00:00
this._prettify(this.codeMirror.getValue());
}
2016-09-13 17:35:49 +00:00
_prettify (code) {
this._codemirrorSetValue(code, true);
2016-09-13 17:29:09 +00:00
}
_prettifyJSON (code) {
2016-09-10 01:51:49 +00:00
try {
let jsonString = code;
2016-09-10 01:51:49 +00:00
if (this.props.updateFilter && this.state.filter) {
let obj = JSON.parse(code);
try {
jsonString = JSON.stringify(jq.query(obj, this.state.filter));
} catch (err) {
jsonString = '[]';
}
2016-09-10 01:51:49 +00:00
}
return prettifyJson(jsonString, '\t');
2016-09-10 01:51:49 +00:00
} catch (e) {
// That's Ok, just leave it
return code;
2016-09-10 01:51:49 +00:00
}
}
_prettifyXML (code) {
2016-09-13 21:18:22 +00:00
if (this.props.updateFilter && this.state.filter) {
try {
const dom = new DOMParser().parseFromString(code);
const nodes = xpath.select(this.state.filter, dom);
const inner = nodes.map(n => n.toString()).join('\n');
code = `<result>${inner}</result>`;
2016-09-13 21:18:22 +00:00
} catch (e) {
// Failed to parse filter (that's ok)
code = `<result></result>`;
2016-09-13 21:18:22 +00:00
}
}
2016-09-10 01:51:49 +00:00
2016-09-28 21:17:57 +00:00
try {
return vkBeautify.xml(code, '\t');
2016-09-28 21:17:57 +00:00
} catch (e) {
// Failed to parse so just return original
return code;
2016-09-28 21:17:57 +00:00
}
2016-09-10 01:51:49 +00:00
}
2016-03-20 20:42:27 +00:00
/**
2016-03-22 05:01:58 +00:00
* Sets options on the CodeMirror editor while also sanitizing them
2016-03-20 20:42:27 +00:00
*/
_codemirrorSetOptions () {
const {
mode: rawMode,
readOnly,
hideLineNumbers,
keyMap,
lineWrapping,
tabIndex,
placeholder,
noMatchBrackets,
noDragDrop,
hideScrollbars,
noStyleActiveLine,
noLint
} = this.props;
let mode;
if (this.props.render) {
mode = {name: 'nunjucks', baseMode: this._normalizeMode(rawMode)};
} else {
// foo bar baz
mode = this._normalizeMode(rawMode);
}
2016-04-29 01:00:12 +00:00
let options = {
readOnly: !!readOnly,
placeholder: placeholder || '',
mode: mode,
tabIndex: typeof tabIndex === 'number' ? tabIndex : null,
dragDrop: !noDragDrop,
scrollbarStyle: hideScrollbars ? 'null' : 'native',
styleActiveLine: !noStyleActiveLine,
lineNumbers: !hideLineNumbers,
foldGutter: !hideLineNumbers,
lineWrapping: lineWrapping,
keyMap: keyMap || 'default',
matchBrackets: !noMatchBrackets,
lint: !noLint && !readOnly,
gutters: []
2016-04-29 01:00:12 +00:00
};
2016-04-11 00:40:14 +00:00
if (options.lineNumbers) {
options.gutters.push('CodeMirror-linenumbers');
}
if (options.foldGutter) {
options.gutters.push('CodeMirror-foldgutter');
}
if (options.lint) {
options.gutters.push('CodeMirror-lint-markers');
}
const cm = this.codeMirror;
2016-04-11 00:40:14 +00:00
// Strip of charset if there is one
2016-03-20 04:00:40 +00:00
Object.keys(options).map(key => {
2017-02-08 01:52:05 +00:00
// Don't set the option if it hasn't changed
if (options[key] === cm.options[key]) {
2017-02-08 01:52:05 +00:00
return;
}
cm.setOption(key, options[key]);
2016-03-20 04:00:40 +00:00
});
}
2016-03-20 04:00:40 +00:00
_normalizeMode (mode) {
const mimeType = mode ? mode.split(';')[0] : 'text/plain';
if (this._isJSON(mimeType)) {
return 'application/json';
} else if (this._isXML(mimeType)) {
return 'application/xml';
} else {
return mimeType;
}
}
_codemirrorKeyDown (doc, e) {
// Use default tab behaviour if we're told
if (this.props.defaultTabBehavior && e.keyCode === TAB_KEY) {
e.codemirrorIgnore = true;
}
if (this.props.onKeyDown) {
this.props.onKeyDown(e, doc.getValue());
}
}
_codemirrorFocus (doc, e) {
if (this.props.onFocus) {
this.props.onFocus(e);
}
}
_codemirrorBlur (doc, e) {
if (this.props.onBlur) {
this.props.onBlur(e);
}
}
_codemirrorValueBeforeChange (doc, change) {
// If we're in single-line mode, merge all changed lines into one
if (this.props.singleLine && change.text.length > 1) {
const text = change.text
.join('') // join all changed lines into one
.replace(/\n/g, ' '); // Convert all whitespace to spaces
const from = {ch: change.from.ch, line: 0};
const to = {ch: from.ch + text.length, line: 0};
change.update(from, to, [text]);
}
}
2016-03-20 20:42:27 +00:00
/**
* Wrapper function to add extra behaviour to our onChange event
*/
_codemirrorValueChanged () {
2016-07-29 00:24:05 +00:00
// Don't trigger change event if we're ignoring changes
if (this._ignoreNextChange || !this.props.onChange) {
this._ignoreNextChange = false;
return;
}
const value = this.codeMirror.getDoc().getValue();
this.props.onChange(value);
}
2016-03-20 20:42:27 +00:00
/**
2016-03-22 05:01:58 +00:00
* Sets the CodeMirror value without triggering the onChange event
2016-03-20 20:42:27 +00:00
* @param code the code to set in the editor
* @param forcePrettify
2016-03-20 20:42:27 +00:00
*/
_codemirrorSetValue (code, forcePrettify = false) {
2016-09-08 22:04:25 +00:00
this._originalCode = code;
2016-04-17 22:46:17 +00:00
// Don't ignore changes from prettify
if (!forcePrettify) {
this._ignoreNextChange = true;
}
const shouldPrettify = forcePrettify || this.props.autoPrettify;
if (shouldPrettify && this._canPrettify()) {
if (this._isXML(this.props.mode)) {
code = this._prettifyXML(code);
} else {
code = this._prettifyJSON(code);
}
2016-04-10 02:58:48 +00:00
}
this.codeMirror.setValue(code || '');
2016-03-16 20:02:47 +00:00
}
_handleFilterChange (e) {
const filter = e.target.value;
2016-09-08 22:04:25 +00:00
clearTimeout(this._filterTimeout);
this._filterTimeout = setTimeout(() => {
this.setState({filter});
this._codemirrorSetValue(this._originalCode);
2016-09-09 00:32:36 +00:00
if (this.props.updateFilter) {
this.props.updateFilter(filter);
}
}, 200);
2016-11-23 23:29:31 +00:00
// So we don't track on every keystroke, give analytics a longer timeout
clearTimeout(this._analyticsTimeout);
const json = this._isJSON(this.props.mode);
this._analyticsTimeout = setTimeout(() => {
trackEvent(
'Response',
`Filter ${json ? 'JSONPath' : 'XPath'}`,
`${filter ? 'Change' : 'Clear'}`
);
}, 2000);
}
2016-09-08 22:04:25 +00:00
2016-09-13 17:29:09 +00:00
_canPrettify () {
const {mode} = this.props;
return this._isJSON(mode) || this._isXML(mode);
}
2016-09-08 22:33:03 +00:00
_showFilterHelp () {
2016-09-10 01:51:49 +00:00
const json = this._isJSON(this.props.mode);
const link = json ? (
<Link href="http://goessner.net/articles/JsonPath/">
JSONPath
</Link>
) : (
<Link href="https://www.w3.org/TR/xpath/">
XPath
</Link>
);
2016-09-10 01:51:49 +00:00
2016-11-23 23:29:31 +00:00
trackEvent('Response', `Filter ${json ? 'JSONPath' : 'XPath'}`, 'Help');
showModal(AlertModal, {
title: 'Response Filtering Help',
2016-09-08 22:33:03 +00:00
message: (
<div>
<p>
2016-09-10 01:51:49 +00:00
Use {link} to filter the response body. Here are some examples that
you might use on a book store API.
2016-09-08 22:33:03 +00:00
</p>
<table className="pad-top-sm">
<tbody>
<tr>
2016-11-23 23:42:10 +00:00
<td>
<code className="selectable">
{json ? '$.store.books[*].title' : '/store/books/title'}
</code>
2016-09-09 00:32:36 +00:00
</td>
2016-09-08 22:33:03 +00:00
<td>Get titles of all books in the store</td>
</tr>
<tr>
2016-11-23 23:42:10 +00:00
<td>
<code className="selectable">
{json ? '$.store.books[?(@.price < 10)].title' : '/store/books[price < 10]'}
</code>
</td>
<td>Get books costing less than $10</td>
2016-09-08 22:33:03 +00:00
</tr>
<tr>
2016-11-23 23:42:10 +00:00
<td>
<code className="selectable">
{json ? '$.store.books[-1:]' : '/store/books[last()]'}
</code>
</td>
2016-09-08 22:33:03 +00:00
<td>Get the last book in the store</td>
</tr>
<tr>
2016-11-23 23:42:10 +00:00
<td>
<code className="selectable">
{json ? '$.store.books.length' : 'count(/store/books)'}
</code>
</td>
2016-09-08 22:33:03 +00:00
<td>Get the number of books in the store</td>
</tr>
</tbody>
</table>
</div>
)
});
2016-09-08 22:33:03 +00:00
}
2016-07-14 22:48:56 +00:00
render () {
const {readOnly, fontSize, mode, filter, onMouseLeave} = this.props;
2016-07-19 22:28:29 +00:00
const classes = classnames(
2016-04-17 22:46:17 +00:00
'editor',
2016-03-24 05:26:04 +00:00
this.props.className,
2017-02-13 08:12:02 +00:00
{'editor--readonly': readOnly}
2016-07-19 22:28:29 +00:00
);
2016-04-29 05:58:37 +00:00
2016-09-13 17:29:09 +00:00
const toolbarChildren = [];
2016-09-10 01:51:49 +00:00
if (this.props.updateFilter && (this._isJSON(mode) || this._isXML(mode))) {
2016-09-13 17:29:09 +00:00
toolbarChildren.push(
<input
key="filter"
type="text"
title="Filter response body"
defaultValue={filter || ''}
placeholder={this._isJSON(mode) ? '$.store.books[*].author' : '/store/books/author'}
onChange={this._handleFilterChange}
2016-09-13 17:29:09 +00:00
/>
);
toolbarChildren.push(
<button key="help"
className="btn btn--compact"
onClick={() => this._showFilterHelp()}>
<i className="fa fa-question-circle"></i>
</button>
);
2016-09-08 22:04:25 +00:00
}
2016-09-13 17:29:09 +00:00
if (this.props.manualPrettify && this._canPrettify()) {
let contentTypeName = '';
if (this._isJSON(mode)) {
contentTypeName = 'JSON';
2016-09-13 17:29:09 +00:00
} else if (this._isXML(mode)) {
contentTypeName = 'XML';
2016-09-13 17:29:09 +00:00
}
toolbarChildren.push(
<button key="prettify"
className="btn btn--compact"
title="Auto-format request body whitespace"
onClick={this._handleBeautify}>
2016-09-13 17:29:09 +00:00
Beautify {contentTypeName}
</button>
);
2016-09-13 17:29:09 +00:00
}
let toolbar = null;
if (toolbarChildren.length) {
toolbar = <div className="editor__toolbar">{toolbarChildren}</div>;
}
const styles = {};
if (fontSize) {
styles.fontSize = `${fontSize}px`;
}
2016-03-16 20:02:47 +00:00
return (
<div className={classes}>
<div className="editor__container input" style={styles} onMouseLeave={onMouseLeave}>
<textarea
ref={this._handleInitTextarea}
style={{display: 'none'}}
defaultValue=" "
readOnly={readOnly}
autoComplete="off"
/>
2016-09-20 21:17:01 +00:00
</div>
2016-09-13 17:29:09 +00:00
{toolbar}
2016-03-20 04:00:40 +00:00
</div>
2016-03-16 20:02:47 +00:00
);
}
}
Editor.propTypes = {
onChange: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onClickLink: PropTypes.func,
onKeyDown: PropTypes.func,
onMouseLeave: PropTypes.func,
2017-02-13 08:12:02 +00:00
render: PropTypes.func,
2017-01-24 22:18:11 +00:00
keyMap: PropTypes.string,
2016-04-29 01:00:12 +00:00
mode: PropTypes.string,
placeholder: PropTypes.string,
2016-07-19 22:28:29 +00:00
lineWrapping: PropTypes.bool,
hideLineNumbers: PropTypes.bool,
noMatchBrackets: PropTypes.bool,
hideScrollbars: PropTypes.bool,
2016-07-19 22:28:29 +00:00
fontSize: PropTypes.number,
defaultValue: PropTypes.string,
tabIndex: PropTypes.number,
2016-09-13 17:29:09 +00:00
autoPrettify: PropTypes.bool,
manualPrettify: PropTypes.bool,
noLint: PropTypes.bool,
noDragDrop: PropTypes.bool,
noStyleActiveLine: PropTypes.bool,
className: PropTypes.any,
2016-09-09 00:32:36 +00:00
updateFilter: PropTypes.func,
defaultTabBehavior: PropTypes.bool,
2017-02-13 08:12:02 +00:00
readOnly: PropTypes.bool,
filter: PropTypes.string,
singleLine: PropTypes.bool,
debounceMillis: PropTypes.number
2016-03-16 20:02:47 +00:00
};
export default Editor;