CodeMirrorEditor.jsx 25 KB

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