CodeMirrorEditor.jsx 25 KB

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