CodeMirrorEditor.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import Modal from 'react-bootstrap/es/Modal';
  4. import AbstractEditor from './AbstractEditor';
  5. import urljoin from 'url-join';
  6. const loadScript = require('simple-load-script');
  7. const loadCssSync = require('load-css-file');
  8. import * as codemirror from 'codemirror';
  9. // set save handler
  10. codemirror.commands.save = (instance) => {
  11. if (instance.codeMirrorEditor != null) {
  12. instance.codeMirrorEditor.dispatchSave();
  13. }
  14. };
  15. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  16. window.CodeMirror = require('codemirror');
  17. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  18. require('codemirror/addon/display/placeholder');
  19. require('codemirror/addon/edit/matchbrackets');
  20. require('codemirror/addon/edit/matchtags');
  21. require('codemirror/addon/edit/closetag');
  22. require('codemirror/addon/edit/continuelist');
  23. require('codemirror/addon/hint/show-hint');
  24. require('codemirror/addon/hint/show-hint.css');
  25. require('codemirror/addon/search/searchcursor');
  26. require('codemirror/addon/search/match-highlighter');
  27. require('codemirror/addon/selection/active-line');
  28. require('codemirror/addon/scroll/annotatescrollbar');
  29. require('codemirror/addon/fold/foldcode');
  30. require('codemirror/addon/fold/foldgutter');
  31. require('codemirror/addon/fold/foldgutter.css');
  32. require('codemirror/addon/fold/markdown-fold');
  33. require('codemirror/addon/fold/brace-fold');
  34. require('codemirror/addon/display/placeholder');
  35. require('codemirror/mode/gfm/gfm');
  36. require('../../util/codemirror/autorefresh.ext');
  37. import pasteHelper from './PasteHelper';
  38. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  39. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  40. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  41. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  42. import mtu from './MarkdownTableUtil';
  43. export default class CodeMirrorEditor extends AbstractEditor {
  44. constructor(props) {
  45. super(props);
  46. this.logger = require('@alias/logger')('growi:PageEditor:CodeMirrorEditor');
  47. this.state = {
  48. value: this.props.value,
  49. isGfmMode: this.props.isGfmMode,
  50. isEnabledEmojiAutoComplete: false,
  51. isLoadingKeymap: false,
  52. isSimpleCheatsheetShown: this.props.isGfmMode && this.props.value.length === 0,
  53. isCheatsheetModalButtonShown: this.props.isGfmMode && this.props.value.length > 0,
  54. isCheatsheetModalShown: false,
  55. additionalClassSet: new Set(),
  56. };
  57. this.init();
  58. this.getCodeMirror = this.getCodeMirror.bind(this);
  59. this.getBol = this.getBol.bind(this);
  60. this.getEol = this.getEol.bind(this);
  61. this.loadTheme = this.loadTheme.bind(this);
  62. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  63. this.setKeymapMode = this.setKeymapMode.bind(this);
  64. this.handleEnterKey = this.handleEnterKey.bind(this);
  65. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  66. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  67. this.pasteHandler = this.pasteHandler.bind(this);
  68. this.cursorHandler = this.cursorHandler.bind(this);
  69. this.changeHandler = this.changeHandler.bind(this);
  70. this.updateCheatsheetStates = this.updateCheatsheetStates.bind(this);
  71. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  72. this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
  73. }
  74. init() {
  75. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  76. this.interceptorManager = new InterceptorManager();
  77. this.interceptorManager.addInterceptors([
  78. new PreventMarkdownListInterceptor(),
  79. new MarkdownTableInterceptor(),
  80. ]);
  81. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  82. this.loadedKeymapSet = new Set();
  83. }
  84. componentWillMount() {
  85. if (this.props.emojiStrategy != null) {
  86. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  87. this.setState({isEnabledEmojiAutoComplete: true});
  88. }
  89. }
  90. componentDidMount() {
  91. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  92. this.getCodeMirror().codeMirrorEditor = this;
  93. // initialize caret line
  94. this.setCaretLine(0);
  95. }
  96. componentWillReceiveProps(nextProps) {
  97. // load theme
  98. const theme = nextProps.editorOptions.theme;
  99. this.loadTheme(theme);
  100. // set keymap
  101. const keymapMode = nextProps.editorOptions.keymapMode;
  102. this.setKeymapMode(keymapMode);
  103. }
  104. getCodeMirror() {
  105. return this.refs.cm.editor;
  106. }
  107. /**
  108. * @inheritDoc
  109. */
  110. forceToFocus() {
  111. const editor = this.getCodeMirror();
  112. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  113. const intervalId = setInterval(() => {
  114. this.getCodeMirror().focus();
  115. if (editor.hasFocus()) {
  116. clearInterval(intervalId);
  117. // refresh
  118. editor.refresh();
  119. }
  120. }, 100);
  121. }
  122. /**
  123. * @inheritDoc
  124. */
  125. setValue(newValue) {
  126. this.setState({ value: newValue });
  127. this.getCodeMirror().getDoc().setValue(newValue);
  128. }
  129. /**
  130. * @inheritDoc
  131. */
  132. setGfmMode(bool) {
  133. // update state
  134. this.setState({
  135. isGfmMode: bool,
  136. isEnabledEmojiAutoComplete: bool,
  137. });
  138. this.updateCheatsheetStates(bool, null);
  139. // update CodeMirror option
  140. const mode = bool ? 'gfm' : undefined;
  141. this.getCodeMirror().setOption('mode', mode);
  142. }
  143. /**
  144. * @inheritDoc
  145. */
  146. setCaretLine(line) {
  147. if (isNaN(line)) {
  148. return;
  149. }
  150. const editor = this.getCodeMirror();
  151. const linePosition = Math.max(0, line);
  152. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  153. this.setScrollTopByLine(linePosition);
  154. }
  155. /**
  156. * @inheritDoc
  157. */
  158. setScrollTopByLine(line) {
  159. if (isNaN(line)) {
  160. return;
  161. }
  162. const editor = this.getCodeMirror();
  163. // get top position of the line
  164. const top = editor.charCoords({line, ch: 0}, 'local').top;
  165. editor.scrollTo(null, top);
  166. }
  167. /**
  168. * @inheritDoc
  169. */
  170. getStrFromBol() {
  171. const editor = this.getCodeMirror();
  172. const curPos = editor.getCursor();
  173. return editor.getDoc().getRange(this.getBol(), curPos);
  174. }
  175. /**
  176. * @inheritDoc
  177. */
  178. getStrToEol() {
  179. const editor = this.getCodeMirror();
  180. const curPos = editor.getCursor();
  181. return editor.getDoc().getRange(curPos, this.getEol());
  182. }
  183. /**
  184. * @inheritDoc
  185. */
  186. getStrFromBolToSelectedUpperPos() {
  187. const editor = this.getCodeMirror();
  188. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  189. return editor.getDoc().getRange(this.getBol(), pos);
  190. }
  191. /**
  192. * @inheritDoc
  193. */
  194. replaceBolToCurrentPos(text) {
  195. const editor = this.getCodeMirror();
  196. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  197. editor.getDoc().replaceRange(text, this.getBol(), pos);
  198. }
  199. /**
  200. * @inheritDoc
  201. */
  202. insertText(text) {
  203. const editor = this.getCodeMirror();
  204. editor.getDoc().replaceSelection(text);
  205. }
  206. /**
  207. * return the postion of the BOL(beginning of line)
  208. */
  209. getBol() {
  210. const editor = this.getCodeMirror();
  211. const curPos = editor.getCursor();
  212. return { line: curPos.line, ch: 0 };
  213. }
  214. /**
  215. * return the postion of the EOL(end of line)
  216. */
  217. getEol() {
  218. const editor = this.getCodeMirror();
  219. const curPos = editor.getCursor();
  220. const lineLength = editor.getDoc().getLine(curPos.line).length;
  221. return { line: curPos.line, ch: lineLength };
  222. }
  223. /**
  224. * select the upper position of pos1 and pos2
  225. * @param {{line: number, ch: number}} pos1
  226. * @param {{line: number, ch: number}} pos2
  227. */
  228. selectUpperPos(pos1, pos2) {
  229. // if both is in same line
  230. if (pos1.line === pos2.line) {
  231. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  232. }
  233. return (pos1.line < pos2.line) ? pos1 : pos2;
  234. }
  235. /**
  236. * select the lower position of pos1 and pos2
  237. * @param {{line: number, ch: number}} pos1
  238. * @param {{line: number, ch: number}} pos2
  239. */
  240. selectLowerPos(pos1, pos2) {
  241. // if both is in same line
  242. if (pos1.line === pos2.line) {
  243. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  244. }
  245. return (pos1.line < pos2.line) ? pos2 : pos1;
  246. }
  247. loadCss(source) {
  248. return new Promise((resolve) => {
  249. loadCssSync(source);
  250. resolve();
  251. });
  252. }
  253. /**
  254. * load Theme
  255. * @see https://codemirror.net/doc/manual.html#config
  256. *
  257. * @param {string} theme
  258. */
  259. loadTheme(theme) {
  260. if (!this.loadedThemeSet.has(theme)) {
  261. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  262. // update Set
  263. this.loadedThemeSet.add(theme);
  264. }
  265. }
  266. /**
  267. * load assets for Key Maps
  268. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  269. */
  270. loadKeymapMode(keymapMode) {
  271. const loadCss = this.loadCss;
  272. let scriptList = [];
  273. let cssList = [];
  274. // add dependencies
  275. if (this.loadedKeymapSet.size == 0) {
  276. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  277. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  278. }
  279. // load keymap
  280. if (!this.loadedKeymapSet.has(keymapMode)) {
  281. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  282. // update Set
  283. this.loadedKeymapSet.add(keymapMode);
  284. }
  285. // set loading state
  286. this.setState({ isLoadingKeymap: true });
  287. return Promise.all(scriptList.concat(cssList))
  288. .then(() => {
  289. this.setState({ isLoadingKeymap: false });
  290. });
  291. }
  292. /**
  293. * set Key Maps
  294. * @see https://codemirror.net/doc/manual.html#keymaps
  295. *
  296. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  297. */
  298. setKeymapMode(keymapMode) {
  299. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  300. // reset
  301. this.getCodeMirror().setOption('keyMap', 'default');
  302. return;
  303. }
  304. this.loadKeymapMode(keymapMode)
  305. .then(() => {
  306. this.getCodeMirror().setOption('keyMap', keymapMode);
  307. });
  308. }
  309. /**
  310. * handle ENTER key
  311. */
  312. handleEnterKey() {
  313. if (!this.state.isGfmMode) {
  314. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  315. return;
  316. }
  317. const context = {
  318. handlers: [], // list of handlers which process enter key
  319. editor: this,
  320. };
  321. const interceptorManager = this.interceptorManager;
  322. interceptorManager.process('preHandleEnter', context)
  323. .then(() => {
  324. if (context.handlers.length == 0) {
  325. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  326. }
  327. });
  328. }
  329. /**
  330. * handle Ctrl+ENTER key
  331. */
  332. handleCtrlEnterKey() {
  333. if (this.props.onCtrlEnter != null) {
  334. this.props.onCtrlEnter();
  335. }
  336. }
  337. scrollCursorIntoViewHandler(editor, event) {
  338. if (this.props.onScrollCursorIntoView != null) {
  339. const line = editor.getCursor().line;
  340. this.props.onScrollCursorIntoView(line);
  341. }
  342. }
  343. cursorHandler(editor, event) {
  344. const strFromBol = this.getStrFromBol();
  345. const autoformatTableClass = 'autoformat-markdown-table-activated';
  346. const additionalClassSet = this.state.additionalClassSet;
  347. const hasCustomClass = additionalClassSet.has(autoformatTableClass);
  348. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  349. if (!hasCustomClass) {
  350. additionalClassSet.add(autoformatTableClass);
  351. this.setState({additionalClassSet});
  352. }
  353. }
  354. else {
  355. if (hasCustomClass) {
  356. additionalClassSet.delete(autoformatTableClass);
  357. this.setState({additionalClassSet});
  358. }
  359. }
  360. }
  361. changeHandler(editor, data, value) {
  362. if (this.props.onChange != null) {
  363. this.props.onChange(value);
  364. }
  365. this.updateCheatsheetStates(null, value);
  366. // Emoji AutoComplete
  367. if (this.state.isEnabledEmojiAutoComplete) {
  368. this.emojiAutoCompleteHelper.showHint(editor);
  369. }
  370. }
  371. /**
  372. * CodeMirror paste event handler
  373. * see: https://codemirror.net/doc/manual.html#events
  374. * @param {any} editor An editor instance of CodeMirror
  375. * @param {any} event
  376. */
  377. pasteHandler(editor, event) {
  378. const types = event.clipboardData.types;
  379. // text
  380. if (types.includes('text/plain')) {
  381. pasteHelper.pasteText(this, event);
  382. }
  383. // files
  384. else if (types.includes('Files')) {
  385. this.dispatchPasteFiles(event);
  386. }
  387. }
  388. /**
  389. * update states which related to cheatsheet
  390. * @param {boolean} isGfmMode (use state.isGfmMode if null is set)
  391. * @param {string} value (get value from codemirror if null is set)
  392. */
  393. updateCheatsheetStates(isGfmMode, value) {
  394. if (isGfmMode == null) {
  395. isGfmMode = this.state.isGfmMode;
  396. }
  397. if (value == null) {
  398. value = this.getCodeMirror().getDoc().getValue();
  399. }
  400. // update isSimpleCheatsheetShown, isCheatsheetModalButtonShown
  401. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  402. const isCheatsheetModalButtonShown = isGfmMode && value.length > 0;
  403. this.setState({ isSimpleCheatsheetShown, isCheatsheetModalButtonShown });
  404. }
  405. renderLoadingKeymapOverlay() {
  406. // centering
  407. const style = {
  408. top: 0,
  409. right: 0,
  410. bottom: 0,
  411. left: 0,
  412. };
  413. return this.state.isLoadingKeymap
  414. ? <div className="overlay overlay-loading-keymap">
  415. <span style={style} className="overlay-content">
  416. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  417. </span>
  418. </div>
  419. : '';
  420. }
  421. renderSimpleCheatsheet() {
  422. return (
  423. <div className="panel panel-default gfm-cheatsheet mb-0">
  424. <div className="panel-body small p-b-0">
  425. <div className="row">
  426. <div className="col-xs-6">
  427. <p>
  428. # 見出し1<br />
  429. ## 見出し2
  430. </p>
  431. <p><i>*斜体*</i>&nbsp;&nbsp;<b>**強調**</b></p>
  432. <p>
  433. [リンク](http://..)<br />
  434. [/ページ名/子ページ名]
  435. </p>
  436. <p>
  437. ```javascript:index.js<br />
  438. writeCode();<br />
  439. ```
  440. </p>
  441. </div>
  442. <div className="col-xs-6">
  443. <p>
  444. - リスト 1<br />
  445. &nbsp;&nbsp;&nbsp;&nbsp;- リスト 1_1<br />
  446. - リスト 2<br />
  447. 1. 番号付きリスト 1
  448. 1. 番号付きリスト 2
  449. </p>
  450. <hr />
  451. <p>行末にスペース2つ[ ][ ]<br />で改行</p>
  452. </div>
  453. </div>
  454. </div>
  455. </div>
  456. );
  457. }
  458. renderCheatsheetModalBody() {
  459. return (
  460. <div className="row small">
  461. <div className="col-sm-6">
  462. <h4>Header</h4>
  463. <ul className="hljs">
  464. <li><code># </code>見出し1</li>
  465. <li><code>## </code>見出し2</li>
  466. <li><code>### </code>見出し3</li>
  467. </ul>
  468. <h4>Block</h4>
  469. <p className="mb-1"><code>[空白行]</code>を挟むことで段落になります</p>
  470. <ul className="hljs">
  471. <li>text</li>
  472. <li></li>
  473. <li>text</li>
  474. </ul>
  475. <h4>Line breaks</h4>
  476. <p className="mb-1">段落中、<code>[space][space]</code>(スペース2つ) で改行されます</p>
  477. <ul className="hljs">
  478. <li>text<code> </code><code> </code></li>
  479. <li>text</li>
  480. </ul>
  481. <h4>Typography</h4>
  482. <ul className="hljs">
  483. <li><i>*イタリック*</i></li>
  484. <li><b>**ボールド**</b></li>
  485. <li><i><b>***イタリックボールド***</b></i></li>
  486. <li>~~取り消し線~~ => <s>striked text</s></li>
  487. </ul>
  488. <h4>Link</h4>
  489. <ul className="hljs">
  490. <li>[Google](https://www.google.co.jp/)</li>
  491. <li>[/Page1/ChildPage1]</li>
  492. </ul>
  493. <h4>コードハイライト</h4>
  494. <ul className="hljs">
  495. <li>```javascript:index.js</li>
  496. <li>writeCode();</li>
  497. <li>```</li>
  498. </ul>
  499. </div>
  500. <div className="col-sm-6">
  501. <h4>リスト</h4>
  502. <ul className="hljs">
  503. <li>- リスト 1</li>
  504. <li>&nbsp;&nbsp;- リスト 1_1</li>
  505. <li>- リスト 2</li>
  506. </ul>
  507. <ul className="hljs">
  508. <li>1. 番号付きリスト 1</li>
  509. <li>1. 番号付きリスト 2</li>
  510. </ul>
  511. <ul className="hljs">
  512. <li>- [ ] タスク(チェックなし)</li>
  513. <li>- [x] タスク(チェック付き)</li>
  514. </ul>
  515. <h4>引用</h4>
  516. <ul className="hljs">
  517. <li>> 複数行の引用文を</li>
  518. <li>> 書くことができます</li>
  519. </ul>
  520. <ul className="hljs">
  521. <li>>> 多重引用</li>
  522. <li>>>> 多重引用</li>
  523. <li>>>>> 多重引用</li>
  524. </ul>
  525. <h4>Table</h4>
  526. <ul className="hljs text-center">
  527. <li>|&nbsp;&nbsp;&nbsp;左寄せ&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;中央寄せ&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;右寄せ&nbsp;&nbsp;&nbsp;|</li>
  528. <li>|:-----------|:----------:|-----------:|</li>
  529. <li>|column 1&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;column 2&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;column 3|</li>
  530. <li>|column 1&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;column 2&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;column 3|</li>
  531. </ul>
  532. <h4>Images</h4>
  533. <p className="mb-1"><code> ![Alt文字列](URL)</code> で<span className="text-info">&lt;img&gt;</span>タグを挿入できます</p>
  534. <ul className="hljs">
  535. <li>![ex](https://example.com/images/a.png)</li>
  536. </ul>
  537. <hr />
  538. <a href="/Sandbox" className="btn btn-info btn-block" target="_blank">
  539. <i className="icon-share-alt"/> Sandbox を開く
  540. </a>
  541. </div>
  542. </div>
  543. );
  544. }
  545. renderCheatsheetModalButton() {
  546. const showCheatsheetModal = () => {
  547. this.setState({isCheatsheetModalShown: true});
  548. };
  549. const hideCheatsheetModal = () => {
  550. this.setState({isCheatsheetModalShown: false});
  551. };
  552. return (
  553. <React.Fragment>
  554. <Modal className="modal-gfm-cheatsheet" show={this.state.isCheatsheetModalShown} onHide={() => { hideCheatsheetModal() }}>
  555. <Modal.Header closeButton>
  556. <Modal.Title><i className="icon-fw icon-question"/>Markdown Help</Modal.Title>
  557. </Modal.Header>
  558. <Modal.Body className="pt-1">
  559. { this.renderCheatsheetModalBody() }
  560. </Modal.Body>
  561. </Modal>
  562. <a className="gfm-cheatsheet-modal-link text-muted small" onClick={() => { showCheatsheetModal() }}>
  563. <i className="icon-question" /> Markdown
  564. </a>
  565. </React.Fragment>
  566. );
  567. }
  568. render() {
  569. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  570. const defaultEditorOptions = {
  571. theme: 'elegant',
  572. lineNumbers: true,
  573. };
  574. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  575. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  576. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  577. return <React.Fragment>
  578. <ReactCodeMirror
  579. ref="cm"
  580. className={additionalClasses}
  581. placeholder="search"
  582. editorDidMount={(editor) => {
  583. // add event handlers
  584. editor.on('paste', this.pasteHandler);
  585. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  586. }}
  587. value={this.state.value}
  588. options={{
  589. mode: mode,
  590. theme: editorOptions.theme,
  591. styleActiveLine: editorOptions.styleActiveLine,
  592. lineNumbers: this.props.lineNumbers,
  593. tabSize: 4,
  594. indentUnit: 4,
  595. lineWrapping: true,
  596. autoRefresh: {force: true}, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  597. autoCloseTags: true,
  598. placeholder: placeholder,
  599. matchBrackets: true,
  600. matchTags: {bothTags: true},
  601. // folding
  602. foldGutter: this.props.lineNumbers,
  603. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  604. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  605. highlightSelectionMatches: {annotateScrollbar: true},
  606. // markdown mode options
  607. highlightFormatting: true,
  608. // continuelist, indentlist
  609. extraKeys: {
  610. 'Enter': this.handleEnterKey,
  611. 'Ctrl-Enter': this.handleCtrlEnterKey,
  612. 'Cmd-Enter': this.handleCtrlEnterKey,
  613. 'Tab': 'indentMore',
  614. 'Shift-Tab': 'indentLess',
  615. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  616. }
  617. }}
  618. onCursor={this.cursorHandler}
  619. onScroll={(editor, data) => {
  620. if (this.props.onScroll != null) {
  621. // add line data
  622. const line = editor.lineAtHeight(data.top, 'local');
  623. data.line = line;
  624. this.props.onScroll(data);
  625. }
  626. }}
  627. onChange={this.changeHandler}
  628. onDragEnter={(editor, event) => {
  629. if (this.props.onDragEnter != null) {
  630. this.props.onDragEnter(event);
  631. }
  632. }}
  633. />
  634. { this.renderLoadingKeymapOverlay() }
  635. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3 pt-3">
  636. { this.state.isSimpleCheatsheetShown && this.renderSimpleCheatsheet() }
  637. { this.state.isCheatsheetModalButtonShown && this.renderCheatsheetModalButton() }
  638. </div>
  639. </React.Fragment>;
  640. }
  641. }
  642. CodeMirrorEditor.propTypes = Object.assign({
  643. emojiStrategy: PropTypes.object,
  644. lineNumbers: PropTypes.bool,
  645. }, AbstractEditor.propTypes);
  646. CodeMirrorEditor.defaultProps = {
  647. lineNumbers: true,
  648. };