CodeMirrorEditor.jsx 32 KB

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