CodeMirrorEditor.jsx 25 KB

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