CodeMirrorEditor.jsx 35 KB

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