CodeMirrorEditor.js 22 KB

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