CodeMirrorEditor.jsx 29 KB

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