CodeMirrorEditor.jsx 24 KB

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