CodeMirrorEditor.jsx 34 KB

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