CodeMirrorEditor.jsx 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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 CodeMirrorEditorFc = React.forwardRef((props, ref) => {
  1036. const { open: openDrawioModal } = useDrawioModal();
  1037. const { open: openHandsontableModal } = useHandsontableModal();
  1038. const openDrawioModalHandler = useCallback((drawioMxFile, onSave) => {
  1039. openDrawioModal(drawioMxFile, onSave);
  1040. }, [openDrawioModal]);
  1041. const openTableModalHandler = useCallback((markdownTable, editor, autoFormatMarkdownTable) => {
  1042. openHandsontableModal(markdownTable, editor, autoFormatMarkdownTable);
  1043. }, [openHandsontableModal]);
  1044. return (
  1045. <CodeMirrorEditor
  1046. ref={ref}
  1047. onClickDrawioBtn={openDrawioModalHandler}
  1048. onClickTableBtn={openTableModalHandler}
  1049. {...props}
  1050. />
  1051. );
  1052. });
  1053. CodeMirrorEditorFc.displayName = 'CodeMirrorEditorFc';
  1054. export default memo(CodeMirrorEditorFc);