CodeMirrorEditor.jsx 26 KB

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