CodeMirrorEditor.jsx 32 KB

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