CodeMirrorEditor.jsx 26 KB

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