CodeMirrorEditor.jsx 25 KB

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