import React, {PureComponent, PropTypes} from 'react';
import autobind from 'autobind-decorator';
import CodeMirror from 'codemirror';
import classnames from 'classnames';
import clone from 'clone';
import jq from 'jsonpath';
import vkBeautify from 'vkbeautify';
import {DOMParser} from 'xmldom';
import xpath from 'xpath';
import {showModal} from '../modals/index';
import FilterHelpModal from '../modals/filter-help-modal';
import * as misc from '../../../common/misc';
import {trackEvent} from '../../../analytics/index';
import {prettifyJson} from '../../../common/prettify';
import {DEBOUNCE_MILLIS, isMac} from '../../../common/constants';
import './base-imports';
import {getTagDefinitions} from '../../../templating/index';
import Dropdown from '../base/dropdown/dropdown';
import DropdownButton from '../base/dropdown/dropdown-button';
import DropdownItem from '../base/dropdown/dropdown-item';
const TAB_KEY = 9;
const TAB_SIZE = 4;
const BASE_CODEMIRROR_OPTIONS = {
lineNumbers: true,
placeholder: 'Start Typing...',
foldGutter: true,
height: 'auto',
autoRefresh: 2000,
lineWrapping: true,
scrollbarStyle: 'native',
lint: true,
matchBrackets: true,
autoCloseBrackets: true,
tabSize: TAB_SIZE,
indentUnit: TAB_SIZE,
hintOptions: null,
dragDrop: true,
viewportMargin: 30, // default 10
selectionPointer: 'default',
styleActiveLine: true,
indentWithTabs: true,
showCursorWhenSelecting: false,
cursorScrollMargin: 12, // NOTE: This is px
keyMap: 'default',
extraKeys: {
'Ctrl-Q': function (cm) {
cm.foldCode(cm.getCursor());
},
'Ctrl-Space': 'autocomplete',
// Change default find command from "find" to "findPersistent" so the
// search box stays open after pressing Enter
[isMac() ? 'Cmd-F' : 'Ctrl-F']: 'findPersistent'
}
};
@autobind
class CodeEditor extends PureComponent {
constructor (props) {
super(props);
this.state = {
filter: props.filter || ''
};
this._originalCode = '';
}
componentWillUnmount () {
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}
);
}
}
focus () {
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) {
this.codeMirror.setSelection(
{line, ch: chStart},
{line, ch: chEnd}
);
}
}
getSelectionStart () {
const selections = this.codeMirror.listSelections();
if (selections.length) {
return selections[0].anchor.ch;
} else {
return 0;
}
}
getSelectionEnd () {
const selections = this.codeMirror.listSelections();
if (selections.length) {
return selections[0].head.ch;
} else {
return 0;
}
}
focusEnd () {
if (this.codeMirror) {
if (!this.hasFocus()) {
this.focus();
}
const doc = this.codeMirror.getDoc();
doc.setCursor(doc.lineCount(), 0);
}
}
hasFocus () {
if (this.codeMirror) {
return this.codeMirror.hasFocus();
} else {
return false;
}
}
setAttribute (name, value) {
this.codeMirror.getTextArea().parentNode.setAttribute(name, value);
}
removeAttribute (name) {
this.codeMirror.getTextArea().parentNode.removeAttribute(name);
}
getAttribute (name) {
this.codeMirror.getTextArea().parentNode.getAttribute(name);
}
clearSelection () {
// Never do this if dropdown is open
if (this.codeMirror.isHintDropdownActive()) {
return;
}
if (this.codeMirror) {
this.codeMirror.setSelection(
{line: -1, ch: -1},
{line: -1, ch: -1}
);
}
}
getValue () {
if (this.codeMirror) {
return this.codeMirror.getValue();
} else {
return '';
}
}
_setFilterInputRef (n) {
this._filterInput = n;
}
_handleInitTextarea (textarea) {
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);
// 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('keyup', this._codemirrorTriggerCompletionKeyUp);
this.codeMirror.on('endCompletion', this._codemirrorEndCompletion);
this.codeMirror.on('focus', this._codemirrorFocus);
this.codeMirror.on('blur', this._codemirrorBlur);
this.codeMirror.on('paste', this._codemirrorPaste);
// Prevent these things if we're type === "password"
this.codeMirror.on('copy', this._codemirrorPreventWhenTypePassword);
this.codeMirror.on('cut', this._codemirrorPreventWhenTypePassword);
this.codeMirror.on('dragstart', this._codemirrorPreventWhenTypePassword);
this.codeMirror.setCursor({line: -1, ch: -1});
if (!this.codeMirror.getOption('indentWithTabs')) {
this.codeMirror.setOption('extraKeys', {
Tab: cm => {
const spaces = (new Array(this.codeMirror.getOption('indentUnit') + 1)).join(' ');
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);
}
// HACK: Refresh because sometimes it renders too early and the scroll doesn't
// quite fit.
setTimeout(() => {
this.codeMirror.refresh();
}, 100);
};
// 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();
}
}
_isJSON (mode) {
if (!mode) {
return false;
}
return mode.indexOf('json') !== -1;
}
_isXML (mode) {
if (!mode) {
return false;
}
return mode.indexOf('xml') !== -1;
}
_handleBeautify () {
trackEvent('Request', 'Beautify');
this._prettify(this.codeMirror.getValue());
}
_prettify (code) {
this._codemirrorSetValue(code, true);
}
_prettifyJSON (code) {
try {
let jsonString = code;
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 = '[]';
}
}
return prettifyJson(jsonString, '\t');
} catch (e) {
// That's Ok, just leave it
return code;
}
}
_prettifyXML (code) {
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 = `