CodeMirrorEditor.jsx 32 KB

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