CodeMirrorEditor.jsx 28 KB

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