CodeMirrorEditor.jsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. import React 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 } from 'throttle-debounce';
  10. import urljoin from 'url-join';
  11. import InterceptorManager from '~/services/interceptor-manager';
  12. import loggerFactory from '~/utils/logger';
  13. import { UncontrolledCodeMirror } from '../UncontrolledCodeMirror';
  14. import AbstractEditor from './AbstractEditor';
  15. import CommentMentionHelper from './CommentMentionHelper';
  16. // import DrawioModal from './DrawioModal';
  17. import EditorIcon from './EditorIcon';
  18. import EmojiPicker from './EmojiPicker';
  19. import EmojiPickerHelper from './EmojiPickerHelper';
  20. import GridEditModal from './GridEditModal';
  21. import geu from './GridEditorUtil';
  22. // import HandsontableModal from './HandsontableModal';
  23. import LinkEditModal from './LinkEditModal';
  24. import mdu from './MarkdownDrawioUtil';
  25. import markdownLinkUtil from './MarkdownLinkUtil';
  26. import markdownListUtil from './MarkdownListUtil';
  27. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  28. import mtu from './MarkdownTableUtil';
  29. import pasteHelper from './PasteHelper';
  30. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  31. import SimpleCheatsheet from './SimpleCheatsheet';
  32. import styles from './CodeMirrorEditor.module.scss';
  33. // Textlint
  34. window.JSHINT = JSHINT;
  35. window.kuromojin = { dicPath: '/static/dict' };
  36. require('codemirror/addon/display/placeholder');
  37. require('codemirror/addon/edit/matchbrackets');
  38. require('codemirror/addon/edit/matchtags');
  39. require('codemirror/addon/edit/closetag');
  40. require('codemirror/addon/edit/continuelist');
  41. require('codemirror/addon/hint/show-hint');
  42. require('codemirror/addon/search/searchcursor');
  43. require('codemirror/addon/search/match-highlighter');
  44. require('codemirror/addon/selection/active-line');
  45. require('codemirror/addon/scroll/annotatescrollbar');
  46. require('codemirror/addon/scroll/scrollpastend');
  47. require('codemirror/addon/fold/foldcode');
  48. require('codemirror/addon/fold/foldgutter');
  49. require('codemirror/addon/fold/markdown-fold');
  50. require('codemirror/addon/fold/brace-fold');
  51. require('codemirror/addon/display/placeholder');
  52. require('codemirror/addon/lint/lint');
  53. require('~/client/util/codemirror/autorefresh.ext');
  54. require('~/client/util/codemirror/drawio-fold.ext');
  55. require('~/client/util/codemirror/gfm-growi.mode');
  56. // import modes to highlight
  57. require('codemirror/mode/clike/clike');
  58. require('codemirror/mode/css/css');
  59. require('codemirror/mode/django/django');
  60. require('codemirror/mode/erlang/erlang');
  61. require('codemirror/mode/gfm/gfm');
  62. require('codemirror/mode/go/go');
  63. require('codemirror/mode/javascript/javascript');
  64. require('codemirror/mode/jsx/jsx');
  65. require('codemirror/mode/mathematica/mathematica');
  66. require('codemirror/mode/nginx/nginx');
  67. require('codemirror/mode/perl/perl');
  68. require('codemirror/mode/php/php');
  69. require('codemirror/mode/python/python');
  70. require('codemirror/mode/r/r');
  71. require('codemirror/mode/ruby/ruby');
  72. require('codemirror/mode/rust/rust');
  73. require('codemirror/mode/sass/sass');
  74. require('codemirror/mode/shell/shell');
  75. require('codemirror/mode/sql/sql');
  76. require('codemirror/mode/stex/stex');
  77. require('codemirror/mode/stylus/stylus');
  78. require('codemirror/mode/swift/swift');
  79. require('codemirror/mode/toml/toml');
  80. require('codemirror/mode/vb/vb');
  81. require('codemirror/mode/vue/vue');
  82. require('codemirror/mode/xml/xml');
  83. require('codemirror/mode/yaml/yaml');
  84. const MARKDOWN_TABLE_ACTIVATED_CLASS = 'markdown-table-activated';
  85. const MARKDOWN_LINK_ACTIVATED_CLASS = 'markdown-link-activated';
  86. class CodeMirrorEditor extends AbstractEditor {
  87. constructor(props) {
  88. super(props);
  89. this.logger = loggerFactory('growi:PageEditor:CodeMirrorEditor');
  90. this.state = {
  91. isGfmMode: this.props.isGfmMode,
  92. isLoadingKeymap: false,
  93. isSimpleCheatsheetShown: this.props.isGfmMode && this.props.value?.length === 0,
  94. isCheatsheetModalShown: false,
  95. additionalClassSet: new Set(),
  96. isEmojiPickerShown: false,
  97. emojiSearchText: '',
  98. isEmojiPickerMode: false,
  99. };
  100. this.cm = React.createRef();
  101. this.gridEditModal = React.createRef();
  102. this.linkEditModal = React.createRef();
  103. this.handsontableModal = React.createRef();
  104. this.drawioModal = React.createRef();
  105. this.init();
  106. this.getCodeMirror = this.getCodeMirror.bind(this);
  107. this.getBol = this.getBol.bind(this);
  108. this.getEol = this.getEol.bind(this);
  109. this.loadTheme = this.loadTheme.bind(this);
  110. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  111. this.setKeymapMode = this.setKeymapMode.bind(this);
  112. this.handleEnterKey = this.handleEnterKey.bind(this);
  113. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  114. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  115. this.pasteHandler = this.pasteHandler.bind(this);
  116. this.cursorHandler = this.cursorHandler.bind(this);
  117. this.changeHandler = this.changeHandler.bind(this);
  118. this.onEmojiPickerMode = this.onEmojiPickerMode.bind(this);
  119. this.offEmojiPickerMode = this.offEmojiPickerMode.bind(this);
  120. this.resetEmojiSearchText = this.resetEmojiSearchText.bind(this);
  121. this.isCharValidForShowingEmojiPicker = this.isCharValidForShowingEmojiPicker.bind(this);
  122. this.loadEmojiSearchText = this.loadEmojiSearchText.bind(this);
  123. this.resetEmojiPickerState = this.resetEmojiPickerState.bind(this);
  124. this.windowClickHandler = this.windowClickHandler.bind(this);
  125. this.clickHandlerForEmojiPicker = this.clickHandlerForEmojiPicker.bind(this);
  126. this.keyDownHandler = this.keyDownHandler.bind(this);
  127. this.keyDownHandlerForEmojiPicker = this.keyDownHandlerForEmojiPicker.bind(this);
  128. this.showEmojiPicker = this.showEmojiPicker.bind(this);
  129. this.loadEmojiPicker = this.loadEmojiPicker.bind(this);
  130. this.keyPressHandlerForEmojiPicker = this.keyPressHandlerForEmojiPicker.bind(this);
  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.showDrawioHandler = this.showDrawioHandler.bind(this);
  140. this.foldDrawioSection = this.foldDrawioSection.bind(this);
  141. this.onSaveForDrawio = this.onSaveForDrawio.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. onEmojiPickerMode() {
  516. this.setState({ isEmojiPickerMode: true });
  517. }
  518. offEmojiPickerMode() {
  519. this.setState({ isEmojiPickerMode: false });
  520. }
  521. resetEmojiSearchText() {
  522. this.setState({ emojiSearchText: '' });
  523. }
  524. isCharValidForShowingEmojiPicker(ch) {
  525. const lowerCh = ch.toLowerCase();
  526. return 'abcdefghijklmnopqrstuvwxyz0123456789-+_'.indexOf(lowerCh) !== -1;
  527. }
  528. loadEmojiSearchText(newchar) {
  529. this.setState(prev => ({ emojiSearchText: prev.emojiSearchText.concat(newchar) }));
  530. }
  531. showEmojiPicker() {
  532. // show emoji picker with a stored word
  533. this.setState({ isEmojiPickerShown: true });
  534. this.offEmojiPickerMode();
  535. }
  536. loadEmojiPicker(ch) {
  537. this.loadEmojiSearchText(ch);
  538. this.showEmojiPicker();
  539. }
  540. resetEmojiPickerState() {
  541. this.offEmojiPickerMode();
  542. this.resetEmojiSearchText();
  543. }
  544. keyPressHandlerForEmojiPicker(editor, event) {
  545. const char = event.key;
  546. const isEmojiPickerMode = this.state.isEmojiPickerMode;
  547. if (!isEmojiPickerMode) {
  548. if (char === ':') { // Turn on emoji picker mode
  549. this.onEmojiPickerMode();
  550. this.resetEmojiSearchText();
  551. return;
  552. }
  553. return;
  554. }
  555. if (!this.isCharValidForShowingEmojiPicker(char)) {
  556. this.resetEmojiPickerState();
  557. return;
  558. }
  559. // TODO: Use throttle https://redmine.weseek.co.jp/issues/106037
  560. this.loadEmojiPicker(char);
  561. }
  562. keyPressHandler(editor, event) {
  563. this.keyPressHandlerForEmojiPicker(editor, event);
  564. }
  565. keyDownHandlerForEmojiPicker(editor, event) {
  566. const key = event.key;
  567. if (['ArrowRight', 'ArrowLeft', 'ArrorUp', 'ArrowDown', 'BackSpace'].includes(key)) {
  568. this.resetEmojiPickerState();
  569. }
  570. }
  571. clickHandlerForEmojiPicker(event) {
  572. this.resetEmojiPickerState();
  573. }
  574. windowClickHandler(event) {
  575. this.clickHandlerForEmojiPicker(event);
  576. }
  577. keyDownHandler(editor, event) {
  578. this.keyDownHandlerForEmojiPicker(editor, event);
  579. }
  580. /**
  581. * CodeMirror paste event handler
  582. * see: https://codemirror.net/doc/manual.html#events
  583. * @param {any} editor An editor instance of CodeMirror
  584. * @param {any} event
  585. */
  586. pasteHandler(editor, event) {
  587. const types = event.clipboardData.types;
  588. // files
  589. if (types.includes('Files')) {
  590. event.preventDefault();
  591. this.dispatchPasteFiles(event);
  592. }
  593. // text
  594. else if (types.includes('text/plain')) {
  595. pasteHelper.pasteText(this, event);
  596. }
  597. }
  598. /**
  599. * update states which related to cheatsheet
  600. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  601. * @param {string} valueTmp (get value from codemirror if null is set)
  602. */
  603. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  604. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  605. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  606. // update isSimpleCheatsheetShown
  607. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  608. this.setState({ isSimpleCheatsheetShown });
  609. }
  610. markdownHelpButtonClickedHandler() {
  611. if (this.props.onMarkdownHelpButtonClicked != null) {
  612. this.props.onMarkdownHelpButtonClicked();
  613. }
  614. }
  615. renderLoadingKeymapOverlay() {
  616. // centering
  617. const style = {
  618. top: 0,
  619. right: 0,
  620. bottom: 0,
  621. left: 0,
  622. };
  623. return this.state.isLoadingKeymap
  624. ? (
  625. <div className="overlay overlay-loading-keymap">
  626. <span style={style} className="overlay-content">
  627. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  628. </span>
  629. </div>
  630. )
  631. : '';
  632. }
  633. renderCheatsheetModalButton() {
  634. return (
  635. <button type="button" className="btn-link gfm-cheatsheet-modal-link small" onClick={() => { this.markdownHelpButtonClickedHandler() }}>
  636. <i className="icon-question" /> Markdown
  637. </button>
  638. );
  639. }
  640. renderCheatsheetOverlay() {
  641. const cheatsheetModalButton = this.renderCheatsheetModalButton();
  642. return (
  643. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3">
  644. { this.state.isSimpleCheatsheetShown
  645. ? (
  646. <div className="text-right">
  647. {cheatsheetModalButton}
  648. <div className="mb-2 d-none d-md-block">
  649. <SimpleCheatsheet />
  650. </div>
  651. </div>
  652. )
  653. : (
  654. <div className="mr-4 mb-2">
  655. {cheatsheetModalButton}
  656. </div>
  657. )
  658. }
  659. </div>
  660. );
  661. }
  662. renderEmojiPicker() {
  663. const { emojiSearchText } = this.state;
  664. return this.state.isEmojiPickerShown
  665. ? (
  666. <div className="text-left">
  667. <div className="mb-2 d-none d-md-block">
  668. <EmojiPicker
  669. onClose={() => this.setState({ isEmojiPickerShown: false, emojiSearchText: null })}
  670. emojiSearchText={emojiSearchText}
  671. emojiPickerHelper={this.emojiPickerHelper}
  672. isOpen={this.state.isEmojiPickerShown}
  673. />
  674. </div>
  675. </div>
  676. )
  677. : '';
  678. }
  679. /**
  680. * return a function to replace a selected range with prefix + selection + suffix
  681. *
  682. * The cursor after replacing is inserted between the selection and the suffix.
  683. */
  684. createReplaceSelectionHandler(prefix, suffix) {
  685. return () => {
  686. const cm = this.getCodeMirror();
  687. const selection = cm.getDoc().getSelection();
  688. const curStartPos = cm.getCursor('from');
  689. const curEndPos = cm.getCursor('to');
  690. const curPosAfterReplacing = {};
  691. curPosAfterReplacing.line = curEndPos.line;
  692. if (curStartPos.line === curEndPos.line) {
  693. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  694. }
  695. else {
  696. curPosAfterReplacing.ch = curEndPos.ch;
  697. }
  698. cm.getDoc().replaceSelection(prefix + selection + suffix);
  699. cm.setCursor(curPosAfterReplacing);
  700. cm.focus();
  701. };
  702. }
  703. /**
  704. * return a function to add prefix to selected each lines
  705. *
  706. * The cursor after editing is inserted between the end of the selection.
  707. */
  708. createAddPrefixToEachLinesHandler(prefix) {
  709. return () => {
  710. const cm = this.getCodeMirror();
  711. const startLineNum = cm.getCursor('from').line;
  712. const endLineNum = cm.getCursor('to').line;
  713. const lines = [];
  714. for (let i = startLineNum; i <= endLineNum; i++) {
  715. lines.push(prefix + cm.getDoc().getLine(i));
  716. }
  717. const replacement = `${lines.join('\n')}\n`;
  718. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  719. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  720. cm.focus();
  721. };
  722. }
  723. /**
  724. * make a selected line a header
  725. *
  726. * The cursor after editing is inserted between the end of the line.
  727. */
  728. makeHeaderHandler() {
  729. const cm = this.getCodeMirror();
  730. const lineNum = cm.getCursor('from').line;
  731. const line = cm.getDoc().getLine(lineNum);
  732. let prefix = '#';
  733. if (!line.startsWith('#')) {
  734. prefix += ' ';
  735. }
  736. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  737. cm.focus();
  738. }
  739. showGridEditorHandler() {
  740. this.gridEditModal.current.show(geu.getGridHtml(this.getCodeMirror()));
  741. }
  742. showLinkEditHandler() {
  743. this.linkEditModal.current.show(markdownLinkUtil.getMarkdownLink(this.getCodeMirror()));
  744. }
  745. showHandsonTableHandler() {
  746. // this.handsontableModal.current.show(mtu.getMarkdownTable(this.getCodeMirror()));
  747. }
  748. showDrawioHandler() {
  749. // this.drawioModal.current.show(mdu.getMarkdownDrawioMxfile(this.getCodeMirror()));
  750. }
  751. // fold draw.io section (::: drawio ~ :::)
  752. foldDrawioSection() {
  753. const editor = this.getCodeMirror();
  754. const lineNumbers = mdu.findAllDrawioSection(editor);
  755. lineNumbers.forEach((lineNumber) => {
  756. editor.foldCode({ line: lineNumber, ch: 0 }, { scanUp: false }, 'fold');
  757. });
  758. }
  759. onSaveForDrawio(drawioData) {
  760. const range = mdu.replaceFocusedDrawioWithEditor(this.getCodeMirror(), drawioData);
  761. // Fold the section after the drawio section (:::drawio) has been updated.
  762. this.foldDrawioSection();
  763. return range;
  764. }
  765. getNavbarItems() {
  766. return [
  767. <Button
  768. key="nav-item-bold"
  769. color={null}
  770. size="sm"
  771. title="Bold"
  772. onClick={this.createReplaceSelectionHandler('**', '**')}
  773. >
  774. <EditorIcon icon="Bold" />
  775. </Button>,
  776. <Button
  777. key="nav-item-italic"
  778. color={null}
  779. size="sm"
  780. title="Italic"
  781. onClick={this.createReplaceSelectionHandler('*', '*')}
  782. >
  783. <EditorIcon icon="Italic" />
  784. </Button>,
  785. <Button
  786. key="nav-item-strikethrough"
  787. color={null}
  788. size="sm"
  789. title="Strikethrough"
  790. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  791. >
  792. <EditorIcon icon="Strikethrough" />
  793. </Button>,
  794. <Button
  795. key="nav-item-header"
  796. color={null}
  797. size="sm"
  798. title="Heading"
  799. onClick={this.makeHeaderHandler}
  800. >
  801. <EditorIcon icon="Heading" />
  802. </Button>,
  803. <Button
  804. key="nav-item-code"
  805. color={null}
  806. size="sm"
  807. title="Inline Code"
  808. onClick={this.createReplaceSelectionHandler('`', '`')}
  809. >
  810. <EditorIcon icon="InlineCode" />
  811. </Button>,
  812. <Button
  813. key="nav-item-quote"
  814. color={null}
  815. size="sm"
  816. title="Quote"
  817. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  818. >
  819. <EditorIcon icon="Quote" />
  820. </Button>,
  821. <Button
  822. key="nav-item-ul"
  823. color={null}
  824. size="sm"
  825. title="List"
  826. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  827. >
  828. <EditorIcon icon="List" />
  829. </Button>,
  830. <Button
  831. key="nav-item-ol"
  832. color={null}
  833. size="sm"
  834. title="Numbered List"
  835. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  836. >
  837. <EditorIcon icon="NumberedList" />
  838. </Button>,
  839. <Button
  840. key="nav-item-checkbox"
  841. color={null}
  842. size="sm"
  843. title="Check List"
  844. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  845. >
  846. <EditorIcon icon="CheckList" />
  847. </Button>,
  848. <Button
  849. key="nav-item-attachment"
  850. color={null}
  851. size="sm"
  852. title="Attachment"
  853. onClick={this.props.onAddAttachmentButtonClicked}
  854. >
  855. <EditorIcon icon="Attachment" />
  856. </Button>,
  857. <Button
  858. key="nav-item-link"
  859. color={null}
  860. size="sm"
  861. title="Link"
  862. onClick={this.showLinkEditHandler}
  863. >
  864. <EditorIcon icon="Link" />
  865. </Button>,
  866. <Button
  867. key="nav-item-image"
  868. color={null}
  869. size="sm"
  870. title="Image"
  871. onClick={this.createReplaceSelectionHandler('![', ']()')}
  872. >
  873. <EditorIcon icon="Image" />
  874. </Button>,
  875. <Button
  876. key="nav-item-grid"
  877. color={null}
  878. size="sm"
  879. title="Grid"
  880. onClick={this.showGridEditorHandler}
  881. >
  882. <EditorIcon icon="Grid" />
  883. </Button>,
  884. <Button
  885. key="nav-item-table"
  886. color={null}
  887. size="sm"
  888. title="Table"
  889. onClick={this.showHandsonTableHandler}
  890. >
  891. <EditorIcon icon="Table" />
  892. </Button>,
  893. <Button
  894. key="nav-item-drawio"
  895. color={null}
  896. bssize="small"
  897. title="draw.io"
  898. onClick={this.showDrawioHandler}
  899. >
  900. <EditorIcon icon="Drawio" />
  901. </Button>,
  902. <Button
  903. key="nav-item-emoji"
  904. color={null}
  905. bssize="small"
  906. title="Emoji"
  907. onClick={() => this.setState({ isEmojiPickerShown: true })}
  908. >
  909. <EditorIcon icon="Emoji" />
  910. </Button>,
  911. ];
  912. }
  913. render() {
  914. const { isTextlintEnabled } = this.props;
  915. const lint = isTextlintEnabled ? this.codemirrorLintConfig : false;
  916. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  917. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plain Text..';
  918. const gutters = [];
  919. if (this.props.lineNumbers != null) {
  920. gutters.push('CodeMirror-linenumbers', 'CodeMirror-foldgutter');
  921. }
  922. if (isTextlintEnabled) {
  923. gutters.push('CodeMirror-lint-markers');
  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. // == temporary deactivate editorDidMount to use https://github.com/scniro/react-codemirror2/issues/284#issuecomment-1155928554
  932. // editorDidMount={(editor) => {
  933. // // add event handlers
  934. // editor.on('paste', this.pasteHandler);
  935. // editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  936. // }}
  937. value={this.props.value}
  938. options={{
  939. indentUnit: this.props.indentSize,
  940. theme: this.props.editorSettings.theme ?? 'elegant',
  941. styleActiveLine: this.props.editorSettings.styleActiveLine,
  942. lineWrapping: true,
  943. scrollPastEnd: true,
  944. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  945. autoCloseTags: true,
  946. placeholder,
  947. matchBrackets: true,
  948. emoji: true,
  949. matchTags: { bothTags: true },
  950. // folding
  951. foldGutter: this.props.lineNumbers,
  952. gutters,
  953. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  954. highlightSelectionMatches: { annotateScrollbar: true },
  955. // continuelist, indentlist
  956. extraKeys: {
  957. Enter: this.handleEnterKey,
  958. 'Ctrl-Enter': this.handleCtrlEnterKey,
  959. 'Cmd-Enter': this.handleCtrlEnterKey,
  960. Tab: 'indentMore',
  961. 'Shift-Tab': 'indentLess',
  962. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  963. },
  964. lint,
  965. }}
  966. onCursor={this.cursorHandler}
  967. onScroll={(editor, data) => {
  968. if (this.props.onScroll != null) {
  969. // add line data
  970. const line = editor.lineAtHeight(data.top, 'local');
  971. data.line = line;
  972. this.props.onScroll(data);
  973. }
  974. }}
  975. onChange={this.changeHandler}
  976. onDragEnter={(editor, event) => {
  977. if (this.props.onDragEnter != null) {
  978. this.props.onDragEnter(event);
  979. }
  980. }}
  981. onKeyPress={this.keyPressHandler}
  982. onKeyDown={this.keyDownHandler}
  983. />
  984. { this.renderLoadingKeymapOverlay() }
  985. { this.renderCheatsheetOverlay() }
  986. { this.renderEmojiPicker() }
  987. <GridEditModal
  988. ref={this.gridEditModal}
  989. onSave={(grid) => { return geu.replaceGridWithHtmlWithEditor(this.getCodeMirror(), grid) }}
  990. />
  991. <LinkEditModal
  992. ref={this.linkEditModal}
  993. onSave={(linkText) => { return markdownLinkUtil.replaceFocusedMarkdownLinkWithEditor(this.getCodeMirror(), linkText) }}
  994. />
  995. {/*
  996. <HandsontableModal
  997. ref={this.handsontableModal}
  998. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  999. autoFormatMarkdownTable={this.props.editorSettings.autoFormatMarkdownTable}
  1000. /> */}
  1001. {/* <DrawioModal
  1002. ref={this.drawioModal}
  1003. onSave={this.onSaveForDrawio}
  1004. /> */}
  1005. </div>
  1006. );
  1007. }
  1008. }
  1009. CodeMirrorEditor.propTypes = Object.assign({
  1010. isTextlintEnabled: PropTypes.bool,
  1011. lineNumbers: PropTypes.bool,
  1012. editorSettings: PropTypes.object.isRequired,
  1013. onMarkdownHelpButtonClicked: PropTypes.func,
  1014. onAddAttachmentButtonClicked: PropTypes.func,
  1015. }, AbstractEditor.propTypes);
  1016. CodeMirrorEditor.defaultProps = {
  1017. lineNumbers: true,
  1018. };
  1019. export default CodeMirrorEditor;