CodeMirrorEditor.jsx 28 KB

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