CodeMirrorEditor.jsx 31 KB

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