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