CodeMirrorEditor.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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 urljoin from 'url-join';
  6. import * as codemirror from 'codemirror';
  7. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  8. import InterceptorManager from '@commons/service/interceptor-manager';
  9. import AbstractEditor from './AbstractEditor';
  10. import SimpleCheatsheet from './SimpleCheatsheet';
  11. import Cheatsheet from './Cheatsheet';
  12. import pasteHelper from './PasteHelper';
  13. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  14. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  15. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  16. import mtu from './MarkdownTableUtil';
  17. import HandsontableModal from './HandsontableModal';
  18. const loadScript = require('simple-load-script');
  19. const loadCssSync = require('load-css-file');
  20. // set save handler
  21. codemirror.commands.save = (instance) => {
  22. if (instance.codeMirrorEditor != null) {
  23. instance.codeMirrorEditor.dispatchSave();
  24. }
  25. };
  26. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  27. window.CodeMirror = require('codemirror');
  28. require('codemirror/addon/display/placeholder');
  29. require('codemirror/addon/edit/matchbrackets');
  30. require('codemirror/addon/edit/matchtags');
  31. require('codemirror/addon/edit/closetag');
  32. require('codemirror/addon/edit/continuelist');
  33. require('codemirror/addon/hint/show-hint');
  34. require('codemirror/addon/hint/show-hint.css');
  35. require('codemirror/addon/search/searchcursor');
  36. require('codemirror/addon/search/match-highlighter');
  37. require('codemirror/addon/selection/active-line');
  38. require('codemirror/addon/scroll/annotatescrollbar');
  39. require('codemirror/addon/fold/foldcode');
  40. require('codemirror/addon/fold/foldgutter');
  41. require('codemirror/addon/fold/foldgutter.css');
  42. require('codemirror/addon/fold/markdown-fold');
  43. require('codemirror/addon/fold/brace-fold');
  44. require('codemirror/addon/display/placeholder');
  45. require('codemirror/mode/gfm/gfm');
  46. require('../../util/codemirror/autorefresh.ext');
  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.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 (Number.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 (Number.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. const scriptList = [];
  282. const 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. // eslint-disable-next-line no-lonely-if
  374. if (hasCustomClass) {
  375. additionalClassSet.delete(autoformatTableClass);
  376. this.setState({ additionalClassSet });
  377. }
  378. }
  379. }
  380. changeHandler(editor, data, value) {
  381. if (this.props.onChange != null) {
  382. this.props.onChange(value);
  383. }
  384. this.updateCheatsheetStates(null, value);
  385. // Emoji AutoComplete
  386. if (this.state.isEnabledEmojiAutoComplete) {
  387. this.emojiAutoCompleteHelper.showHint(editor);
  388. }
  389. }
  390. /**
  391. * CodeMirror paste event handler
  392. * see: https://codemirror.net/doc/manual.html#events
  393. * @param {any} editor An editor instance of CodeMirror
  394. * @param {any} event
  395. */
  396. pasteHandler(editor, event) {
  397. const types = event.clipboardData.types;
  398. // files
  399. if (types.includes('Files')) {
  400. event.preventDefault();
  401. this.dispatchPasteFiles(event);
  402. }
  403. // text
  404. else if (types.includes('text/plain')) {
  405. pasteHelper.pasteText(this, event);
  406. }
  407. }
  408. /**
  409. * update states which related to cheatsheet
  410. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  411. * @param {string} valueTmp (get value from codemirror if null is set)
  412. */
  413. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  414. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  415. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  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. ? (
  431. <div className="overlay overlay-loading-keymap">
  432. <span style={style} className="overlay-content">
  433. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  434. </span>
  435. </div>
  436. )
  437. : '';
  438. }
  439. renderSimpleCheatsheet() {
  440. return <SimpleCheatsheet />;
  441. }
  442. renderCheatsheetModalBody() {
  443. return <Cheatsheet />;
  444. }
  445. renderCheatsheetModalButton() {
  446. const showCheatsheetModal = () => {
  447. this.setState({ isCheatsheetModalShown: true });
  448. };
  449. const hideCheatsheetModal = () => {
  450. this.setState({ isCheatsheetModalShown: false });
  451. };
  452. return (
  453. <React.Fragment>
  454. <Modal className="modal-gfm-cheatsheet" show={this.state.isCheatsheetModalShown} onHide={() => { hideCheatsheetModal() }}>
  455. <Modal.Header closeButton>
  456. <Modal.Title><i className="icon-fw icon-question" />Markdown Help</Modal.Title>
  457. </Modal.Header>
  458. <Modal.Body className="pt-1">
  459. { this.renderCheatsheetModalBody() }
  460. </Modal.Body>
  461. </Modal>
  462. <button type="button" className="btn-link gfm-cheatsheet-modal-link text-muted small mr-3" onClick={() => { showCheatsheetModal() }}>
  463. <i className="icon-question" /> Markdown
  464. </button>
  465. </React.Fragment>
  466. );
  467. }
  468. /**
  469. * return a function to replace a selected range with prefix + selection + suffix
  470. *
  471. * The cursor after replacing is inserted between the selection and the suffix.
  472. */
  473. createReplaceSelectionHandler(prefix, suffix) {
  474. return () => {
  475. const cm = this.getCodeMirror();
  476. const selection = cm.getDoc().getSelection();
  477. const curStartPos = cm.getCursor('from');
  478. const curEndPos = cm.getCursor('to');
  479. const curPosAfterReplacing = {};
  480. curPosAfterReplacing.line = curEndPos.line;
  481. if (curStartPos.line === curEndPos.line) {
  482. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  483. }
  484. else {
  485. curPosAfterReplacing.ch = curEndPos.ch;
  486. }
  487. cm.getDoc().replaceSelection(prefix + selection + suffix);
  488. cm.setCursor(curPosAfterReplacing);
  489. cm.focus();
  490. };
  491. }
  492. /**
  493. * return a function to add prefix to selected each lines
  494. *
  495. * The cursor after editing is inserted between the end of the selection.
  496. */
  497. createAddPrefixToEachLinesHandler(prefix) {
  498. return () => {
  499. const cm = this.getCodeMirror();
  500. const startLineNum = cm.getCursor('from').line;
  501. const endLineNum = cm.getCursor('to').line;
  502. const lines = [];
  503. for (let i = startLineNum; i <= endLineNum; i++) {
  504. lines.push(prefix + cm.getDoc().getLine(i));
  505. }
  506. const replacement = `${lines.join('\n')}\n`;
  507. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  508. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  509. cm.focus();
  510. };
  511. }
  512. /**
  513. * make a selected line a header
  514. *
  515. * The cursor after editing is inserted between the end of the line.
  516. */
  517. makeHeaderHandler() {
  518. const cm = this.getCodeMirror();
  519. const lineNum = cm.getCursor('from').line;
  520. const line = cm.getDoc().getLine(lineNum);
  521. let prefix = '#';
  522. if (!line.startsWith('#')) {
  523. prefix += ' ';
  524. }
  525. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  526. cm.focus();
  527. }
  528. showHandsonTableHandler() {
  529. this.handsontableModal.show(mtu.getMarkdownTable(this.getCodeMirror()));
  530. }
  531. getNavbarItems() {
  532. // The following styles will be removed after creating icons for the editor navigation bar.
  533. const paddingTopBottom54 = { paddingTop: '6px', paddingBottom: '5px' };
  534. const paddingBottom6 = { paddingBottom: '7px' };
  535. const fontSize18 = { fontSize: '18px' };
  536. return [
  537. <Button
  538. key="nav-item-bold"
  539. bsSize="small"
  540. title="Bold"
  541. onClick={this.createReplaceSelectionHandler('**', '**')}
  542. >
  543. <i className="fa fa-bold"></i>
  544. </Button>,
  545. <Button
  546. key="nav-item-italic"
  547. bsSize="small"
  548. title="Italic"
  549. onClick={this.createReplaceSelectionHandler('*', '*')}
  550. >
  551. <i className="fa fa-italic"></i>
  552. </Button>,
  553. <Button
  554. key="nav-item-strikethough"
  555. bsSize="small"
  556. title="Strikethrough"
  557. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  558. >
  559. <i className="fa fa-strikethrough"></i>
  560. </Button>,
  561. <Button
  562. key="nav-item-header"
  563. bsSize="small"
  564. title="Heading"
  565. onClick={this.makeHeaderHandler}
  566. >
  567. <i className="fa fa-header"></i>
  568. </Button>,
  569. <Button
  570. key="nav-item-code"
  571. bsSize="small"
  572. title="Inline Code"
  573. onClick={this.createReplaceSelectionHandler('`', '`')}
  574. >
  575. <i className="fa fa-code"></i>
  576. </Button>,
  577. <Button
  578. key="nav-item-quote"
  579. bsSize="small"
  580. title="Quote"
  581. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  582. style={paddingBottom6}
  583. >
  584. <i className="ti-quote-right"></i>
  585. </Button>,
  586. <Button
  587. key="nav-item-ul"
  588. bsSize="small"
  589. title="List"
  590. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  591. style={paddingTopBottom54}
  592. >
  593. <i className="ti-list" style={fontSize18}></i>
  594. </Button>,
  595. <Button
  596. key="nav-item-ol"
  597. bsSize="small"
  598. title="Numbered List"
  599. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  600. style={paddingTopBottom54}
  601. >
  602. <i className="ti-list-ol" style={fontSize18}></i>
  603. </Button>,
  604. <Button
  605. key="nav-item-checkbox"
  606. bsSize="small"
  607. title="Check List"
  608. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  609. style={paddingBottom6}
  610. >
  611. <i className="ti-check-box"></i>
  612. </Button>,
  613. <Button
  614. key="nav-item-link"
  615. bsSize="small"
  616. title="Link"
  617. onClick={this.createReplaceSelectionHandler('[', ']()')}
  618. style={paddingBottom6}
  619. >
  620. <i className="icon-link"></i>
  621. </Button>,
  622. <Button
  623. key="nav-item-image"
  624. bsSize="small"
  625. title="Image"
  626. onClick={this.createReplaceSelectionHandler('![', ']()')}
  627. style={paddingBottom6}
  628. >
  629. <i className="icon-picture"></i>
  630. </Button>,
  631. <Button
  632. key="nav-item-table"
  633. bsSize="small"
  634. title="Table"
  635. onClick={this.showHandsonTableHandler}
  636. >
  637. <img src="/images/icons/editor/table.svg" alt="icon-table" width="14" height="14" />
  638. </Button>,
  639. ];
  640. }
  641. render() {
  642. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  643. const defaultEditorOptions = {
  644. theme: 'elegant',
  645. lineNumbers: true,
  646. };
  647. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  648. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  649. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  650. return (
  651. <React.Fragment>
  652. <ReactCodeMirror
  653. ref={(c) => { this.cm = c }}
  654. className={additionalClasses}
  655. placeholder="search"
  656. editorDidMount={(editor) => {
  657. // add event handlers
  658. editor.on('paste', this.pasteHandler);
  659. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  660. }}
  661. value={this.state.value}
  662. options={{
  663. mode,
  664. theme: editorOptions.theme,
  665. styleActiveLine: editorOptions.styleActiveLine,
  666. lineNumbers: this.props.lineNumbers,
  667. tabSize: 4,
  668. indentUnit: 4,
  669. lineWrapping: true,
  670. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  671. autoCloseTags: true,
  672. placeholder,
  673. matchBrackets: true,
  674. matchTags: { bothTags: true },
  675. // folding
  676. foldGutter: this.props.lineNumbers,
  677. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  678. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  679. highlightSelectionMatches: { annotateScrollbar: true },
  680. // markdown mode options
  681. highlightFormatting: true,
  682. // continuelist, indentlist
  683. extraKeys: {
  684. Enter: this.handleEnterKey,
  685. 'Ctrl-Enter': this.handleCtrlEnterKey,
  686. 'Cmd-Enter': this.handleCtrlEnterKey,
  687. Tab: 'indentMore',
  688. 'Shift-Tab': 'indentLess',
  689. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  690. },
  691. }}
  692. onCursor={this.cursorHandler}
  693. onScroll={(editor, data) => {
  694. if (this.props.onScroll != null) {
  695. // add line data
  696. const line = editor.lineAtHeight(data.top, 'local');
  697. data.line = line;
  698. this.props.onScroll(data);
  699. }
  700. }}
  701. onChange={this.changeHandler}
  702. onDragEnter={(editor, event) => {
  703. if (this.props.onDragEnter != null) {
  704. this.props.onDragEnter(event);
  705. }
  706. }}
  707. />
  708. { this.renderLoadingKeymapOverlay() }
  709. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3 pt-3">
  710. { this.state.isSimpleCheatsheetShown && this.renderSimpleCheatsheet() }
  711. { this.state.isCheatsheetModalButtonShown && this.renderCheatsheetModalButton() }
  712. </div>
  713. <HandsontableModal
  714. ref={(c) => { this.handsontableModal = c }}
  715. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  716. />
  717. </React.Fragment>
  718. );
  719. }
  720. }
  721. CodeMirrorEditor.propTypes = Object.assign({
  722. emojiStrategy: PropTypes.object,
  723. lineNumbers: PropTypes.bool,
  724. }, AbstractEditor.propTypes);
  725. CodeMirrorEditor.defaultProps = {
  726. lineNumbers: true,
  727. };