CodeMirrorEditor.jsx 29 KB

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