CodeMirrorEditor.jsx 35 KB

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