CodeMirrorEditor.jsx 25 KB

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