CodeMirrorEditor.jsx 29 KB

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