CodeMirrorEditor.jsx 31 KB

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