CodeMirrorEditor.jsx 30 KB

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