CodeMirrorEditor.jsx 29 KB

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