CodeMirrorEditor.jsx 31 KB

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