CodeMirrorEditor.jsx 34 KB

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