CodeMirrorEditor.jsx 29 KB

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