CodeMirrorEditor.jsx 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. import React from 'react';
  2. import { createValidator } from '@growi/codemirror-textlint';
  3. import * as codemirror from 'codemirror';
  4. import { JSHINT } from 'jshint';
  5. import * as loadCssSync from 'load-css-file';
  6. import PropTypes from 'prop-types';
  7. import { Button } from 'reactstrap';
  8. import * as loadScript from 'simple-load-script';
  9. import urljoin from 'url-join';
  10. import InterceptorManager from '~/services/interceptor-manager';
  11. import loggerFactory from '~/utils/logger';
  12. import { UncontrolledCodeMirror } from '../UncontrolledCodeMirror';
  13. import AbstractEditor from './AbstractEditor';
  14. import DrawioModal from './DrawioModal';
  15. import EditorIcon from './EditorIcon';
  16. import EmojiPicker from './EmojiPicker';
  17. import EmojiPickerHelper from './EmojiPickerHelper';
  18. import GridEditModal from './GridEditModal';
  19. import geu from './GridEditorUtil';
  20. import HandsontableModal from './HandsontableModal';
  21. import LinkEditModal from './LinkEditModal';
  22. import mdu from './MarkdownDrawioUtil';
  23. import mlu from './MarkdownLinkUtil';
  24. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  25. import mtu from './MarkdownTableUtil';
  26. import pasteHelper from './PasteHelper';
  27. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  28. import SimpleCheatsheet from './SimpleCheatsheet';
  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,
  100. isLoadingKeymap: false,
  101. isSimpleCheatsheetShown: this.props.isGfmMode && this.props.value.length === 0,
  102. isCheatsheetModalShown: false,
  103. additionalClassSet: new Set(),
  104. isEmojiPickerShown: false,
  105. emojiSearchText: null,
  106. };
  107. this.gridEditModal = React.createRef();
  108. this.linkEditModal = React.createRef();
  109. this.handsontableModal = React.createRef();
  110. this.drawioModal = React.createRef();
  111. this.init();
  112. this.getCodeMirror = this.getCodeMirror.bind(this);
  113. this.getBol = this.getBol.bind(this);
  114. this.getEol = this.getEol.bind(this);
  115. this.loadTheme = this.loadTheme.bind(this);
  116. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  117. this.setKeymapMode = this.setKeymapMode.bind(this);
  118. this.handleEnterKey = this.handleEnterKey.bind(this);
  119. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  120. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  121. this.pasteHandler = this.pasteHandler.bind(this);
  122. this.cursorHandler = this.cursorHandler.bind(this);
  123. this.changeHandler = this.changeHandler.bind(this);
  124. this.keyUpHandler = this.keyUpHandler.bind(this);
  125. this.updateCheatsheetStates = this.updateCheatsheetStates.bind(this);
  126. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  127. this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
  128. this.makeHeaderHandler = this.makeHeaderHandler.bind(this);
  129. this.showGridEditorHandler = this.showGridEditorHandler.bind(this);
  130. this.showLinkEditHandler = this.showLinkEditHandler.bind(this);
  131. this.showHandsonTableHandler = this.showHandsonTableHandler.bind(this);
  132. this.showDrawioHandler = this.showDrawioHandler.bind(this);
  133. this.foldDrawioSection = this.foldDrawioSection.bind(this);
  134. this.onSaveForDrawio = this.onSaveForDrawio.bind(this);
  135. this.checkWhetherEmojiPickerShouldBeShown = this.checkWhetherEmojiPickerShouldBeShown.bind(this);
  136. }
  137. init() {
  138. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.42.0';
  139. this.cmNoCdnScriptRoot = '/static/js/cdn';
  140. this.cmNoCdnStyleRoot = '/static/styles/cdn';
  141. this.interceptorManager = new InterceptorManager();
  142. this.interceptorManager.addInterceptors([
  143. new PreventMarkdownListInterceptor(),
  144. new MarkdownTableInterceptor(),
  145. ]);
  146. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  147. this.loadedKeymapSet = new Set();
  148. }
  149. componentWillMount() {
  150. this.initializeTextlint();
  151. }
  152. componentDidMount() {
  153. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  154. this.getCodeMirror().codeMirrorEditor = this;
  155. // load theme
  156. const theme = this.props.editorOptions.theme;
  157. this.loadTheme(theme);
  158. // set keymap
  159. const keymapMode = this.props.editorOptions.keymapMode;
  160. this.setKeymapMode(keymapMode);
  161. // fold drawio section
  162. this.foldDrawioSection();
  163. this.emojiPickerHelper = new EmojiPickerHelper(this.getCodeMirror());
  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. });
  217. this.updateCheatsheetStates(bool, null);
  218. // update CodeMirror option
  219. const mode = bool ? 'gfm' : undefined;
  220. this.getCodeMirror().setOption('mode', mode);
  221. }
  222. /**
  223. * @inheritDoc
  224. */
  225. setCaretLine(line) {
  226. if (Number.isNaN(line)) {
  227. return;
  228. }
  229. const editor = this.getCodeMirror();
  230. const linePosition = Math.max(0, line);
  231. editor.setCursor({ line: linePosition }); // leave 'ch' field as null/undefined to indicate the end of line
  232. setTimeout(() => {
  233. this.setScrollTopByLine(linePosition);
  234. }, 100);
  235. }
  236. /**
  237. * @inheritDoc
  238. */
  239. setScrollTopByLine(line) {
  240. if (Number.isNaN(line)) {
  241. return;
  242. }
  243. const editor = this.getCodeMirror();
  244. // get top position of the line
  245. const top = editor.charCoords({ line: line - 1, ch: 0 }, 'local').top;
  246. editor.scrollTo(null, top);
  247. }
  248. /**
  249. * @inheritDoc
  250. */
  251. getStrFromBol() {
  252. const editor = this.getCodeMirror();
  253. const curPos = editor.getCursor();
  254. return editor.getDoc().getRange(this.getBol(), curPos);
  255. }
  256. /**
  257. * @inheritDoc
  258. */
  259. getStrToEol() {
  260. const editor = this.getCodeMirror();
  261. const curPos = editor.getCursor();
  262. return editor.getDoc().getRange(curPos, this.getEol());
  263. }
  264. /**
  265. * @inheritDoc
  266. */
  267. getStrFromBolToSelectedUpperPos() {
  268. const editor = this.getCodeMirror();
  269. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  270. return editor.getDoc().getRange(this.getBol(), pos);
  271. }
  272. /**
  273. * @inheritDoc
  274. */
  275. replaceBolToCurrentPos(text) {
  276. const editor = this.getCodeMirror();
  277. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  278. editor.getDoc().replaceRange(text, this.getBol(), pos);
  279. }
  280. /**
  281. * @inheritDoc
  282. */
  283. replaceLine(text) {
  284. const editor = this.getCodeMirror();
  285. editor.getDoc().replaceRange(text, this.getBol(), this.getEol());
  286. }
  287. /**
  288. * @inheritDoc
  289. */
  290. insertText(text) {
  291. const editor = this.getCodeMirror();
  292. editor.getDoc().replaceSelection(text);
  293. }
  294. /**
  295. * return the postion of the BOL(beginning of line)
  296. */
  297. getBol() {
  298. const editor = this.getCodeMirror();
  299. const curPos = editor.getCursor();
  300. return { line: curPos.line, ch: 0 };
  301. }
  302. /**
  303. * return the postion of the EOL(end of line)
  304. */
  305. getEol() {
  306. const editor = this.getCodeMirror();
  307. const curPos = editor.getCursor();
  308. const lineLength = editor.getDoc().getLine(curPos.line).length;
  309. return { line: curPos.line, ch: lineLength };
  310. }
  311. /**
  312. * select the upper position of pos1 and pos2
  313. * @param {{line: number, ch: number}} pos1
  314. * @param {{line: number, ch: number}} pos2
  315. */
  316. selectUpperPos(pos1, pos2) {
  317. // if both is in same line
  318. if (pos1.line === pos2.line) {
  319. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  320. }
  321. return (pos1.line < pos2.line) ? pos1 : pos2;
  322. }
  323. /**
  324. * select the lower position of pos1 and pos2
  325. * @param {{line: number, ch: number}} pos1
  326. * @param {{line: number, ch: number}} pos2
  327. */
  328. selectLowerPos(pos1, pos2) {
  329. // if both is in same line
  330. if (pos1.line === pos2.line) {
  331. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  332. }
  333. return (pos1.line < pos2.line) ? pos2 : pos1;
  334. }
  335. loadCss(source) {
  336. return new Promise((resolve) => {
  337. loadCssSync(source);
  338. resolve();
  339. });
  340. }
  341. /**
  342. * load Theme
  343. * @see https://codemirror.net/doc/manual.html#config
  344. *
  345. * @param {string} theme
  346. */
  347. loadTheme(theme) {
  348. if (!this.loadedThemeSet.has(theme)) {
  349. const url = this.props.noCdn
  350. ? urljoin(this.cmNoCdnStyleRoot, `codemirror-theme-${theme}.css`)
  351. : urljoin(this.cmCdnRoot, `theme/${theme}.min.css`);
  352. this.loadCss(url);
  353. // update Set
  354. this.loadedThemeSet.add(theme);
  355. }
  356. }
  357. /**
  358. * load assets for Key Maps
  359. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  360. */
  361. loadKeymapMode(keymapMode) {
  362. const loadCss = this.loadCss;
  363. const scriptList = [];
  364. const cssList = [];
  365. // add dependencies
  366. if (this.loadedKeymapSet.size === 0) {
  367. const dialogScriptUrl = this.props.noCdn
  368. ? urljoin(this.cmNoCdnScriptRoot, 'codemirror-dialog.js')
  369. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js');
  370. const dialogStyleUrl = this.props.noCdn
  371. ? urljoin(this.cmNoCdnStyleRoot, 'codemirror-dialog.css')
  372. : urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css');
  373. scriptList.push(loadScript(dialogScriptUrl));
  374. cssList.push(loadCss(dialogStyleUrl));
  375. }
  376. // load keymap
  377. if (!this.loadedKeymapSet.has(keymapMode)) {
  378. const keymapScriptUrl = this.props.noCdn
  379. ? urljoin(this.cmNoCdnScriptRoot, `codemirror-keymap-${keymapMode}.js`)
  380. : urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`);
  381. scriptList.push(loadScript(keymapScriptUrl));
  382. // update Set
  383. this.loadedKeymapSet.add(keymapMode);
  384. }
  385. // set loading state
  386. this.setState({ isLoadingKeymap: true });
  387. return Promise.all(scriptList.concat(cssList))
  388. .then(() => {
  389. this.setState({ isLoadingKeymap: false });
  390. });
  391. }
  392. /**
  393. * set Key Maps
  394. * @see https://codemirror.net/doc/manual.html#keymaps
  395. *
  396. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  397. */
  398. setKeymapMode(keymapMode) {
  399. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  400. // reset
  401. this.getCodeMirror().setOption('keyMap', 'default');
  402. return;
  403. }
  404. this.loadKeymapMode(keymapMode)
  405. .then(() => {
  406. let errorCount = 0;
  407. const timer = setInterval(() => {
  408. if (errorCount > 10) { // cancel over 3000ms
  409. this.logger.error(`Timeout to load keyMap '${keymapMode}'`);
  410. clearInterval(timer);
  411. }
  412. try {
  413. this.getCodeMirror().setOption('keyMap', keymapMode);
  414. clearInterval(timer);
  415. }
  416. catch (e) {
  417. this.logger.info(`keyMap '${keymapMode}' has not been initialized. retry..`);
  418. // continue if error occured
  419. errorCount++;
  420. }
  421. }, 300);
  422. });
  423. }
  424. /**
  425. * handle ENTER key
  426. */
  427. handleEnterKey() {
  428. if (!this.state.isGfmMode) {
  429. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  430. return;
  431. }
  432. const context = {
  433. handlers: [], // list of handlers which process enter key
  434. editor: this,
  435. editorOptions: this.props.editorOptions,
  436. };
  437. const interceptorManager = this.interceptorManager;
  438. interceptorManager.process('preHandleEnter', context)
  439. .then(() => {
  440. if (context.handlers.length === 0) {
  441. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  442. }
  443. });
  444. }
  445. /**
  446. * handle Ctrl+ENTER key
  447. */
  448. handleCtrlEnterKey() {
  449. if (this.props.onCtrlEnter != null) {
  450. this.props.onCtrlEnter();
  451. }
  452. }
  453. scrollCursorIntoViewHandler(editor, event) {
  454. if (this.props.onScrollCursorIntoView != null) {
  455. const line = editor.getCursor().line;
  456. this.props.onScrollCursorIntoView(line);
  457. }
  458. }
  459. cursorHandler(editor, event) {
  460. const { additionalClassSet } = this.state;
  461. const hasCustomClass = additionalClassSet.has(MARKDOWN_TABLE_ACTIVATED_CLASS);
  462. const hasLinkClass = additionalClassSet.has(MARKDOWN_LINK_ACTIVATED_CLASS);
  463. const isInTable = mtu.isInTable(editor);
  464. const isInLink = mlu.isInLink(editor);
  465. if (!hasCustomClass && isInTable) {
  466. additionalClassSet.add(MARKDOWN_TABLE_ACTIVATED_CLASS);
  467. this.setState({ additionalClassSet });
  468. }
  469. if (hasCustomClass && !isInTable) {
  470. additionalClassSet.delete(MARKDOWN_TABLE_ACTIVATED_CLASS);
  471. this.setState({ additionalClassSet });
  472. }
  473. if (!hasLinkClass && isInLink) {
  474. additionalClassSet.add(MARKDOWN_LINK_ACTIVATED_CLASS);
  475. this.setState({ additionalClassSet });
  476. }
  477. if (hasLinkClass && !isInLink) {
  478. additionalClassSet.delete(MARKDOWN_LINK_ACTIVATED_CLASS);
  479. this.setState({ additionalClassSet });
  480. }
  481. }
  482. changeHandler(editor, data, value) {
  483. if (this.props.onChange != null) {
  484. this.props.onChange(value);
  485. }
  486. this.updateCheatsheetStates(null, value);
  487. }
  488. keyUpHandler(editor, event) {
  489. if (event.key !== 'Backspace') {
  490. this.checkWhetherEmojiPickerShouldBeShown();
  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. * Show emoji picker component when emoji pattern (`:` + searchWord ) found
  513. * eg `:a`, `:ap`
  514. */
  515. checkWhetherEmojiPickerShouldBeShown() {
  516. const searchWord = this.emojiPickerHelper.getEmoji();
  517. if (searchWord == null) {
  518. this.setState({ isEmojiPickerShown: false });
  519. this.setState({ emojiSearchText: null });
  520. }
  521. else {
  522. this.setState({ emojiSearchText: searchWord });
  523. // Show emoji picker after user stop typing
  524. setTimeout(() => {
  525. this.setState({ isEmojiPickerShown: true });
  526. }, 700);
  527. }
  528. }
  529. /**
  530. * update states which related to cheatsheet
  531. * @param {boolean} isGfmModeTmp (use state.isGfmMode if null is set)
  532. * @param {string} valueTmp (get value from codemirror if null is set)
  533. */
  534. updateCheatsheetStates(isGfmModeTmp, valueTmp) {
  535. const isGfmMode = isGfmModeTmp || this.state.isGfmMode;
  536. const value = valueTmp || this.getCodeMirror().getDoc().getValue();
  537. // update isSimpleCheatsheetShown
  538. const isSimpleCheatsheetShown = isGfmMode && value.length === 0;
  539. this.setState({ isSimpleCheatsheetShown });
  540. }
  541. markdownHelpButtonClickedHandler() {
  542. if (this.props.onMarkdownHelpButtonClicked != null) {
  543. this.props.onMarkdownHelpButtonClicked();
  544. }
  545. }
  546. renderLoadingKeymapOverlay() {
  547. // centering
  548. const style = {
  549. top: 0,
  550. right: 0,
  551. bottom: 0,
  552. left: 0,
  553. };
  554. return this.state.isLoadingKeymap
  555. ? (
  556. <div className="overlay overlay-loading-keymap">
  557. <span style={style} className="overlay-content">
  558. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  559. </span>
  560. </div>
  561. )
  562. : '';
  563. }
  564. renderCheatsheetModalButton() {
  565. return (
  566. <button type="button" className="btn-link gfm-cheatsheet-modal-link small" onClick={() => { this.markdownHelpButtonClickedHandler() }}>
  567. <i className="icon-question" /> Markdown
  568. </button>
  569. );
  570. }
  571. renderCheatsheetOverlay() {
  572. const cheatsheetModalButton = this.renderCheatsheetModalButton();
  573. return (
  574. <div className="overlay overlay-gfm-cheatsheet mt-1 p-3">
  575. { this.state.isSimpleCheatsheetShown
  576. ? (
  577. <div className="text-right">
  578. {cheatsheetModalButton}
  579. <div className="mb-2 d-none d-md-block">
  580. <SimpleCheatsheet />
  581. </div>
  582. </div>
  583. )
  584. : (
  585. <div className="mr-4 mb-2">
  586. {cheatsheetModalButton}
  587. </div>
  588. )
  589. }
  590. </div>
  591. );
  592. }
  593. renderEmojiPicker() {
  594. const { emojiSearchText } = this.state;
  595. return this.state.isEmojiPickerShown
  596. ? (
  597. <div className="text-left">
  598. <div className="mb-2 d-none d-md-block">
  599. <EmojiPicker
  600. onClose={() => this.setState({ isEmojiPickerShown: false })}
  601. emojiSearchText={emojiSearchText}
  602. emojiPickerHelper={this.emojiPickerHelper}
  603. isOpen={this.state.isEmojiPickerShown}
  604. />
  605. </div>
  606. </div>
  607. )
  608. : '';
  609. }
  610. /**
  611. * return a function to replace a selected range with prefix + selection + suffix
  612. *
  613. * The cursor after replacing is inserted between the selection and the suffix.
  614. */
  615. createReplaceSelectionHandler(prefix, suffix) {
  616. return () => {
  617. const cm = this.getCodeMirror();
  618. const selection = cm.getDoc().getSelection();
  619. const curStartPos = cm.getCursor('from');
  620. const curEndPos = cm.getCursor('to');
  621. const curPosAfterReplacing = {};
  622. curPosAfterReplacing.line = curEndPos.line;
  623. if (curStartPos.line === curEndPos.line) {
  624. curPosAfterReplacing.ch = curEndPos.ch + prefix.length;
  625. }
  626. else {
  627. curPosAfterReplacing.ch = curEndPos.ch;
  628. }
  629. cm.getDoc().replaceSelection(prefix + selection + suffix);
  630. cm.setCursor(curPosAfterReplacing);
  631. cm.focus();
  632. };
  633. }
  634. /**
  635. * return a function to add prefix to selected each lines
  636. *
  637. * The cursor after editing is inserted between the end of the selection.
  638. */
  639. createAddPrefixToEachLinesHandler(prefix) {
  640. return () => {
  641. const cm = this.getCodeMirror();
  642. const startLineNum = cm.getCursor('from').line;
  643. const endLineNum = cm.getCursor('to').line;
  644. const lines = [];
  645. for (let i = startLineNum; i <= endLineNum; i++) {
  646. lines.push(prefix + cm.getDoc().getLine(i));
  647. }
  648. const replacement = `${lines.join('\n')}\n`;
  649. cm.getDoc().replaceRange(replacement, { line: startLineNum, ch: 0 }, { line: endLineNum + 1, ch: 0 });
  650. cm.setCursor(endLineNum, cm.getDoc().getLine(endLineNum).length);
  651. cm.focus();
  652. };
  653. }
  654. /**
  655. * make a selected line a header
  656. *
  657. * The cursor after editing is inserted between the end of the line.
  658. */
  659. makeHeaderHandler() {
  660. const cm = this.getCodeMirror();
  661. const lineNum = cm.getCursor('from').line;
  662. const line = cm.getDoc().getLine(lineNum);
  663. let prefix = '#';
  664. if (!line.startsWith('#')) {
  665. prefix += ' ';
  666. }
  667. cm.getDoc().replaceRange(prefix, { line: lineNum, ch: 0 }, { line: lineNum, ch: 0 });
  668. cm.focus();
  669. }
  670. showGridEditorHandler() {
  671. this.gridEditModal.current.show(geu.getGridHtml(this.getCodeMirror()));
  672. }
  673. showLinkEditHandler() {
  674. this.linkEditModal.current.show(mlu.getMarkdownLink(this.getCodeMirror()));
  675. }
  676. showHandsonTableHandler() {
  677. this.handsontableModal.current.show(mtu.getMarkdownTable(this.getCodeMirror()));
  678. }
  679. showDrawioHandler() {
  680. this.drawioModal.current.show(mdu.getMarkdownDrawioMxfile(this.getCodeMirror()));
  681. }
  682. // fold draw.io section (::: drawio ~ :::)
  683. foldDrawioSection() {
  684. const editor = this.getCodeMirror();
  685. const lineNumbers = mdu.findAllDrawioSection(editor);
  686. lineNumbers.forEach((lineNumber) => {
  687. editor.foldCode({ line: lineNumber, ch: 0 }, { scanUp: false }, 'fold');
  688. });
  689. }
  690. onSaveForDrawio(drawioData) {
  691. const range = mdu.replaceFocusedDrawioWithEditor(this.getCodeMirror(), drawioData);
  692. // Fold the section after the drawio section (:::drawio) has been updated.
  693. this.foldDrawioSection();
  694. return range;
  695. }
  696. getNavbarItems() {
  697. return [
  698. <Button
  699. key="nav-item-bold"
  700. color={null}
  701. size="sm"
  702. title="Bold"
  703. onClick={this.createReplaceSelectionHandler('**', '**')}
  704. >
  705. <EditorIcon icon="Bold" />
  706. </Button>,
  707. <Button
  708. key="nav-item-italic"
  709. color={null}
  710. size="sm"
  711. title="Italic"
  712. onClick={this.createReplaceSelectionHandler('*', '*')}
  713. >
  714. <EditorIcon icon="Italic" />
  715. </Button>,
  716. <Button
  717. key="nav-item-strikethrough"
  718. color={null}
  719. size="sm"
  720. title="Strikethrough"
  721. onClick={this.createReplaceSelectionHandler('~~', '~~')}
  722. >
  723. <EditorIcon icon="Strikethrough" />
  724. </Button>,
  725. <Button
  726. key="nav-item-header"
  727. color={null}
  728. size="sm"
  729. title="Heading"
  730. onClick={this.makeHeaderHandler}
  731. >
  732. <EditorIcon icon="Heading" />
  733. </Button>,
  734. <Button
  735. key="nav-item-code"
  736. color={null}
  737. size="sm"
  738. title="Inline Code"
  739. onClick={this.createReplaceSelectionHandler('`', '`')}
  740. >
  741. <EditorIcon icon="InlineCode" />
  742. </Button>,
  743. <Button
  744. key="nav-item-quote"
  745. color={null}
  746. size="sm"
  747. title="Quote"
  748. onClick={this.createAddPrefixToEachLinesHandler('> ')}
  749. >
  750. <EditorIcon icon="Quote" />
  751. </Button>,
  752. <Button
  753. key="nav-item-ul"
  754. color={null}
  755. size="sm"
  756. title="List"
  757. onClick={this.createAddPrefixToEachLinesHandler('- ')}
  758. >
  759. <EditorIcon icon="List" />
  760. </Button>,
  761. <Button
  762. key="nav-item-ol"
  763. color={null}
  764. size="sm"
  765. title="Numbered List"
  766. onClick={this.createAddPrefixToEachLinesHandler('1. ')}
  767. >
  768. <EditorIcon icon="NumberedList" />
  769. </Button>,
  770. <Button
  771. key="nav-item-checkbox"
  772. color={null}
  773. size="sm"
  774. title="Check List"
  775. onClick={this.createAddPrefixToEachLinesHandler('- [ ] ')}
  776. >
  777. <EditorIcon icon="CheckList" />
  778. </Button>,
  779. <Button
  780. key="nav-item-attachment"
  781. color={null}
  782. size="sm"
  783. title="Attachment"
  784. onClick={this.props.onAddAttachmentButtonClicked}
  785. >
  786. <EditorIcon icon="Attachment" />
  787. </Button>,
  788. <Button
  789. key="nav-item-link"
  790. color={null}
  791. size="sm"
  792. title="Link"
  793. onClick={this.showLinkEditHandler}
  794. >
  795. <EditorIcon icon="Link" />
  796. </Button>,
  797. <Button
  798. key="nav-item-image"
  799. color={null}
  800. size="sm"
  801. title="Image"
  802. onClick={this.createReplaceSelectionHandler('![', ']()')}
  803. >
  804. <EditorIcon icon="Image" />
  805. </Button>,
  806. <Button
  807. key="nav-item-grid"
  808. color={null}
  809. size="sm"
  810. title="Grid"
  811. onClick={this.showGridEditorHandler}
  812. >
  813. <EditorIcon icon="Grid" />
  814. </Button>,
  815. <Button
  816. key="nav-item-table"
  817. color={null}
  818. size="sm"
  819. title="Table"
  820. onClick={this.showHandsonTableHandler}
  821. >
  822. <EditorIcon icon="Table" />
  823. </Button>,
  824. <Button
  825. key="nav-item-drawio"
  826. color={null}
  827. bssize="small"
  828. title="draw.io"
  829. onClick={this.showDrawioHandler}
  830. >
  831. <EditorIcon icon="Drawio" />
  832. </Button>,
  833. <Button
  834. key="nav-item-emoji"
  835. color={null}
  836. bssize="small"
  837. title="Emoji"
  838. onClick={() => this.setState({ isEmojiPickerShown: true })}
  839. >
  840. <EditorIcon icon="Emoji" />
  841. </Button>,
  842. ];
  843. }
  844. render() {
  845. const lint = this.props.isTextlintEnabled ? this.codemirrorLintConfig : false;
  846. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  847. const placeholder = this.state.isGfmMode ? 'Input with Markdown..' : 'Input with Plain Text..';
  848. const gutters = [];
  849. if (this.props.lineNumbers != null) {
  850. gutters.push('CodeMirror-linenumbers', 'CodeMirror-foldgutter');
  851. }
  852. if (this.props.isTextlintEnabled === true) {
  853. gutters.push('CodeMirror-lint-markers');
  854. }
  855. return (
  856. <React.Fragment>
  857. <UncontrolledCodeMirror
  858. ref={(c) => { this.cm = c }}
  859. className={additionalClasses}
  860. placeholder="search"
  861. editorDidMount={(editor) => {
  862. // add event handlers
  863. editor.on('paste', this.pasteHandler);
  864. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  865. }}
  866. value={this.state.value}
  867. options={{
  868. indentUnit: this.props.indentSize,
  869. lineWrapping: true,
  870. scrollPastEnd: true,
  871. autoRefresh: { force: true }, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  872. autoCloseTags: true,
  873. placeholder,
  874. matchBrackets: true,
  875. emoji: true,
  876. matchTags: { bothTags: true },
  877. // folding
  878. foldGutter: this.props.lineNumbers,
  879. gutters,
  880. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  881. highlightSelectionMatches: { annotateScrollbar: true },
  882. // continuelist, indentlist
  883. extraKeys: {
  884. Enter: this.handleEnterKey,
  885. 'Ctrl-Enter': this.handleCtrlEnterKey,
  886. 'Cmd-Enter': this.handleCtrlEnterKey,
  887. Tab: 'indentMore',
  888. 'Shift-Tab': 'indentLess',
  889. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  890. },
  891. lint,
  892. }}
  893. onCursor={this.cursorHandler}
  894. onScroll={(editor, data) => {
  895. if (this.props.onScroll != null) {
  896. // add line data
  897. const line = editor.lineAtHeight(data.top, 'local');
  898. data.line = line;
  899. this.props.onScroll(data);
  900. }
  901. }}
  902. onChange={this.changeHandler}
  903. onDragEnter={(editor, event) => {
  904. if (this.props.onDragEnter != null) {
  905. this.props.onDragEnter(event);
  906. }
  907. }}
  908. onKeyUp={this.keyUpHandler}
  909. />
  910. { this.renderLoadingKeymapOverlay() }
  911. { this.renderCheatsheetOverlay() }
  912. { this.renderEmojiPicker() }
  913. <GridEditModal
  914. ref={this.gridEditModal}
  915. onSave={(grid) => { return geu.replaceGridWithHtmlWithEditor(this.getCodeMirror(), grid) }}
  916. />
  917. <LinkEditModal
  918. ref={this.linkEditModal}
  919. onSave={(linkText) => { return mlu.replaceFocusedMarkdownLinkWithEditor(this.getCodeMirror(), linkText) }}
  920. />
  921. <HandsontableModal
  922. ref={this.handsontableModal}
  923. onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}
  924. ignoreAutoFormatting={this.props.editorOptions.ignoreMarkdownTableAutoFormatting}
  925. />
  926. <DrawioModal
  927. ref={this.drawioModal}
  928. onSave={this.onSaveForDrawio}
  929. />
  930. </React.Fragment>
  931. );
  932. }
  933. }
  934. CodeMirrorEditor.propTypes = Object.assign({
  935. editorOptions: PropTypes.object.isRequired,
  936. isTextlintEnabled: PropTypes.bool,
  937. textlintRules: PropTypes.array,
  938. lineNumbers: PropTypes.bool,
  939. onMarkdownHelpButtonClicked: PropTypes.func,
  940. onAddAttachmentButtonClicked: PropTypes.func,
  941. onInitializeTextlint: PropTypes.func,
  942. }, AbstractEditor.propTypes);
  943. CodeMirrorEditor.defaultProps = {
  944. lineNumbers: true,
  945. isTextlintEnabled: false,
  946. };