CodeMirrorEditor.jsx 29 KB

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