CodeMirrorEditor.jsx 26 KB

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