CodeMirrorEditor.jsx 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. import React, { useCallback, memo } from 'react';
  2. import { createValidator } from '@growi/codemirror-textlint';
  3. import { commands } from 'codemirror';
  4. import { JSHINT } from 'jshint';
  5. import * as loadCssSync from 'load-css-file';
  6. import PropTypes from 'prop-types';
  7. import { Button } from 'reactstrap';
  8. import * as loadScript from 'simple-load-script';
  9. import { throttle, debounce } from 'throttle-debounce';
  10. import urljoin from 'url-join';
  11. import InterceptorManager from '~/services/interceptor-manager';
  12. import { useHandsontableModal, useDrawioModal, useTemplateModal } from '~/stores/modal';
  13. import loggerFactory from '~/utils/logger';
  14. import { UncontrolledCodeMirror } from '../UncontrolledCodeMirror';
  15. import AbstractEditor from './AbstractEditor';
  16. import CommentMentionHelper from './CommentMentionHelper';
  17. import EditorIcon from './EditorIcon';
  18. import EmojiPicker from './EmojiPicker';
  19. import EmojiPickerHelper from './EmojiPickerHelper';
  20. import GridEditModal from './GridEditModal';
  21. // TODO: re-impl with https://redmine.weseek.co.jp/issues/107248
  22. // import geu from './GridEditorUtil';
  23. import LinkEditModal from './LinkEditModal';
  24. import mdu from './MarkdownDrawioUtil';
  25. import markdownLinkUtil from './MarkdownLinkUtil';
  26. import markdownListUtil from './MarkdownListUtil';
  27. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  28. import mtu from './MarkdownTableUtil';
  29. import pasteHelper from './PasteHelper';
  30. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  31. import SimpleCheatsheet from './SimpleCheatsheet';
  32. import styles from './CodeMirrorEditor.module.scss';
  33. // Textlint
  34. window.JSHINT = JSHINT;
  35. window.kuromojin = { dicPath: '/static/dict' };
  36. require('codemirror/addon/hint/show-hint.css'); // Import from CodeMirrorEditor.module.scss not working
  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. isTemplateModalOpened: false,
  102. };
  103. this.cm = React.createRef();
  104. this.gridEditModal = React.createRef();
  105. this.linkEditModal = React.createRef();
  106. this.drawioModal = React.createRef();
  107. this.init();
  108. this.getCodeMirror = this.getCodeMirror.bind(this);
  109. this.getBol = this.getBol.bind(this);
  110. this.getEol = this.getEol.bind(this);
  111. this.loadTheme = this.loadTheme.bind(this);
  112. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  113. this.setKeymapMode = this.setKeymapMode.bind(this);
  114. this.handleEnterKey = this.handleEnterKey.bind(this);
  115. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  116. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  117. this.scrollCursorIntoViewHandlerThrottled = throttle(500, this.scrollCursorIntoViewHandler);
  118. this.pasteHandler = this.pasteHandler.bind(this);
  119. this.cursorHandler = this.cursorHandler.bind(this);
  120. this.cursorHandlerDebounced = debounce(200, throttle(500, this.cursorHandler));
  121. this.changeHandler = this.changeHandler.bind(this);
  122. this.turnOnEmojiPickerMode = this.turnOnEmojiPickerMode.bind(this);
  123. this.turnOffEmojiPickerMode = this.turnOffEmojiPickerMode.bind(this);
  124. this.windowClickHandler = this.windowClickHandler.bind(this);
  125. this.keyDownHandler = this.keyDownHandler.bind(this);
  126. this.keyDownHandlerForEmojiPicker = this.keyDownHandlerForEmojiPicker.bind(this);
  127. this.keyDownHandlerForEmojiPickerThrottled = throttle(400, this.keyDownHandlerForEmojiPicker);
  128. this.showEmojiPicker = this.showEmojiPicker.bind(this);
  129. this.keyPressHandlerForEmojiPicker = this.keyPressHandlerForEmojiPicker.bind(this);
  130. this.keyPressHandlerForEmojiPickerThrottled = debounce(50, throttle(200, this.keyPressHandlerForEmojiPicker));
  131. this.keyPressHandler = this.keyPressHandler.bind(this);
  132. this.updateCheatsheetStates = this.updateCheatsheetStates.bind(this);
  133. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  134. this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
  135. this.makeHeaderHandler = this.makeHeaderHandler.bind(this);
  136. // TODO: re-impl with https://redmine.weseek.co.jp/issues/107248
  137. // this.showGridEditorHandler = this.showGridEditorHandler.bind(this);
  138. this.showLinkEditHandler = this.showLinkEditHandler.bind(this);
  139. this.foldDrawioSection = this.foldDrawioSection.bind(this);
  140. this.clickDrawioIconHandler = this.clickDrawioIconHandler.bind(this);
  141. this.clickTableIconHandler = this.clickTableIconHandler.bind(this);
  142. this.showTemplateModal = this.showTemplateModal.bind(this);
  143. }
  144. init() {
  145. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.42.0';
  146. this.cmNoCdnScriptRoot = '/static/js/cdn';
  147. this.cmNoCdnStyleRoot = '/static/styles/cdn';
  148. this.interceptorManager = new InterceptorManager();
  149. this.interceptorManager.addInterceptors([
  150. new PreventMarkdownListInterceptor(),
  151. new MarkdownTableInterceptor(),
  152. ]);
  153. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  154. this.loadedKeymapSet = new Set();
  155. }
  156. componentDidMount() {
  157. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  158. this.getCodeMirror().codeMirrorEditor = this;
  159. // mark clean
  160. this.getCodeMirror().getDoc().markClean();
  161. // fold drawio section
  162. this.foldDrawioSection();
  163. // initialize commentMentionHelper if comment editor is opened
  164. if (this.props.isComment) {
  165. this.commentMentionHelper = new CommentMentionHelper(this.getCodeMirror());
  166. }
  167. this.emojiPickerHelper = new EmojiPickerHelper(this.getCodeMirror());
  168. // HACKME: Find a better way to handle onClick for Editor
  169. document.addEventListener('click', this.windowClickHandler);
  170. }
  171. componentWillUnmount() {
  172. // HACKME: Find a better way to handle onClick for Editor
  173. document.removeEventListener('click', this.windowClickHandler);
  174. }
  175. componentWillReceiveProps(nextProps) {
  176. this.initializeEditorSettings(nextProps.editorSettings);
  177. this.initializeTextlint(nextProps.isTextlintEnabled, nextProps.editorSettings);
  178. // fold drawio section
  179. this.foldDrawioSection();
  180. }
  181. initializeEditorSettings(editorSettings) {
  182. if (editorSettings == null) {
  183. return;
  184. }
  185. // load theme
  186. const theme = editorSettings.theme;
  187. if (theme != null) {
  188. this.loadTheme(theme);
  189. }
  190. // set keymap
  191. const keymapMode = editorSettings.keymapMode;
  192. if (keymapMode != null) {
  193. this.setKeymapMode(keymapMode);
  194. }
  195. }
  196. async initializeTextlint(isTextlintEnabled, editorSettings) {
  197. if (!isTextlintEnabled || editorSettings == null) {
  198. return;
  199. }
  200. const textlintRules = editorSettings.textlintSettings?.textlintRules;
  201. // If database has empty array, pass null instead to enable all default rules
  202. const rulesForValidator = (textlintRules == null || textlintRules.length === 0) ? null : textlintRules;
  203. this.textlintValidator = createValidator(rulesForValidator);
  204. this.codemirrorLintConfig = { getAnnotations: this.textlintValidator, async: true };
  205. }
  206. getCodeMirror() {
  207. return this.cm.current?.editor;
  208. }
  209. /**
  210. * @inheritDoc
  211. */
  212. forceToFocus() {
  213. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  214. const intervalId = setInterval(() => {
  215. const editor = this.getCodeMirror();
  216. editor.focus();
  217. if (editor.hasFocus()) {
  218. clearInterval(intervalId);
  219. // refresh
  220. editor.refresh();
  221. }
  222. }, 100);
  223. }
  224. /**
  225. * @inheritDoc
  226. */
  227. setValue(newValue) {
  228. this.getCodeMirror().getDoc().setValue(newValue);
  229. // mark clean
  230. this.getCodeMirror().getDoc().markClean();
  231. }
  232. /**
  233. * @inheritDoc
  234. */
  235. setGfmMode(bool) {
  236. // update state
  237. this.setState({
  238. isGfmMode: bool,
  239. });
  240. this.updateCheatsheetStates(bool, null);
  241. // update CodeMirror option
  242. const mode = bool ? 'gfm' : undefined;
  243. this.getCodeMirror().setOption('mode', mode);
  244. }
  245. /**
  246. * @inheritDoc
  247. */
  248. setCaretLine(line) {
  249. if (Number.isNaN(line)) {
  250. return;
  251. }
  252. const editor = this.getCodeMirror();
  253. const linePosition = Math.max(0, line - 1);
  254. editor.setCursor({ line: linePosition }); // leave 'ch' field as null/undefined to indicate the end of line
  255. setTimeout(() => {
  256. this.setScrollTopByLine(linePosition);
  257. }, 100);
  258. }
  259. /**
  260. * @inheritDoc
  261. */
  262. setScrollTopByLine(line) {
  263. if (Number.isNaN(line)) {
  264. return;
  265. }
  266. const editor = this.getCodeMirror();
  267. // get top position of the line
  268. const top = editor.charCoords({ line: line - 1, ch: 0 }, 'local').top;
  269. editor.scrollTo(null, top);
  270. }
  271. /**
  272. * @inheritDoc
  273. */
  274. getStrFromBol() {
  275. const editor = this.getCodeMirror();
  276. const curPos = editor.getCursor();
  277. return editor.getDoc().getRange(this.getBol(), curPos);
  278. }
  279. /**
  280. * @inheritDoc
  281. */
  282. getStrToEol() {
  283. const editor = this.getCodeMirror();
  284. const curPos = editor.getCursor();
  285. return editor.getDoc().getRange(curPos, this.getEol());
  286. }
  287. /**
  288. * @inheritDoc
  289. */
  290. getStrFromBolToSelectedUpperPos() {
  291. const editor = this.getCodeMirror();
  292. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  293. return editor.getDoc().getRange(this.getBol(), pos);
  294. }
  295. /**
  296. * @inheritDoc
  297. */
  298. replaceBolToCurrentPos(text) {
  299. const editor = this.getCodeMirror();
  300. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  301. editor.getDoc().replaceRange(text, this.getBol(), pos);
  302. }
  303. /**
  304. * @inheritDoc
  305. */
  306. replaceLine(text) {
  307. const editor = this.getCodeMirror();
  308. editor.getDoc().replaceRange(text, this.getBol(), this.getEol());
  309. }
  310. /**
  311. * @inheritDoc
  312. */
  313. insertText(text) {
  314. const editor = this.getCodeMirror();
  315. editor.getDoc().replaceSelection(text);
  316. }
  317. /**
  318. * return the postion of the BOL(beginning of line)
  319. */
  320. getBol() {
  321. const editor = this.getCodeMirror();
  322. const curPos = editor.getCursor();
  323. return { line: curPos.line, ch: 0 };
  324. }
  325. /**
  326. * return the postion of the EOL(end of line)
  327. */
  328. getEol() {
  329. const editor = this.getCodeMirror();
  330. const curPos = editor.getCursor();
  331. const lineLength = editor.getDoc().getLine(curPos.line).length;
  332. return { line: curPos.line, ch: lineLength };
  333. }
  334. /**
  335. * select the upper position of pos1 and pos2
  336. * @param {{line: number, ch: number}} pos1
  337. * @param {{line: number, ch: number}} pos2
  338. */
  339. selectUpperPos(pos1, pos2) {
  340. // if both is in same line
  341. if (pos1.line === pos2.line) {
  342. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  343. }
  344. return (pos1.line < pos2.line) ? pos1 : pos2;
  345. }
  346. /**
  347. * select the lower position of pos1 and pos2
  348. * @param {{line: number, ch: number}} pos1
  349. * @param {{line: number, ch: number}} pos2
  350. */
  351. selectLowerPos(pos1, pos2) {
  352. // if both is in same line
  353. if (pos1.line === pos2.line) {
  354. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  355. }
  356. return (pos1.line < pos2.line) ? pos2 : pos1;
  357. }
  358. loadCss(source) {
  359. return new Promise((resolve) => {
  360. loadCssSync(source);
  361. resolve();
  362. });
  363. }
  364. /**
  365. * load Theme
  366. * @see https://codemirror.net/doc/manual.html#config
  367. *
  368. * @param {string} theme
  369. */
  370. loadTheme(theme) {
  371. if (!this.loadedThemeSet.has(theme)) {
  372. const url = this.props.noCdn
  373. ? urljoin(this.cmNoCdnStyleRoot, `codemirror-theme-${theme}.css`)
  374. : urljoin(this.cmCdnRoot, `theme/${theme}.min.css`);
  375. this.loadCss(url);
  376. // update Set
  377. this.loadedThemeSet.add(theme);
  378. }
  379. }
  380. /**
  381. * load assets for Key Maps
  382. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  383. */
  384. loadKeymapMode(keymapMode) {
  385. const loadCss = this.loadCss;
  386. const scriptList = [];
  387. const cssList = [];
  388. // add dependencies
  389. if (this.loadedKeymapSet.size === 0) {
  390. const dialogScriptUrl = this.props.noCdn
  391. ? urljoin(this.cmNoCdnScriptRoot, 'codemirror-dialog.js')
  392. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js');
  393. const dialogStyleUrl = this.props.noCdn
  394. ? urljoin(this.cmNoCdnStyleRoot, 'codemirror-dialog.css')
  395. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css');
  396. scriptList.push(loadScript(dialogScriptUrl));
  397. cssList.push(loadCss(dialogStyleUrl));
  398. }
  399. // load keymap
  400. if (!this.loadedKeymapSet.has(keymapMode)) {
  401. const keymapScriptUrl = this.props.noCdn
  402. ? urljoin(this.cmNoCdnScriptRoot, `codemirror-keymap-${keymapMode}.js`)
  403. : urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`);
  404. scriptList.push(loadScript(keymapScriptUrl));
  405. // update Set
  406. this.loadedKeymapSet.add(keymapMode);
  407. }
  408. // set loading state
  409. this.setState({ isLoadingKeymap: true });
  410. return Promise.all(scriptList.concat(cssList))
  411. .then(() => {
  412. this.setState({ isLoadingKeymap: false });
  413. });
  414. }
  415. /**
  416. * set Key Maps
  417. * @see https://codemirror.net/doc/manual.html#keymaps
  418. *
  419. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  420. */
  421. setKeymapMode(keymapMode) {
  422. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  423. // reset
  424. this.getCodeMirror().setOption('keyMap', 'default');
  425. return;
  426. }
  427. this.loadKeymapMode(keymapMode)
  428. .then(() => {
  429. let errorCount = 0;
  430. const timer = setInterval(() => {
  431. if (errorCount > 10) { // cancel over 3000ms
  432. this.logger.error(`Timeout to load keyMap '${keymapMode}'`);
  433. clearInterval(timer);
  434. }
  435. try {
  436. this.getCodeMirror().setOption('keyMap', keymapMode);
  437. clearInterval(timer);
  438. }
  439. catch (e) {
  440. this.logger.info(`keyMap '${keymapMode}' has not been initialized. retry..`);
  441. // continue if error occured
  442. errorCount++;
  443. }
  444. }, 300);
  445. });
  446. }
  447. /**
  448. * handle ENTER key
  449. */
  450. handleEnterKey() {
  451. if (!this.state.isGfmMode) {
  452. commands.newlineAndIndent(this.getCodeMirror());
  453. return;
  454. }
  455. const context = {
  456. handlers: [], // list of handlers which process enter key
  457. editor: this,
  458. autoFormatMarkdownTable: this.props.editorSettings.autoFormatMarkdownTable,
  459. };
  460. const interceptorManager = this.interceptorManager;
  461. interceptorManager.process('preHandleEnter', context)
  462. .then(() => {
  463. if (context.handlers.length === 0) {
  464. markdownListUtil.newlineAndIndentContinueMarkdownList(this);
  465. }
  466. });
  467. }
  468. /**
  469. * handle Ctrl+ENTER key
  470. */
  471. handleCtrlEnterKey() {
  472. if (this.props.onCtrlEnter != null) {
  473. this.props.onCtrlEnter();
  474. }
  475. }
  476. scrollCursorIntoViewHandler(editor, event) {
  477. if (this.props.onScrollCursorIntoView != null) {
  478. const line = editor.getCursor().line;
  479. this.props.onScrollCursorIntoView(line);
  480. }
  481. }
  482. cursorHandler(editor, event) {
  483. const { additionalClassSet } = this.state;
  484. const hasCustomClass = additionalClassSet.has(MARKDOWN_TABLE_ACTIVATED_CLASS);
  485. const hasLinkClass = additionalClassSet.has(MARKDOWN_LINK_ACTIVATED_CLASS);
  486. const isInTable = mtu.isInTable(editor);
  487. const isInLink = markdownLinkUtil.isInLink(editor);
  488. if (!hasCustomClass && isInTable) {
  489. additionalClassSet.add(MARKDOWN_TABLE_ACTIVATED_CLASS);
  490. this.setState({ additionalClassSet });
  491. }
  492. if (hasCustomClass && !isInTable) {
  493. additionalClassSet.delete(MARKDOWN_TABLE_ACTIVATED_CLASS);
  494. this.setState({ additionalClassSet });
  495. }
  496. if (!hasLinkClass && isInLink) {
  497. additionalClassSet.add(MARKDOWN_LINK_ACTIVATED_CLASS);
  498. this.setState({ additionalClassSet });
  499. }
  500. if (hasLinkClass && !isInLink) {
  501. additionalClassSet.delete(MARKDOWN_LINK_ACTIVATED_CLASS);
  502. this.setState({ additionalClassSet });
  503. }
  504. }
  505. changeHandler(editor, data, value) {
  506. if (this.props.onChange != null) {
  507. const isClean = data.origin == null || editor.isClean();
  508. this.props.onChange(value, isClean);
  509. }
  510. this.updateCheatsheetStates(null, value);
  511. // Show username hint on comment editor
  512. if (this.props.isComment) {
  513. this.commentMentionHelper.showUsernameHint();
  514. }
  515. }
  516. turnOnEmojiPickerMode(pos) {
  517. this.setState({
  518. isEmojiPickerMode: true,
  519. startPosWithEmojiPickerModeTurnedOn: pos,
  520. });
  521. }
  522. turnOffEmojiPickerMode() {
  523. this.setState({
  524. isEmojiPickerMode: false,
  525. });
  526. }
  527. showEmojiPicker(initialSearchingText) {
  528. // show emoji picker with a stored word
  529. this.setState({
  530. isEmojiPickerShown: true,
  531. emojiSearchText: initialSearchingText ?? '',
  532. });
  533. const resetStartPos = initialSearchingText == null;
  534. if (resetStartPos) {
  535. this.setState({ startPosWithEmojiPickerModeTurnedOn: null });
  536. }
  537. this.turnOffEmojiPickerMode();
  538. }
  539. keyPressHandlerForEmojiPicker(editor, event) {
  540. const char = event.key;
  541. const isEmojiPickerMode = this.state.isEmojiPickerMode;
  542. // evaluate whether emoji picker mode to be turned on
  543. if (!isEmojiPickerMode) {
  544. const startPos = this.emojiPickerHelper.shouldModeTurnOn(char);
  545. if (startPos == null) {
  546. return;
  547. }
  548. this.turnOnEmojiPickerMode(startPos);
  549. return;
  550. }
  551. // evaluate whether EmojiPicker to be opened
  552. const startPos = this.state.startPosWithEmojiPickerModeTurnedOn;
  553. if (this.emojiPickerHelper.shouldOpen(startPos)) {
  554. const initialSearchingText = this.emojiPickerHelper.getInitialSearchingText(startPos);
  555. this.showEmojiPicker(initialSearchingText);
  556. return;
  557. }
  558. this.turnOffEmojiPickerMode();
  559. }
  560. keyPressHandler(editor, event) {
  561. this.keyPressHandlerForEmojiPickerThrottled(editor, event);
  562. }
  563. keyDownHandlerForEmojiPicker(editor, event) {
  564. const key = event.key;
  565. if (!this.state.isEmojiPickerMode) {
  566. return;
  567. }
  568. if (['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown', 'BackSpace'].includes(key)) {
  569. this.turnOffEmojiPickerMode();
  570. }
  571. }
  572. keyDownHandler(editor, event) {
  573. this.keyDownHandlerForEmojiPickerThrottled(editor, event);
  574. }
  575. windowClickHandler() {
  576. this.turnOffEmojiPickerMode();
  577. }
  578. /**
  579. * CodeMirror paste event handler
  580. * see: https://codemirror.net/doc/manual.html#events
  581. * @param {any} editor An editor instance of CodeMirror
  582. * @param {any} event
  583. */
  584. pasteHandler(editor, event) {
  585. const types = event.clipboardData.types;
  586. // files
  587. if (types.includes('Files')) {
  588. event.preventDefault();
  589. this.dispatchPasteFiles(event);
  590. }
  591. // text
  592. else if (types.includes('text/plain')) {
  593. pasteHelper.pasteText(this, event);
  594. }
  595. }
  596. /**
  597. * update states which related to cheatsheet
  598. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  599. * @param {string} valueTmp (get value from codemirror if null is set)
  600. */
  601. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  602. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  603. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  604. // update isSimpleCheatsheetShown
  605. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  606. this.setState({ isSimpleCheatsheetShown });
  607. }
  608. markdownHelpButtonClickedHandler() {
  609. if (this.props.onMarkdownHelpButtonClicked != null) {
  610. this.props.onMarkdownHelpButtonClicked();
  611. }
  612. }
  613. renderLoadingKeymapOverlay() {
  614. // centering
  615. const style = {
  616. top: 0,
  617. right: 0,
  618. bottom: 0,
  619. left: 0,
  620. };
  621. return this.state.isLoadingKeymap
  622. ? (
  623. <div className="overlay overlay-loading-keymap">
  624. <span style={style} className="overlay-content">
  625. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  626. </span>
  627. </div>
  628. )
  629. : '';
  630. }
  631. renderCheatsheetModalButton() {
  632. return (
  633. <button type="button" className="btn-link gfm-cheatsheet-modal-link small" onClick={() => { this.markdownHelpButtonClickedHandler() }}>
  634. <i className="icon-question" /> Markdown
  635. </button>
  636. );
  637. }
  638. renderCheatsheetOverlay() {
  639. const cheatsheetModalButton = this.renderCheatsheetModalButton();
  640. return (
  641. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3">
  642. { this.state.isSimpleCheatsheetShown
  643. ? (
  644. <div className="text-right">
  645. {cheatsheetModalButton}
  646. <div className="mb-2 d-none d-md-block">
  647. <SimpleCheatsheet />
  648. </div>
  649. </div>
  650. )
  651. : (
  652. <div className="mr-4 mb-2">
  653. {cheatsheetModalButton}
  654. </div>
  655. )
  656. }
  657. </div>
  658. );
  659. }
  660. renderEmojiPicker() {
  661. const { emojiSearchText } = this.state;
  662. return this.state.isEmojiPickerShown
  663. ? (
  664. <div className="text-left">
  665. <div className="mb-2 d-none d-md-block">
  666. <EmojiPicker
  667. onClose={() => this.setState({ isEmojiPickerShown: false })}
  668. onSelected={emoji => this.emojiPickerHelper.addEmoji(emoji, this.state.startPosWithEmojiPickerModeTurnedOn)}
  669. emojiSearchText={emojiSearchText}
  670. emojiPickerHelper={this.emojiPickerHelper}
  671. isOpen={this.state.isEmojiPickerShown}
  672. />
  673. </div>
  674. </div>
  675. )
  676. : '';
  677. }
  678. /**
  679. * return a function to replace a selected range with prefix + selection + suffix
  680. *
  681. * The cursor after replacing is inserted between the selection and the suffix.
  682. */
  683. createReplaceSelectionHandler(prefix, suffix) {
  684. return () => {
  685. const cm = this.getCodeMirror();
  686. const selection = cm.getDoc().getSelection();
  687. const curStartPos = cm.getCursor('from');
  688. const curEndPos = cm.getCursor('to');
  689. const curPosAfterReplacing = {};
  690. curPosAfterReplacing.line = curEndPos.line;
  691. if (curStartPos.line === curEndPos.line) {
  692. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  693. }
  694. else {
  695. curPosAfterReplacing.ch = curEndPos.ch;
  696. }
  697. cm.getDoc().replaceSelection(prefix + selection + suffix);
  698. cm.setCursor(curPosAfterReplacing);
  699. cm.focus();
  700. };
  701. }
  702. /**
  703. * return a function to add prefix to selected each lines
  704. *
  705. * The cursor after editing is inserted between the end of the selection.
  706. */
  707. createAddPrefixToEachLinesHandler(prefix) {
  708. return () => {
  709. const cm = this.getCodeMirror();
  710. const startLineNum = cm.getCursor('from').line;
  711. const endLineNum = cm.getCursor('to').line;
  712. const lines = [];
  713. for (let i = startLineNum; i <= endLineNum; i++) {
  714. lines.push(prefix + cm.getDoc().getLine(i));
  715. }
  716. const replacement = `${lines.join('\n')}\n`;
  717. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  718. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  719. cm.focus();
  720. };
  721. }
  722. /**
  723. * make a selected line a header
  724. *
  725. * The cursor after editing is inserted between the end of the line.
  726. */
  727. makeHeaderHandler() {
  728. const cm = this.getCodeMirror();
  729. const lineNum = cm.getCursor('from').line;
  730. const line = cm.getDoc().getLine(lineNum);
  731. let prefix = '#';
  732. if (!line.startsWith('#')) {
  733. prefix += ' ';
  734. }
  735. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  736. cm.focus();
  737. }
  738. // TODO: re-impl with https://redmine.weseek.co.jp/issues/107248
  739. // showGridEditorHandler() {
  740. // this.gridEditModal.current.show(geu.getGridHtml(this.getCodeMirror()));
  741. // }
  742. showLinkEditHandler() {
  743. this.linkEditModal.current.show(markdownLinkUtil.getMarkdownLink(this.getCodeMirror()));
  744. }
  745. showTemplateModal() {
  746. const onSubmit = templateText => this.setValue(templateText);
  747. this.props.onClickTemplateBtn(onSubmit);
  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. </div>
  1017. );
  1018. }
  1019. }
  1020. CodeMirrorEditor.propTypes = Object.assign({
  1021. isTextlintEnabled: PropTypes.bool,
  1022. lineNumbers: PropTypes.bool,
  1023. editorSettings: PropTypes.object.isRequired,
  1024. onMarkdownHelpButtonClicked: PropTypes.func,
  1025. onAddAttachmentButtonClicked: PropTypes.func,
  1026. }, AbstractEditor.propTypes);
  1027. CodeMirrorEditor.defaultProps = {
  1028. lineNumbers: true,
  1029. };
  1030. const CodeMirrorEditorMemoized = memo(CodeMirrorEditor);
  1031. const CodeMirrorEditorFc = React.forwardRef((props, ref) => {
  1032. const { open: openDrawioModal } = useDrawioModal();
  1033. const { open: openHandsontableModal } = useHandsontableModal();
  1034. const { open: openTemplateModal } = useTemplateModal();
  1035. const openDrawioModalHandler = useCallback((drawioMxFile, onSave) => {
  1036. openDrawioModal(drawioMxFile, onSave);
  1037. }, [openDrawioModal]);
  1038. const openTableModalHandler = useCallback((markdownTable, editor, autoFormatMarkdownTable) => {
  1039. openHandsontableModal(markdownTable, editor, autoFormatMarkdownTable);
  1040. }, [openHandsontableModal]);
  1041. const openTemplateModalHandler = useCallback((onSubmit) => {
  1042. openTemplateModal(onSubmit);
  1043. }, [openTemplateModal]);
  1044. return (
  1045. <CodeMirrorEditorMemoized
  1046. ref={ref}
  1047. onClickDrawioBtn={openDrawioModalHandler}
  1048. onClickTableBtn={openTableModalHandler}
  1049. onClickTemplateBtn={openTemplateModalHandler}
  1050. {...props}
  1051. />
  1052. );
  1053. });
  1054. CodeMirrorEditorFc.displayName = 'CodeMirrorEditorFc';
  1055. export default memo(CodeMirrorEditorFc);