CodeMirrorEditor.jsx 35 KB

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