CodeMirrorEditor.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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 SimpleCheatsheet from './SimpleCheatsheet';
  40. import Cheatsheet from './Cheatsheet';
  41. import pasteHelper from './PasteHelper';
  42. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  43. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  44. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  45. import mtu from './MarkdownTableUtil';
  46. import HandsontableModal from './HandsontableModal';
  47. export default class CodeMirrorEditor extends AbstractEditor {
  48. constructor(props) {
  49. super(props);
  50. this.logger = require('@alias/logger')('growi:PageEditor:CodeMirrorEditor');
  51. this.state = {
  52. value: this.props.value,
  53. isGfmMode: this.props.isGfmMode,
  54. isEnabledEmojiAutoComplete: false,
  55. isLoadingKeymap: false,
  56. isSimpleCheatsheetShown: this.props.isGfmMode && this.props.value.length === 0,
  57. isCheatsheetModalButtonShown: this.props.isGfmMode && this.props.value.length > 0,
  58. isCheatsheetModalShown: false,
  59. additionalClassSet: new Set(),
  60. };
  61. this.init();
  62. this.getCodeMirror = this.getCodeMirror.bind(this);
  63. this.getBol = this.getBol.bind(this);
  64. this.getEol = this.getEol.bind(this);
  65. this.loadTheme = this.loadTheme.bind(this);
  66. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  67. this.setKeymapMode = this.setKeymapMode.bind(this);
  68. this.handleEnterKey = this.handleEnterKey.bind(this);
  69. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  70. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  71. this.pasteHandler = this.pasteHandler.bind(this);
  72. this.cursorHandler = this.cursorHandler.bind(this);
  73. this.changeHandler = this.changeHandler.bind(this);
  74. this.updateCheatsheetStates = this.updateCheatsheetStates.bind(this);
  75. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  76. this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
  77. this.makeHeaderHandler = this.makeHeaderHandler.bind(this);
  78. this.showHandsonTableHandler = this.showHandsonTableHandler.bind(this);
  79. }
  80. init() {
  81. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.42.0';
  82. this.cmNoCdnScriptRoot = '/js/cdn';
  83. this.cmNoCdnStyleRoot = '/styles/cdn';
  84. this.interceptorManager = new InterceptorManager();
  85. this.interceptorManager.addInterceptors([
  86. new PreventMarkdownListInterceptor(),
  87. new MarkdownTableInterceptor(),
  88. ]);
  89. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  90. this.loadedKeymapSet = new Set();
  91. }
  92. componentWillMount() {
  93. if (this.props.emojiStrategy != null) {
  94. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  95. this.setState({isEnabledEmojiAutoComplete: true});
  96. }
  97. }
  98. componentDidMount() {
  99. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  100. this.getCodeMirror().codeMirrorEditor = this;
  101. }
  102. componentWillReceiveProps(nextProps) {
  103. // load theme
  104. const theme = nextProps.editorOptions.theme;
  105. this.loadTheme(theme);
  106. // set keymap
  107. const keymapMode = nextProps.editorOptions.keymapMode;
  108. this.setKeymapMode(keymapMode);
  109. }
  110. getCodeMirror() {
  111. return this.refs.cm.editor;
  112. }
  113. /**
  114. * @inheritDoc
  115. */
  116. forceToFocus() {
  117. const editor = this.getCodeMirror();
  118. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  119. const intervalId = setInterval(() => {
  120. this.getCodeMirror().focus();
  121. if (editor.hasFocus()) {
  122. clearInterval(intervalId);
  123. // refresh
  124. editor.refresh();
  125. }
  126. }, 100);
  127. }
  128. /**
  129. * @inheritDoc
  130. */
  131. setValue(newValue) {
  132. this.setState({ value: newValue });
  133. this.getCodeMirror().getDoc().setValue(newValue);
  134. }
  135. /**
  136. * @inheritDoc
  137. */
  138. setGfmMode(bool) {
  139. // update state
  140. this.setState({
  141. isGfmMode: bool,
  142. isEnabledEmojiAutoComplete: bool,
  143. });
  144. this.updateCheatsheetStates(bool, null);
  145. // update CodeMirror option
  146. const mode = bool ? 'gfm' : undefined;
  147. this.getCodeMirror().setOption('mode', mode);
  148. }
  149. /**
  150. * @inheritDoc
  151. */
  152. setCaretLine(line) {
  153. if (isNaN(line)) {
  154. return;
  155. }
  156. const editor = this.getCodeMirror();
  157. const linePosition = Math.max(0, line);
  158. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  159. this.setScrollTopByLine(linePosition);
  160. }
  161. /**
  162. * @inheritDoc
  163. */
  164. setScrollTopByLine(line) {
  165. if (isNaN(line)) {
  166. return;
  167. }
  168. const editor = this.getCodeMirror();
  169. // get top position of the line
  170. const top = editor.charCoords({line, ch: 0}, 'local').top;
  171. editor.scrollTo(null, top);
  172. }
  173. /**
  174. * @inheritDoc
  175. */
  176. getStrFromBol() {
  177. const editor = this.getCodeMirror();
  178. const curPos = editor.getCursor();
  179. return editor.getDoc().getRange(this.getBol(), curPos);
  180. }
  181. /**
  182. * @inheritDoc
  183. */
  184. getStrToEol() {
  185. const editor = this.getCodeMirror();
  186. const curPos = editor.getCursor();
  187. return editor.getDoc().getRange(curPos, this.getEol());
  188. }
  189. /**
  190. * @inheritDoc
  191. */
  192. getStrFromBolToSelectedUpperPos() {
  193. const editor = this.getCodeMirror();
  194. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  195. return editor.getDoc().getRange(this.getBol(), pos);
  196. }
  197. /**
  198. * @inheritDoc
  199. */
  200. replaceBolToCurrentPos(text) {
  201. const editor = this.getCodeMirror();
  202. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  203. editor.getDoc().replaceRange(text, this.getBol(), pos);
  204. }
  205. /**
  206. * @inheritDoc
  207. */
  208. insertText(text) {
  209. const editor = this.getCodeMirror();
  210. editor.getDoc().replaceSelection(text);
  211. }
  212. /**
  213. * return the postion of the BOL(beginning of line)
  214. */
  215. getBol() {
  216. const editor = this.getCodeMirror();
  217. const curPos = editor.getCursor();
  218. return { line: curPos.line, ch: 0 };
  219. }
  220. /**
  221. * return the postion of the EOL(end of line)
  222. */
  223. getEol() {
  224. const editor = this.getCodeMirror();
  225. const curPos = editor.getCursor();
  226. const lineLength = editor.getDoc().getLine(curPos.line).length;
  227. return { line: curPos.line, ch: lineLength };
  228. }
  229. /**
  230. * select the upper position of pos1 and pos2
  231. * @param {{line: number, ch: number}} pos1
  232. * @param {{line: number, ch: number}} pos2
  233. */
  234. selectUpperPos(pos1, pos2) {
  235. // if both is in same line
  236. if (pos1.line === pos2.line) {
  237. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  238. }
  239. return (pos1.line < pos2.line) ? pos1 : pos2;
  240. }
  241. /**
  242. * select the lower position of pos1 and pos2
  243. * @param {{line: number, ch: number}} pos1
  244. * @param {{line: number, ch: number}} pos2
  245. */
  246. selectLowerPos(pos1, pos2) {
  247. // if both is in same line
  248. if (pos1.line === pos2.line) {
  249. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  250. }
  251. return (pos1.line < pos2.line) ? pos2 : pos1;
  252. }
  253. loadCss(source) {
  254. return new Promise((resolve) => {
  255. loadCssSync(source);
  256. resolve();
  257. });
  258. }
  259. /**
  260. * load Theme
  261. * @see https://codemirror.net/doc/manual.html#config
  262. *
  263. * @param {string} theme
  264. */
  265. loadTheme(theme) {
  266. if (!this.loadedThemeSet.has(theme)) {
  267. const url = this.props.noCdn
  268. ? urljoin(this.cmNoCdnStyleRoot, `codemirror-theme-${theme}.css`)
  269. : urljoin(this.cmCdnRoot, `theme/${theme}.min.css`);
  270. this.loadCss(url);
  271. // update Set
  272. this.loadedThemeSet.add(theme);
  273. }
  274. }
  275. /**
  276. * load assets for Key Maps
  277. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  278. */
  279. loadKeymapMode(keymapMode) {
  280. const loadCss = this.loadCss;
  281. let scriptList = [];
  282. let cssList = [];
  283. // add dependencies
  284. if (this.loadedKeymapSet.size == 0) {
  285. const dialogScriptUrl = this.props.noCdn
  286. ? urljoin(this.cmNoCdnScriptRoot, 'codemirror-dialog.js')
  287. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js');
  288. const dialogStyleUrl = this.props.noCdn
  289. ? urljoin(this.cmNoCdnStyleRoot, 'codemirror-dialog.css')
  290. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css');
  291. scriptList.push(loadScript(dialogScriptUrl));
  292. cssList.push(loadCss(dialogStyleUrl));
  293. }
  294. // load keymap
  295. if (!this.loadedKeymapSet.has(keymapMode)) {
  296. const keymapScriptUrl = this.props.noCdn
  297. ? urljoin(this.cmNoCdnScriptRoot, `codemirror-keymap-${keymapMode}.js`)
  298. : urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`);
  299. scriptList.push(loadScript(keymapScriptUrl));
  300. // update Set
  301. this.loadedKeymapSet.add(keymapMode);
  302. }
  303. // set loading state
  304. this.setState({ isLoadingKeymap: true });
  305. return Promise.all(scriptList.concat(cssList))
  306. .then(() => {
  307. this.setState({ isLoadingKeymap: false });
  308. });
  309. }
  310. /**
  311. * set Key Maps
  312. * @see https://codemirror.net/doc/manual.html#keymaps
  313. *
  314. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  315. */
  316. setKeymapMode(keymapMode) {
  317. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  318. // reset
  319. this.getCodeMirror().setOption('keyMap', 'default');
  320. return;
  321. }
  322. this.loadKeymapMode(keymapMode)
  323. .then(() => {
  324. this.getCodeMirror().setOption('keyMap', keymapMode);
  325. });
  326. }
  327. /**
  328. * handle ENTER key
  329. */
  330. handleEnterKey() {
  331. if (!this.state.isGfmMode) {
  332. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  333. return;
  334. }
  335. const context = {
  336. handlers: [], // list of handlers which process enter key
  337. editor: this,
  338. };
  339. const interceptorManager = this.interceptorManager;
  340. interceptorManager.process('preHandleEnter', context)
  341. .then(() => {
  342. if (context.handlers.length == 0) {
  343. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  344. }
  345. });
  346. }
  347. /**
  348. * handle Ctrl+ENTER key
  349. */
  350. handleCtrlEnterKey() {
  351. if (this.props.onCtrlEnter != null) {
  352. this.props.onCtrlEnter();
  353. }
  354. }
  355. scrollCursorIntoViewHandler(editor, event) {
  356. if (this.props.onScrollCursorIntoView != null) {
  357. const line = editor.getCursor().line;
  358. this.props.onScrollCursorIntoView(line);
  359. }
  360. }
  361. cursorHandler(editor, event) {
  362. const strFromBol = this.getStrFromBol();
  363. const autoformatTableClass = 'autoformat-markdown-table-activated';
  364. const additionalClassSet = this.state.additionalClassSet;
  365. const hasCustomClass = additionalClassSet.has(autoformatTableClass);
  366. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  367. if (!hasCustomClass) {
  368. additionalClassSet.add(autoformatTableClass);
  369. this.setState({additionalClassSet});
  370. }
  371. }
  372. else {
  373. if (hasCustomClass) {
  374. additionalClassSet.delete(autoformatTableClass);
  375. this.setState({additionalClassSet});
  376. }
  377. }
  378. }
  379. changeHandler(editor, data, value) {
  380. if (this.props.onChange != null) {
  381. this.props.onChange(value);
  382. }
  383. this.updateCheatsheetStates(null, value);
  384. // Emoji AutoComplete
  385. if (this.state.isEnabledEmojiAutoComplete) {
  386. this.emojiAutoCompleteHelper.showHint(editor);
  387. }
  388. }
  389. /**
  390. * CodeMirror paste event handler
  391. * see: https://codemirror.net/doc/manual.html#events
  392. * @param {any} editor An editor instance of CodeMirror
  393. * @param {any} event
  394. */
  395. pasteHandler(editor, event) {
  396. const types = event.clipboardData.types;
  397. // files
  398. if (types.includes('Files')) {
  399. event.preventDefault();
  400. this.dispatchPasteFiles(event);
  401. }
  402. // text
  403. else if (types.includes('text/plain')) {
  404. pasteHelper.pasteText(this, event);
  405. }
  406. }
  407. /**
  408. * update states which related to cheatsheet
  409. * @param {boolean} isGfmMode (use state.isGfmMode if null is set)
  410. * @param {string} value (get value from codemirror if null is set)
  411. */
  412. updateCheatsheetStates(isGfmMode, value) {
  413. if (isGfmMode == null) {
  414. isGfmMode = this.state.isGfmMode;
  415. }
  416. if (value == null) {
  417. value = this.getCodeMirror().getDoc().getValue();
  418. }
  419. // update isSimpleCheatsheetShown, isCheatsheetModalButtonShown
  420. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  421. const isCheatsheetModalButtonShown = isGfmMode && value.length > 0;
  422. this.setState({ isSimpleCheatsheetShown, isCheatsheetModalButtonShown });
  423. }
  424. renderLoadingKeymapOverlay() {
  425. // centering
  426. const style = {
  427. top: 0,
  428. right: 0,
  429. bottom: 0,
  430. left: 0,
  431. };
  432. return this.state.isLoadingKeymap
  433. ? <div className="overlay overlay-loading-keymap">
  434. <span style={style} className="overlay-content">
  435. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  436. </span>
  437. </div>
  438. : '';
  439. }
  440. renderSimpleCheatsheet() {
  441. return <SimpleCheatsheet />;
  442. }
  443. renderCheatsheetModalBody() {
  444. return <Cheatsheet />;
  445. }
  446. renderCheatsheetModalButton() {
  447. const showCheatsheetModal = () => {
  448. this.setState({isCheatsheetModalShown: true});
  449. };
  450. const hideCheatsheetModal = () => {
  451. this.setState({isCheatsheetModalShown: false});
  452. };
  453. return (
  454. <React.Fragment>
  455. <Modal className="modal-gfm-cheatsheet" show={this.state.isCheatsheetModalShown} onHide={() => { hideCheatsheetModal() }}>
  456. <Modal.Header closeButton>
  457. <Modal.Title><i className="icon-fw icon-question"/>Markdown Help</Modal.Title>
  458. </Modal.Header>
  459. <Modal.Body className="pt-1">
  460. { this.renderCheatsheetModalBody() }
  461. </Modal.Body>
  462. </Modal>
  463. <a className="gfm-cheatsheet-modal-link text-muted small" onClick={() => { showCheatsheetModal() }}>
  464. <i className="icon-question" /> Markdown
  465. </a>
  466. </React.Fragment>
  467. );
  468. }
  469. /**
  470. * return a function to replace a selected range with prefix + selection + suffix
  471. *
  472. * The cursor after replacing is inserted between the selection and the suffix.
  473. */
  474. createReplaceSelectionHandler(prefix, suffix) {
  475. return () => {
  476. const cm = this.getCodeMirror();
  477. const selection = cm.getDoc().getSelection();
  478. const curStartPos = cm.getCursor('from');
  479. const curEndPos = cm.getCursor('to');
  480. const curPosAfterReplacing = {};
  481. curPosAfterReplacing.line = curEndPos.line;
  482. if (curStartPos.line === curEndPos.line) {
  483. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  484. }
  485. else {
  486. curPosAfterReplacing.ch = curEndPos.ch;
  487. }
  488. cm.getDoc().replaceSelection(prefix + selection + suffix);
  489. cm.setCursor(curPosAfterReplacing);
  490. cm.focus();
  491. };
  492. }
  493. /**
  494. * return a function to add prefix to selected each lines
  495. *
  496. * The cursor after editing is inserted between the end of the selection.
  497. */
  498. createAddPrefixToEachLinesHandler(prefix) {
  499. return () => {
  500. const cm = this.getCodeMirror();
  501. const startLineNum = cm.getCursor('from').line;
  502. const endLineNum = cm.getCursor('to').line;
  503. const lines = [];
  504. for (let i = startLineNum; i <= endLineNum; i++) {
  505. lines.push(prefix + cm.getDoc().getLine(i));
  506. }
  507. const replacement = lines.join('\n') + '\n';
  508. cm.getDoc().replaceRange(replacement, {line: startLineNum, ch: 0}, {line: endLineNum + 1, ch: 0});
  509. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  510. cm.focus();
  511. };
  512. }
  513. /**
  514. * make a selected line a header
  515. *
  516. * The cursor after editing is inserted between the end of the line.
  517. */
  518. makeHeaderHandler() {
  519. const cm = this.getCodeMirror();
  520. const lineNum = cm.getCursor('from').line;
  521. const line = cm.getDoc().getLine(lineNum);
  522. let prefix = '#';
  523. if (!line.startsWith('#')) {
  524. prefix += ' ';
  525. }
  526. cm.getDoc().replaceRange(prefix, {line: lineNum, ch: 0}, {line: lineNum, ch: 0});
  527. cm.focus();
  528. }
  529. showHandsonTableHandler() {
  530. this.refs.handsontableModal.show(mtu.getMarkdownTable(this.getCodeMirror()));
  531. }
  532. getNavbarItems() {
  533. // The following styles will be removed after creating icons for the editor navigation bar.
  534. const paddingTopBottom54 = {'paddingTop': '6px', 'paddingBottom': '5px'};
  535. const paddingBottom6 = {'paddingBottom': '7px'};
  536. const fontSize18 = {'fontSize': '18px'};
  537. return [
  538. <Button key='nav-item-bold' bsSize="small" title={'Bold'}
  539. onClick={ this.createReplaceSelectionHandler('**', '**') }>
  540. <i className={'fa fa-bold'}></i>
  541. </Button>,
  542. <Button key='nav-item-italic' bsSize="small" title={'Italic'}
  543. onClick={ this.createReplaceSelectionHandler('*', '*') }>
  544. <i className={'fa fa-italic'}></i>
  545. </Button>,
  546. <Button key='nav-item-strikethough' bsSize="small" title={'Strikethrough'}
  547. onClick={ this.createReplaceSelectionHandler('~~', '~~') }>
  548. <i className={'fa fa-strikethrough'}></i>
  549. </Button>,
  550. <Button key='nav-item-header' bsSize="small" title={'Heading'}
  551. onClick={ this.makeHeaderHandler }>
  552. <i className={'fa fa-header'}></i>
  553. </Button>,
  554. <Button key='nav-item-code' bsSize="small" title={'Inline Code'}
  555. onClick={ this.createReplaceSelectionHandler('`', '`') }>
  556. <i className={'fa fa-code'}></i>
  557. </Button>,
  558. <Button key='nav-item-quote' bsSize="small" title={'Quote'}
  559. onClick={ this.createAddPrefixToEachLinesHandler('> ') } style={paddingBottom6}>
  560. <i className={'ti-quote-right'}></i>
  561. </Button>,
  562. <Button key='nav-item-ul' bsSize="small" title={'List'}
  563. onClick={ this.createAddPrefixToEachLinesHandler('- ') } style={paddingTopBottom54}>
  564. <i className={'ti-list'} style={fontSize18}></i>
  565. </Button>,
  566. <Button key='nav-item-ol' bsSize="small" title={'Numbered List'}
  567. onClick={ this.createAddPrefixToEachLinesHandler('1. ') } style={paddingTopBottom54}>
  568. <i className={'ti-list-ol'} style={fontSize18}></i>
  569. </Button>,
  570. <Button key='nav-item-checkbox' bsSize="small" title={'Check List'}
  571. onClick={ this.createAddPrefixToEachLinesHandler('- [ ] ') } style={paddingBottom6}>
  572. <i className={'ti-check-box'}></i>
  573. </Button>,
  574. <Button key='nav-item-link' bsSize="small" title={'Link'}
  575. onClick={ this.createReplaceSelectionHandler('[', ']()') } style={paddingBottom6}>
  576. <i className={'icon-link'}></i>
  577. </Button>,
  578. <Button key='nav-item-image' bsSize="small" title={'Image'}
  579. onClick={ this.createReplaceSelectionHandler('![', ']()') } style={paddingBottom6}>
  580. <i className={'icon-picture'}></i>
  581. </Button>,
  582. <Button key='nav-item-table' bsSize="small" title={'Table'}
  583. onClick={ this.showHandsonTableHandler }>
  584. <img src="/images/icons/editor/table.svg" width="14" height="14" />
  585. </Button>
  586. ];
  587. }
  588. render() {
  589. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  590. const defaultEditorOptions = {
  591. theme: 'elegant',
  592. lineNumbers: true,
  593. };
  594. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  595. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  596. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  597. return <React.Fragment>
  598. <ReactCodeMirror
  599. ref="cm"
  600. className={additionalClasses}
  601. placeholder="search"
  602. editorDidMount={(editor) => {
  603. // add event handlers
  604. editor.on('paste', this.pasteHandler);
  605. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  606. }}
  607. value={this.state.value}
  608. options={{
  609. mode: mode,
  610. theme: editorOptions.theme,
  611. styleActiveLine: editorOptions.styleActiveLine,
  612. lineNumbers: this.props.lineNumbers,
  613. tabSize: 4,
  614. indentUnit: 4,
  615. lineWrapping: true,
  616. autoRefresh: {force: true}, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  617. autoCloseTags: true,
  618. placeholder: placeholder,
  619. matchBrackets: true,
  620. matchTags: {bothTags: true},
  621. // folding
  622. foldGutter: this.props.lineNumbers,
  623. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  624. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  625. highlightSelectionMatches: {annotateScrollbar: true},
  626. // markdown mode options
  627. highlightFormatting: true,
  628. // continuelist, indentlist
  629. extraKeys: {
  630. 'Enter': this.handleEnterKey,
  631. 'Ctrl-Enter': this.handleCtrlEnterKey,
  632. 'Cmd-Enter': this.handleCtrlEnterKey,
  633. 'Tab': 'indentMore',
  634. 'Shift-Tab': 'indentLess',
  635. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  636. }
  637. }}
  638. onCursor={this.cursorHandler}
  639. onScroll={(editor, data) => {
  640. if (this.props.onScroll != null) {
  641. // add line data
  642. const line = editor.lineAtHeight(data.top, 'local');
  643. data.line = line;
  644. this.props.onScroll(data);
  645. }
  646. }}
  647. onChange={this.changeHandler}
  648. onDragEnter={(editor, event) => {
  649. if (this.props.onDragEnter != null) {
  650. this.props.onDragEnter(event);
  651. }
  652. }}
  653. />
  654. { this.renderLoadingKeymapOverlay() }
  655. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3 pt-3">
  656. { this.state.isSimpleCheatsheetShown && this.renderSimpleCheatsheet() }
  657. { this.state.isCheatsheetModalButtonShown && this.renderCheatsheetModalButton() }
  658. </div>
  659. <HandsontableModal ref='handsontableModal' onSave={ table => mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }/>
  660. </React.Fragment>;
  661. }
  662. }
  663. CodeMirrorEditor.propTypes = Object.assign({
  664. emojiStrategy: PropTypes.object,
  665. lineNumbers: PropTypes.bool,
  666. }, AbstractEditor.propTypes);
  667. CodeMirrorEditor.defaultProps = {
  668. lineNumbers: true,
  669. };