CodeMirrorEditor.jsx 35 KB

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