CodeMirrorEditor.js 22 KB

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