CodeMirrorEditor.jsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. };
  380. const interceptorManager = this.interceptorManager;
  381. interceptorManager.process('preHandleEnter', context)
  382. .then(() => {
  383. if (context.handlers.length === 0) {
  384. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  385. }
  386. });
  387. }
  388. /**
  389. * handle Ctrl+ENTER key
  390. */
  391. handleCtrlEnterKey() {
  392. if (this.props.onCtrlEnter != null) {
  393. this.props.onCtrlEnter();
  394. }
  395. }
  396. scrollCursorIntoViewHandler(editor, event) {
  397. if (this.props.onScrollCursorIntoView != null) {
  398. const line = editor.getCursor().line;
  399. this.props.onScrollCursorIntoView(line);
  400. }
  401. }
  402. cursorHandler(editor, event) {
  403. const { additionalClassSet } = this.state;
  404. const hasCustomClass = additionalClassSet.has(MARKDOWN_TABLE_ACTIVATED_CLASS);
  405. const hasLinkClass = additionalClassSet.has(MARKDOWN_LINK_ACTIVATED_CLASS);
  406. const isInTable = mtu.isInTable(editor);
  407. const isInLink = mlu.isInLink(editor);
  408. if (!hasCustomClass && isInTable) {
  409. additionalClassSet.add(MARKDOWN_TABLE_ACTIVATED_CLASS);
  410. this.setState({ additionalClassSet });
  411. }
  412. if (hasCustomClass && !isInTable) {
  413. additionalClassSet.delete(MARKDOWN_TABLE_ACTIVATED_CLASS);
  414. this.setState({ additionalClassSet });
  415. }
  416. if (!hasLinkClass && isInLink) {
  417. additionalClassSet.add(MARKDOWN_LINK_ACTIVATED_CLASS);
  418. this.setState({ additionalClassSet });
  419. }
  420. if (hasLinkClass && !isInLink) {
  421. additionalClassSet.delete(MARKDOWN_LINK_ACTIVATED_CLASS);
  422. this.setState({ additionalClassSet });
  423. }
  424. }
  425. changeHandler(editor, data, value) {
  426. if (this.props.onChange != null) {
  427. this.props.onChange(value);
  428. }
  429. this.updateCheatsheetStates(null, value);
  430. // Emoji AutoComplete
  431. if (this.state.isEnabledEmojiAutoComplete) {
  432. this.emojiAutoCompleteHelper.showHint(editor);
  433. }
  434. }
  435. /**
  436. * CodeMirror paste event handler
  437. * see: https://codemirror.net/doc/manual.html#events
  438. * @param {any} editor An editor instance of CodeMirror
  439. * @param {any} event
  440. */
  441. pasteHandler(editor, event) {
  442. const types = event.clipboardData.types;
  443. // files
  444. if (types.includes('Files')) {
  445. event.preventDefault();
  446. this.dispatchPasteFiles(event);
  447. }
  448. // text
  449. else if (types.includes('text/plain')) {
  450. pasteHelper.pasteText(this, event);
  451. }
  452. }
  453. /**
  454. * update states which related to cheatsheet
  455. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  456. * @param {string} valueTmp (get value from codemirror if null is set)
  457. */
  458. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  459. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  460. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  461. // update isSimpleCheatsheetShown
  462. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  463. this.setState({ isSimpleCheatsheetShown });
  464. }
  465. markdownHelpButtonClickedHandler() {
  466. if (this.props.onMarkdownHelpButtonClicked != null) {
  467. this.props.onMarkdownHelpButtonClicked();
  468. }
  469. }
  470. renderLoadingKeymapOverlay() {
  471. // centering
  472. const style = {
  473. top: 0,
  474. right: 0,
  475. bottom: 0,
  476. left: 0,
  477. };
  478. return this.state.isLoadingKeymap
  479. ? (
  480. <div className="overlay overlay-loading-keymap">
  481. <span style={style} className="overlay-content">
  482. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  483. </span>
  484. </div>
  485. )
  486. : '';
  487. }
  488. renderCheatsheetModalButton() {
  489. return (
  490. <button type="button" className="btn-link gfm-cheatsheet-modal-link small" onClick={() => { this.markdownHelpButtonClickedHandler() }}>
  491. <i className="icon-question" /> Markdown
  492. </button>
  493. );
  494. }
  495. renderCheatsheetOverlay() {
  496. const cheatsheetModalButton = this.renderCheatsheetModalButton();
  497. return (
  498. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3">
  499. { this.state.isSimpleCheatsheetShown
  500. ? (
  501. <div className="text-right">
  502. {cheatsheetModalButton}
  503. <div className="mb-2 d-none d-md-block">
  504. <SimpleCheatsheet />
  505. </div>
  506. </div>
  507. )
  508. : (
  509. <div className="mr-4 mb-2">
  510. {cheatsheetModalButton}
  511. </div>
  512. )
  513. }
  514. </div>
  515. );
  516. }
  517. /**
  518. * return a function to replace a selected range with prefix + selection + suffix
  519. *
  520. * The cursor after replacing is inserted between the selection and the suffix.
  521. */
  522. createReplaceSelectionHandler(prefix, suffix) {
  523. return () => {
  524. const cm = this.getCodeMirror();
  525. const selection = cm.getDoc().getSelection();
  526. const curStartPos = cm.getCursor('from');
  527. const curEndPos = cm.getCursor('to');
  528. const curPosAfterReplacing = {};
  529. curPosAfterReplacing.line = curEndPos.line;
  530. if (curStartPos.line === curEndPos.line) {
  531. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  532. }
  533. else {
  534. curPosAfterReplacing.ch = curEndPos.ch;
  535. }
  536. cm.getDoc().replaceSelection(prefix + selection + suffix);
  537. cm.setCursor(curPosAfterReplacing);
  538. cm.focus();
  539. };
  540. }
  541. /**
  542. * return a function to add prefix to selected each lines
  543. *
  544. * The cursor after editing is inserted between the end of the selection.
  545. */
  546. createAddPrefixToEachLinesHandler(prefix) {
  547. return () => {
  548. const cm = this.getCodeMirror();
  549. const startLineNum = cm.getCursor('from').line;
  550. const endLineNum = cm.getCursor('to').line;
  551. const lines = [];
  552. for (let i = startLineNum; i <= endLineNum; i++) {
  553. lines.push(prefix + cm.getDoc().getLine(i));
  554. }
  555. const replacement = `${lines.join('\n')}\n`;
  556. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  557. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  558. cm.focus();
  559. };
  560. }
  561. /**
  562. * make a selected line a header
  563. *
  564. * The cursor after editing is inserted between the end of the line.
  565. */
  566. makeHeaderHandler() {
  567. const cm = this.getCodeMirror();
  568. const lineNum = cm.getCursor('from').line;
  569. const line = cm.getDoc().getLine(lineNum);
  570. let prefix = '#';
  571. if (!line.startsWith('#')) {
  572. prefix += ' ';
  573. }
  574. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  575. cm.focus();
  576. }
  577. showGridEditorHandler() {
  578. this.gridEditModal.current.show(geu.getGridHtml(this.getCodeMirror()));
  579. }
  580. showLinkEditHandler() {
  581. this.linkEditModal.current.show(mlu.getMarkdownLink(this.getCodeMirror()));
  582. }
  583. showHandsonTableHandler() {
  584. this.handsontableModal.current.show(mtu.getMarkdownTable(this.getCodeMirror()));
  585. }
  586. showDrawioHandler() {
  587. this.drawioModal.current.show(mdu.getMarkdownDrawioMxfile(this.getCodeMirror()));
  588. }
  589. getNavbarItems() {
  590. return [
  591. <Button
  592. key="nav-item-bold"
  593. color={null}
  594. size="sm"
  595. title="Bold"
  596. onClick={this.createReplaceSelectionHandler('**', '**')}
  597. >
  598. <EditorIcon icon="Bold" />
  599. </Button>,
  600. <Button
  601. key="nav-item-italic"
  602. color={null}
  603. size="sm"
  604. title="Italic"
  605. onClick={this.createReplaceSelectionHandler('*', '*')}
  606. >
  607. <EditorIcon icon="Italic" />
  608. </Button>,
  609. <Button
  610. key="nav-item-strikethrough"
  611. color={null}
  612. size="sm"
  613. title="Strikethrough"
  614. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  615. >
  616. <EditorIcon icon="Strikethrough" />
  617. </Button>,
  618. <Button
  619. key="nav-item-header"
  620. color={null}
  621. size="sm"
  622. title="Heading"
  623. onClick={this.makeHeaderHandler}
  624. >
  625. <EditorIcon icon="Heading" />
  626. </Button>,
  627. <Button
  628. key="nav-item-code"
  629. color={null}
  630. size="sm"
  631. title="Inline Code"
  632. onClick={this.createReplaceSelectionHandler('`', '`')}
  633. >
  634. <EditorIcon icon="InlineCode" />
  635. </Button>,
  636. <Button
  637. key="nav-item-quote"
  638. color={null}
  639. size="sm"
  640. title="Quote"
  641. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  642. >
  643. <EditorIcon icon="Quote" />
  644. </Button>,
  645. <Button
  646. key="nav-item-ul"
  647. color={null}
  648. size="sm"
  649. title="List"
  650. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  651. >
  652. <EditorIcon icon="List" />
  653. </Button>,
  654. <Button
  655. key="nav-item-ol"
  656. color={null}
  657. size="sm"
  658. title="Numbered List"
  659. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  660. >
  661. <EditorIcon icon="NumberedList" />
  662. </Button>,
  663. <Button
  664. key="nav-item-checkbox"
  665. color={null}
  666. size="sm"
  667. title="Check List"
  668. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  669. >
  670. <EditorIcon icon="CheckList" />
  671. </Button>,
  672. <Button
  673. key="nav-item-link"
  674. color={null}
  675. size="sm"
  676. title="Link"
  677. onClick={this.showLinkEditHandler}
  678. >
  679. <EditorIcon icon="Link" />
  680. </Button>,
  681. <Button
  682. key="nav-item-image"
  683. color={null}
  684. size="sm"
  685. title="Image"
  686. onClick={this.createReplaceSelectionHandler('![', ']()')}
  687. >
  688. <EditorIcon icon="Image" />
  689. </Button>,
  690. <Button
  691. key="nav-item-grid"
  692. color={null}
  693. size="sm"
  694. title="Grid"
  695. onClick={this.showGridEditorHandler}
  696. >
  697. <EditorIcon icon="Grid" />
  698. </Button>,
  699. <Button
  700. key="nav-item-table"
  701. color={null}
  702. size="sm"
  703. title="Table"
  704. onClick={this.showHandsonTableHandler}
  705. >
  706. <EditorIcon icon="Table" />
  707. </Button>,
  708. <Button
  709. key="nav-item-drawio"
  710. color={null}
  711. bssize="small"
  712. title="draw.io"
  713. onClick={this.showDrawioHandler}
  714. >
  715. <EditorIcon icon="Drawio" />
  716. </Button>,
  717. ];
  718. }
  719. render() {
  720. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  721. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  722. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plane Text..';
  723. return (
  724. <React.Fragment>
  725. <ReactCodeMirror
  726. ref={(c) => { this.cm = c }}
  727. className={additionalClasses}
  728. placeholder="search"
  729. editorDidMount={(editor) => {
  730. // add event handlers
  731. editor.on('paste', this.pasteHandler);
  732. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  733. }}
  734. value={this.state.value}
  735. options={{
  736. mode,
  737. theme: this.props.editorOptions.theme,
  738. styleActiveLine: this.props.editorOptions.styleActiveLine,
  739. lineNumbers: this.props.lineNumbers,
  740. tabSize: 4,
  741. indentUnit: 4,
  742. lineWrapping: true,
  743. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  744. autoCloseTags: true,
  745. placeholder,
  746. matchBrackets: true,
  747. matchTags: { bothTags: true },
  748. // folding
  749. foldGutter: this.props.lineNumbers,
  750. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  751. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  752. highlightSelectionMatches: { annotateScrollbar: true },
  753. // markdown mode options
  754. highlightFormatting: true,
  755. // continuelist, indentlist
  756. extraKeys: {
  757. Enter: this.handleEnterKey,
  758. 'Ctrl-Enter': this.handleCtrlEnterKey,
  759. 'Cmd-Enter': this.handleCtrlEnterKey,
  760. Tab: 'indentMore',
  761. 'Shift-Tab': 'indentLess',
  762. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  763. },
  764. }}
  765. onCursor={this.cursorHandler}
  766. onScroll={(editor, data) => {
  767. if (this.props.onScroll != null) {
  768. // add line data
  769. const line = editor.lineAtHeight(data.top, 'local');
  770. data.line = line;
  771. this.props.onScroll(data);
  772. }
  773. }}
  774. onChange={this.changeHandler}
  775. onDragEnter={(editor, event) => {
  776. if (this.props.onDragEnter != null) {
  777. this.props.onDragEnter(event);
  778. }
  779. }}
  780. />
  781. { this.renderLoadingKeymapOverlay() }
  782. { this.renderCheatsheetOverlay() }
  783. <GridEditModal
  784. ref={this.gridEditModal}
  785. onSave={(grid) => { return geu.replaceGridWithHtmlWithEditor(this.getCodeMirror(), grid) }}
  786. />
  787. <LinkEditModal
  788. ref={this.linkEditModal}
  789. onSave={(link) => { return mlu.replaceFocusedMarkdownLinkWithEditor(this.getCodeMirror(), link) }}
  790. />
  791. <HandsontableModal
  792. ref={this.handsontableModal}
  793. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  794. />
  795. <DrawioModal
  796. ref={this.drawioModal}
  797. onSave={(drawioData) => { return mdu.replaceFocusedDrawioWithEditor(this.getCodeMirror(), drawioData) }}
  798. />
  799. </React.Fragment>
  800. );
  801. }
  802. }
  803. CodeMirrorEditor.propTypes = Object.assign({
  804. editorOptions: PropTypes.object.isRequired,
  805. emojiStrategy: PropTypes.object,
  806. lineNumbers: PropTypes.bool,
  807. onMarkdownHelpButtonClicked: PropTypes.func,
  808. }, AbstractEditor.propTypes);
  809. CodeMirrorEditor.defaultProps = {
  810. lineNumbers: true,
  811. };