CodeMirrorEditor.jsx 26 KB

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