CodeMirrorEditor.jsx 31 KB

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