CodeMirrorEditor.jsx 35 KB

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