CodeMirrorEditor.jsx 35 KB

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