CodeMirrorEditor.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. return [
  533. <Button
  534. key="nav-item-bold"
  535. bsSize="small"
  536. title="Bold"
  537. onClick={this.createReplaceSelectionHandler('**', '**')}
  538. >
  539. <img src="/images/icons/editor/bold.svg" alt="icon-bold" height="13" />
  540. </Button>,
  541. <Button
  542. key="nav-item-italic"
  543. bsSize="small"
  544. title="Italic"
  545. onClick={this.createReplaceSelectionHandler('*', '*')}
  546. >
  547. <img src="/images/icons/editor/italic.svg" alt="icon-italic" height="13" />
  548. </Button>,
  549. <Button
  550. key="nav-item-strikethrough"
  551. bsSize="small"
  552. title="Strikethrough"
  553. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  554. >
  555. <img src="/images/icons/editor/strikethrough.svg" alt="icon-strikethrough" height="13" />
  556. </Button>,
  557. <Button
  558. key="nav-item-header"
  559. bsSize="small"
  560. title="Heading"
  561. onClick={this.makeHeaderHandler}
  562. >
  563. <img src="/images/icons/editor/header.svg" alt="icon-header" height="13" />
  564. </Button>,
  565. <Button
  566. key="nav-item-code"
  567. bsSize="small"
  568. title="Inline Code"
  569. onClick={this.createReplaceSelectionHandler('`', '`')}
  570. >
  571. <img src="/images/icons/editor/code.svg" alt="icon-code" height="13" />
  572. </Button>,
  573. <Button
  574. key="nav-item-quote"
  575. bsSize="small"
  576. title="Quote"
  577. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  578. >
  579. <img src="/images/icons/editor/quote.svg" alt="icon-quote" height="13" />
  580. </Button>,
  581. <Button
  582. key="nav-item-ul"
  583. bsSize="small"
  584. title="List"
  585. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  586. >
  587. <img src="/images/icons/editor/list-ul.svg" alt="icon-list-ul" height="13" />
  588. </Button>,
  589. <Button
  590. key="nav-item-ol"
  591. bsSize="small"
  592. title="Numbered List"
  593. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  594. >
  595. <img src="/images/icons/editor/list-ol.svg" alt="icon-list-ol" height="13" />
  596. </Button>,
  597. <Button
  598. key="nav-item-checkbox"
  599. bsSize="small"
  600. title="Check List"
  601. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  602. >
  603. <img src="/images/icons/editor/check.svg" alt="icon-check" height="13" />
  604. </Button>,
  605. <Button
  606. key="nav-item-link"
  607. bsSize="small"
  608. title="Link"
  609. onClick={this.createReplaceSelectionHandler('[', ']()')}
  610. >
  611. <img src="/images/icons/editor/link.svg" alt="icon-link" height="13" />
  612. </Button>,
  613. <Button
  614. key="nav-item-image"
  615. bsSize="small"
  616. title="Image"
  617. onClick={this.createReplaceSelectionHandler('![', ']()')}
  618. >
  619. <img src="/images/icons/editor/picture.svg" alt="icon-picture" height="13" />
  620. </Button>,
  621. <Button
  622. key="nav-item-table"
  623. bsSize="small"
  624. title="Table"
  625. onClick={this.showHandsonTableHandler}
  626. >
  627. <img src="/images/icons/editor/table.svg" alt="icon-table" height="13" />
  628. </Button>,
  629. ];
  630. }
  631. render() {
  632. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  633. const defaultEditorOptions = {
  634. theme: 'elegant',
  635. lineNumbers: true,
  636. };
  637. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  638. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  639. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  640. return (
  641. <React.Fragment>
  642. <ReactCodeMirror
  643. ref={(c) => { this.cm = c }}
  644. className={additionalClasses}
  645. placeholder="search"
  646. editorDidMount={(editor) => {
  647. // add event handlers
  648. editor.on('paste', this.pasteHandler);
  649. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  650. }}
  651. value={this.state.value}
  652. options={{
  653. mode,
  654. theme: editorOptions.theme,
  655. styleActiveLine: editorOptions.styleActiveLine,
  656. lineNumbers: this.props.lineNumbers,
  657. tabSize: 4,
  658. indentUnit: 4,
  659. lineWrapping: true,
  660. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  661. autoCloseTags: true,
  662. placeholder,
  663. matchBrackets: true,
  664. matchTags: { bothTags: true },
  665. // folding
  666. foldGutter: this.props.lineNumbers,
  667. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  668. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  669. highlightSelectionMatches: { annotateScrollbar: true },
  670. // markdown mode options
  671. highlightFormatting: true,
  672. // continuelist, indentlist
  673. extraKeys: {
  674. Enter: this.handleEnterKey,
  675. 'Ctrl-Enter': this.handleCtrlEnterKey,
  676. 'Cmd-Enter': this.handleCtrlEnterKey,
  677. Tab: 'indentMore',
  678. 'Shift-Tab': 'indentLess',
  679. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  680. },
  681. }}
  682. onCursor={this.cursorHandler}
  683. onScroll={(editor, data) => {
  684. if (this.props.onScroll != null) {
  685. // add line data
  686. const line = editor.lineAtHeight(data.top, 'local');
  687. data.line = line;
  688. this.props.onScroll(data);
  689. }
  690. }}
  691. onChange={this.changeHandler}
  692. onDragEnter={(editor, event) => {
  693. if (this.props.onDragEnter != null) {
  694. this.props.onDragEnter(event);
  695. }
  696. }}
  697. />
  698. { this.renderLoadingKeymapOverlay() }
  699. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3 pt-3">
  700. { this.state.isSimpleCheatsheetShown && this.renderSimpleCheatsheet() }
  701. { this.state.isCheatsheetModalButtonShown && this.renderCheatsheetModalButton() }
  702. </div>
  703. <HandsontableModal
  704. ref={(c) => { this.handsontableModal = c }}
  705. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  706. />
  707. </React.Fragment>
  708. );
  709. }
  710. }
  711. CodeMirrorEditor.propTypes = Object.assign({
  712. emojiStrategy: PropTypes.object,
  713. lineNumbers: PropTypes.bool,
  714. }, AbstractEditor.propTypes);
  715. CodeMirrorEditor.defaultProps = {
  716. lineNumbers: true,
  717. };