CodeMirrorEditor.js 22 KB

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