CodeMirrorEditor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import AbstractEditor from './AbstractEditor';
  4. import urljoin from 'url-join';
  5. const loadScript = require('simple-load-script');
  6. const loadCssSync = require('load-css-file');
  7. import * as codemirror from 'codemirror';
  8. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  9. require('codemirror/addon/display/autorefresh');
  10. require('codemirror/addon/edit/matchbrackets');
  11. require('codemirror/addon/edit/matchtags');
  12. require('codemirror/addon/edit/closetag');
  13. require('codemirror/addon/edit/continuelist');
  14. require('codemirror/addon/hint/show-hint');
  15. require('codemirror/addon/hint/show-hint.css');
  16. require('codemirror/addon/search/searchcursor');
  17. require('codemirror/addon/search/match-highlighter');
  18. require('codemirror/addon/selection/active-line');
  19. require('codemirror/addon/scroll/annotatescrollbar');
  20. require('codemirror/addon/fold/foldcode');
  21. require('codemirror/addon/fold/foldgutter');
  22. require('codemirror/addon/fold/foldgutter.css');
  23. require('codemirror/addon/fold/markdown-fold');
  24. require('codemirror/addon/fold/brace-fold');
  25. require('codemirror/mode/gfm/gfm');
  26. import pasteHelper from './PasteHelper';
  27. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  28. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  29. import MarkdownListInterceptor from './MarkdownListInterceptor';
  30. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  31. export default class CodeMirrorEditor extends AbstractEditor {
  32. constructor(props) {
  33. super(props);
  34. this.state = {
  35. value: this.props.value,
  36. dropzoneActive: false,
  37. isEnabledEmojiAutoComplete: false,
  38. isUploading: false,
  39. isLoadingKeymap: false,
  40. };
  41. this.init();
  42. this.getCodeMirror = this.getCodeMirror.bind(this);
  43. this.setCaretLine = this.setCaretLine.bind(this);
  44. this.setScrollTopByLine = this.setScrollTopByLine.bind(this);
  45. this.loadTheme = this.loadTheme.bind(this);
  46. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  47. this.setKeymapMode = this.setKeymapMode.bind(this);
  48. this.forceToFocus = this.forceToFocus.bind(this);
  49. this.dispatchSave = this.dispatchSave.bind(this);
  50. this.handleEnterKey = this.handleEnterKey.bind(this);
  51. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  52. this.pasteHandler = this.pasteHandler.bind(this);
  53. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  54. }
  55. init() {
  56. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  57. this.interceptorManager = new InterceptorManager();
  58. this.interceptorManager.addInterceptors([
  59. new MarkdownListInterceptor(),
  60. new MarkdownTableInterceptor(),
  61. ]);
  62. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  63. this.loadedKeymapSet = new Set();
  64. }
  65. componentWillMount() {
  66. if (this.props.emojiStrategy != null) {
  67. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  68. this.setState({isEnabledEmojiAutoComplete: true});
  69. }
  70. }
  71. componentDidMount() {
  72. // initialize caret line
  73. this.setCaretLine(0);
  74. // set save handler
  75. codemirror.commands.save = this.dispatchSave;
  76. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  77. window.CodeMirror = require('codemirror');
  78. }
  79. componentWillReceiveProps(nextProps) {
  80. // load theme
  81. const theme = nextProps.editorOptions.theme;
  82. this.loadTheme(theme);
  83. // set keymap
  84. const keymapMode = nextProps.editorOptions.keymapMode;
  85. this.setKeymapMode(keymapMode);
  86. }
  87. getCodeMirror() {
  88. return this.refs.cm.editor;
  89. }
  90. /**
  91. * @inheritDoc
  92. */
  93. forceToFocus() {
  94. if (this.props.isMobile) {
  95. return;
  96. }
  97. const editor = this.getCodeMirror();
  98. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  99. const intervalId = setInterval(() => {
  100. this.getCodeMirror().focus();
  101. if (editor.hasFocus()) {
  102. clearInterval(intervalId);
  103. // refresh
  104. editor.refresh();
  105. }
  106. }, 100);
  107. }
  108. /**
  109. * @inheritDoc
  110. */
  111. setCaretLine(line) {
  112. if (isNaN(line)) {
  113. return;
  114. }
  115. const editor = this.getCodeMirror();
  116. const linePosition = Math.max(0, line);
  117. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  118. this.setScrollTopByLine(linePosition);
  119. }
  120. /**
  121. * @inheritDoc
  122. */
  123. setScrollTopByLine(line) {
  124. if (isNaN(line)) {
  125. return;
  126. }
  127. const editor = this.getCodeMirror();
  128. // get top position of the line
  129. var top = editor.charCoords({line, ch: 0}, 'local').top;
  130. editor.scrollTo(null, top);
  131. }
  132. /**
  133. * @inheritDoc
  134. */
  135. insertText(text) {
  136. const editor = this.getCodeMirror();
  137. editor.getDoc().replaceSelection(text);
  138. }
  139. loadCss(source) {
  140. return new Promise((resolve) => {
  141. loadCssSync(source);
  142. resolve();
  143. });
  144. }
  145. /**
  146. * load Theme
  147. * @see https://codemirror.net/doc/manual.html#config
  148. *
  149. * @param {string} theme
  150. */
  151. loadTheme(theme) {
  152. if (!this.loadedThemeSet.has(theme)) {
  153. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  154. // update Set
  155. this.loadedThemeSet.add(theme);
  156. }
  157. }
  158. /**
  159. * load assets for Key Maps
  160. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  161. */
  162. loadKeymapMode(keymapMode) {
  163. const loadCss = this.loadCss;
  164. let scriptList = [];
  165. let cssList = [];
  166. // add dependencies
  167. if (this.loadedKeymapSet.size == 0) {
  168. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  169. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  170. }
  171. // load keymap
  172. if (!this.loadedKeymapSet.has(keymapMode)) {
  173. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  174. // update Set
  175. this.loadedKeymapSet.add(keymapMode);
  176. }
  177. // set loading state
  178. this.setState({ isLoadingKeymap: true });
  179. return Promise.all(scriptList.concat(cssList))
  180. .then(() => {
  181. this.setState({ isLoadingKeymap: false });
  182. });
  183. }
  184. /**
  185. * set Key Maps
  186. * @see https://codemirror.net/doc/manual.html#keymaps
  187. *
  188. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  189. */
  190. setKeymapMode(keymapMode) {
  191. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  192. // reset
  193. this.getCodeMirror().setOption('keyMap', 'default');
  194. return;
  195. }
  196. this.loadKeymapMode(keymapMode)
  197. .then(() => {
  198. this.getCodeMirror().setOption('keyMap', keymapMode);
  199. });
  200. }
  201. /**
  202. * handle ENTER key
  203. */
  204. handleEnterKey() {
  205. if (this.props.isMobile) {
  206. // TODO impl
  207. }
  208. else {
  209. const editor = this.getCodeMirror();
  210. var context = {
  211. handlers: [], // list of handlers which process enter key
  212. editor: editor,
  213. };
  214. const interceptorManager = this.interceptorManager;
  215. interceptorManager.process('preHandleEnter', context)
  216. .then(() => {
  217. if (context.handlers.length == 0) {
  218. codemirror.commands.newlineAndIndentContinueMarkdownList(editor);
  219. }
  220. });
  221. }
  222. }
  223. scrollCursorIntoViewHandler(editor, event) {
  224. if (this.props.onScrollCursorIntoView != null) {
  225. const line = editor.getCursor().line;
  226. this.props.onScrollCursorIntoView(line);
  227. }
  228. }
  229. /**
  230. * CodeMirror paste event handler
  231. * see: https://codemirror.net/doc/manual.html#events
  232. * @param {any} editor An editor instance of CodeMirror
  233. * @param {any} event
  234. */
  235. pasteHandler(editor, event) {
  236. const types = event.clipboardData.types;
  237. // text
  238. if (types.includes('text/plain')) {
  239. pasteHelper.pasteText(editor, event);
  240. }
  241. // files
  242. else if (types.includes('Files')) {
  243. this.dispatchPasteFiles(event);
  244. }
  245. }
  246. dispatchPasteFiles(event) {
  247. if (this.props.onPasteFiles != null) {
  248. this.props.onPasteFiles(event);
  249. }
  250. }
  251. getOverlayStyle() {
  252. return {
  253. position: 'absolute',
  254. zIndex: 4, // forward than .CodeMirror-gutters
  255. top: 0,
  256. right: 0,
  257. bottom: 0,
  258. left: 0,
  259. };
  260. }
  261. renderLoadingKeymapOverlay() {
  262. const overlayStyle = this.getOverlayStyle();
  263. return this.state.isLoadingKeymap
  264. ? <div style={overlayStyle} className="loading-keymap overlay">
  265. <span className="overlay-content">
  266. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  267. </span>
  268. </div>
  269. : '';
  270. }
  271. render() {
  272. const theme = this.props.editorOptions.theme || 'elegant';
  273. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  274. return <React.Fragment>
  275. <ReactCodeMirror
  276. ref="cm"
  277. editorDidMount={(editor) => {
  278. // add event handlers
  279. editor.on('paste', this.pasteHandler);
  280. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  281. }}
  282. value={this.state.value}
  283. options={{
  284. mode: 'gfm',
  285. theme: theme,
  286. styleActiveLine: styleActiveLine,
  287. lineNumbers: true,
  288. tabSize: 4,
  289. indentUnit: 4,
  290. lineWrapping: true,
  291. autoRefresh: true,
  292. autoCloseTags: true,
  293. matchBrackets: true,
  294. matchTags: {bothTags: true},
  295. // folding
  296. foldGutter: true,
  297. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
  298. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  299. highlightSelectionMatches: {annotateScrollbar: true},
  300. // markdown mode options
  301. highlightFormatting: true,
  302. // continuelist, indentlist
  303. extraKeys: {
  304. 'Enter': this.handleEnterKey,
  305. 'Tab': 'indentMore',
  306. 'Shift-Tab': 'indentLess',
  307. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  308. }
  309. }}
  310. onScroll={(editor, data) => {
  311. if (this.props.onScroll != null) {
  312. // add line data
  313. const line = editor.lineAtHeight(data.top, 'local');
  314. data.line = line;
  315. this.props.onScroll(data);
  316. }
  317. }}
  318. onChange={(editor, data, value) => {
  319. if (this.props.onChange != null) {
  320. this.props.onChange(value);
  321. }
  322. // Emoji AutoComplete
  323. if (this.state.isEnabledEmojiAutoComplete) {
  324. this.emojiAutoCompleteHelper.showHint(editor);
  325. }
  326. }}
  327. onDragEnter={(editor, event) => {
  328. if (this.props.onDragEnter != null) {
  329. this.props.onDragEnter(event);
  330. }
  331. }}
  332. />
  333. { this.renderLoadingKeymapOverlay() }
  334. </React.Fragment>;
  335. }
  336. }
  337. CodeMirrorEditor.propTypes = Object.assign({
  338. emojiStrategy: PropTypes.object,
  339. onDragEnter: PropTypes.func,
  340. }, AbstractEditor.propTypes);