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