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