CodeMirrorEditor.js 23 KB

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