CodeMirrorEditor.jsx 29 KB

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