CodeMirrorEditor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import AbstractEditor from './AbstractEditor';
  4. import urljoin from 'url-join';
  5. const loadScript = require('simple-load-script');
  6. const loadCssSync = require('load-css-file');
  7. import * as codemirror from 'codemirror';
  8. // set save handler
  9. codemirror.commands.save = (instance) => {
  10. if (instance.codeMirrorEditor != null) {
  11. instance.codeMirrorEditor.dispatchSave();
  12. }
  13. };
  14. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  15. window.CodeMirror = require('codemirror');
  16. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  17. require('codemirror/addon/edit/matchbrackets');
  18. require('codemirror/addon/edit/matchtags');
  19. require('codemirror/addon/edit/closetag');
  20. require('codemirror/addon/edit/continuelist');
  21. require('codemirror/addon/hint/show-hint');
  22. require('codemirror/addon/hint/show-hint.css');
  23. require('codemirror/addon/search/searchcursor');
  24. require('codemirror/addon/search/match-highlighter');
  25. require('codemirror/addon/selection/active-line');
  26. require('codemirror/addon/scroll/annotatescrollbar');
  27. require('codemirror/addon/fold/foldcode');
  28. require('codemirror/addon/fold/foldgutter');
  29. require('codemirror/addon/fold/foldgutter.css');
  30. require('codemirror/addon/fold/markdown-fold');
  31. require('codemirror/addon/fold/brace-fold');
  32. require('codemirror/mode/gfm/gfm');
  33. require('../../util/codemirror/autorefresh.ext');
  34. import pasteHelper from './PasteHelper';
  35. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  36. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  37. import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
  38. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  39. import mtu from './MarkdownTableUtil';
  40. export default class CodeMirrorEditor extends AbstractEditor {
  41. constructor(props) {
  42. super(props);
  43. this.logger = require('@alias/logger')('growi:PageEditor:CodeMirrorEditor');
  44. this.state = {
  45. value: this.props.value,
  46. isGfmMode: this.props.isGfmMode,
  47. isEnabledEmojiAutoComplete: false,
  48. isLoadingKeymap: false,
  49. additionalClassSet: new Set(),
  50. };
  51. this.init();
  52. this.getCodeMirror = this.getCodeMirror.bind(this);
  53. this.getBol = this.getBol.bind(this);
  54. this.getEol = this.getEol.bind(this);
  55. this.loadTheme = this.loadTheme.bind(this);
  56. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  57. this.setKeymapMode = this.setKeymapMode.bind(this);
  58. this.handleEnterKey = this.handleEnterKey.bind(this);
  59. this.handleCtrlEnterKey = this.handleCtrlEnterKey.bind(this);
  60. this.scrollCursorIntoViewHandler = this.scrollCursorIntoViewHandler.bind(this);
  61. this.pasteHandler = this.pasteHandler.bind(this);
  62. this.cursorHandler = this.cursorHandler.bind(this);
  63. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  64. }
  65. init() {
  66. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  67. this.interceptorManager = new InterceptorManager();
  68. this.interceptorManager.addInterceptors([
  69. new PreventMarkdownListInterceptor(),
  70. new MarkdownTableInterceptor(),
  71. ]);
  72. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  73. this.loadedKeymapSet = new Set();
  74. }
  75. componentWillMount() {
  76. if (this.props.emojiStrategy != null) {
  77. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  78. this.setState({isEnabledEmojiAutoComplete: true});
  79. }
  80. }
  81. componentDidMount() {
  82. // ensure to be able to resolve 'this' to use 'codemirror.commands.save'
  83. this.getCodeMirror().codeMirrorEditor = this;
  84. // initialize caret line
  85. this.setCaretLine(0);
  86. }
  87. componentWillReceiveProps(nextProps) {
  88. // load theme
  89. const theme = nextProps.editorOptions.theme;
  90. this.loadTheme(theme);
  91. // set keymap
  92. const keymapMode = nextProps.editorOptions.keymapMode;
  93. this.setKeymapMode(keymapMode);
  94. }
  95. getCodeMirror() {
  96. return this.refs.cm.editor;
  97. }
  98. /**
  99. * @inheritDoc
  100. */
  101. forceToFocus() {
  102. const editor = this.getCodeMirror();
  103. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  104. const intervalId = setInterval(() => {
  105. this.getCodeMirror().focus();
  106. if (editor.hasFocus()) {
  107. clearInterval(intervalId);
  108. // refresh
  109. editor.refresh();
  110. }
  111. }, 100);
  112. }
  113. /**
  114. * @inheritDoc
  115. */
  116. setValue(newValue) {
  117. this.setState({ value: newValue });
  118. this.getCodeMirror().getDoc().setValue(newValue);
  119. }
  120. /**
  121. * @inheritDoc
  122. */
  123. setGfmMode(bool) {
  124. // update state
  125. const additionalClassSet = this.state.additionalClassSet;
  126. this.setState({
  127. isGfmMode: bool,
  128. isEnabledEmojiAutoComplete: bool,
  129. additionalClassSet,
  130. });
  131. // update CodeMirror option
  132. const mode = bool ? 'gfm' : undefined;
  133. this.getCodeMirror().setOption('mode', mode);
  134. }
  135. /**
  136. * @inheritDoc
  137. */
  138. setCaretLine(line) {
  139. if (isNaN(line)) {
  140. return;
  141. }
  142. const editor = this.getCodeMirror();
  143. const linePosition = Math.max(0, line);
  144. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  145. this.setScrollTopByLine(linePosition);
  146. }
  147. /**
  148. * @inheritDoc
  149. */
  150. setScrollTopByLine(line) {
  151. if (isNaN(line)) {
  152. return;
  153. }
  154. const editor = this.getCodeMirror();
  155. // get top position of the line
  156. const top = editor.charCoords({line, ch: 0}, 'local').top;
  157. editor.scrollTo(null, top);
  158. }
  159. /**
  160. * @inheritDoc
  161. */
  162. getStrFromBol() {
  163. const editor = this.getCodeMirror();
  164. const curPos = editor.getCursor();
  165. return editor.getDoc().getRange(this.getBol(), curPos);
  166. }
  167. /**
  168. * @inheritDoc
  169. */
  170. getStrToEol() {
  171. const editor = this.getCodeMirror();
  172. const curPos = editor.getCursor();
  173. return editor.getDoc().getRange(curPos, this.getEol());
  174. }
  175. /**
  176. * @inheritDoc
  177. */
  178. getStrFromBolToSelectedUpperPos() {
  179. const editor = this.getCodeMirror();
  180. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  181. return editor.getDoc().getRange(this.getBol(), pos);
  182. }
  183. /**
  184. * @inheritDoc
  185. */
  186. replaceBolToCurrentPos(text) {
  187. const editor = this.getCodeMirror();
  188. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  189. editor.getDoc().replaceRange(text, this.getBol(), pos);
  190. }
  191. /**
  192. * @inheritDoc
  193. */
  194. insertText(text) {
  195. const editor = this.getCodeMirror();
  196. editor.getDoc().replaceSelection(text);
  197. }
  198. /**
  199. * return the postion of the BOL(beginning of line)
  200. */
  201. getBol() {
  202. const editor = this.getCodeMirror();
  203. const curPos = editor.getCursor();
  204. return { line: curPos.line, ch: 0 };
  205. }
  206. /**
  207. * return the postion of the EOL(end of line)
  208. */
  209. getEol() {
  210. const editor = this.getCodeMirror();
  211. const curPos = editor.getCursor();
  212. const lineLength = editor.getDoc().getLine(curPos.line).length;
  213. return { line: curPos.line, ch: lineLength };
  214. }
  215. /**
  216. * select the upper position of pos1 and pos2
  217. * @param {{line: number, ch: number}} pos1
  218. * @param {{line: number, ch: number}} pos2
  219. */
  220. selectUpperPos(pos1, pos2) {
  221. // if both is in same line
  222. if (pos1.line === pos2.line) {
  223. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  224. }
  225. return (pos1.line < pos2.line) ? pos1 : pos2;
  226. }
  227. /**
  228. * select the lower position of pos1 and pos2
  229. * @param {{line: number, ch: number}} pos1
  230. * @param {{line: number, ch: number}} pos2
  231. */
  232. selectLowerPos(pos1, pos2) {
  233. // if both is in same line
  234. if (pos1.line === pos2.line) {
  235. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  236. }
  237. return (pos1.line < pos2.line) ? pos2 : pos1;
  238. }
  239. loadCss(source) {
  240. return new Promise((resolve) => {
  241. loadCssSync(source);
  242. resolve();
  243. });
  244. }
  245. /**
  246. * load Theme
  247. * @see https://codemirror.net/doc/manual.html#config
  248. *
  249. * @param {string} theme
  250. */
  251. loadTheme(theme) {
  252. if (!this.loadedThemeSet.has(theme)) {
  253. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  254. // update Set
  255. this.loadedThemeSet.add(theme);
  256. }
  257. }
  258. /**
  259. * load assets for Key Maps
  260. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  261. */
  262. loadKeymapMode(keymapMode) {
  263. const loadCss = this.loadCss;
  264. let scriptList = [];
  265. let cssList = [];
  266. // add dependencies
  267. if (this.loadedKeymapSet.size == 0) {
  268. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  269. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  270. }
  271. // load keymap
  272. if (!this.loadedKeymapSet.has(keymapMode)) {
  273. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  274. // update Set
  275. this.loadedKeymapSet.add(keymapMode);
  276. }
  277. // set loading state
  278. this.setState({ isLoadingKeymap: true });
  279. return Promise.all(scriptList.concat(cssList))
  280. .then(() => {
  281. this.setState({ isLoadingKeymap: false });
  282. });
  283. }
  284. /**
  285. * set Key Maps
  286. * @see https://codemirror.net/doc/manual.html#keymaps
  287. *
  288. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  289. */
  290. setKeymapMode(keymapMode) {
  291. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  292. // reset
  293. this.getCodeMirror().setOption('keyMap', 'default');
  294. return;
  295. }
  296. this.loadKeymapMode(keymapMode)
  297. .then(() => {
  298. this.getCodeMirror().setOption('keyMap', keymapMode);
  299. });
  300. }
  301. /**
  302. * handle ENTER key
  303. */
  304. handleEnterKey() {
  305. if (!this.state.isGfmMode) {
  306. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  307. return;
  308. }
  309. const context = {
  310. handlers: [], // list of handlers which process enter key
  311. editor: this,
  312. };
  313. const interceptorManager = this.interceptorManager;
  314. interceptorManager.process('preHandleEnter', context)
  315. .then(() => {
  316. if (context.handlers.length == 0) {
  317. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  318. }
  319. });
  320. }
  321. /**
  322. * handle Ctrl+ENTER key
  323. */
  324. handleCtrlEnterKey() {
  325. if (this.props.onCtrlEnter != null) {
  326. this.props.onCtrlEnter();
  327. }
  328. }
  329. scrollCursorIntoViewHandler(editor, event) {
  330. if (this.props.onScrollCursorIntoView != null) {
  331. const line = editor.getCursor().line;
  332. this.props.onScrollCursorIntoView(line);
  333. }
  334. }
  335. cursorHandler(editor, event) {
  336. const strFromBol = this.getStrFromBol();
  337. const autoformatTableClass = 'autoformat-markdown-table-activated';
  338. const additionalClassSet = this.state.additionalClassSet;
  339. const hasCustomClass = additionalClassSet.has(autoformatTableClass);
  340. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  341. if (!hasCustomClass) {
  342. additionalClassSet.add(autoformatTableClass);
  343. this.setState({additionalClassSet});
  344. }
  345. }
  346. else {
  347. if (hasCustomClass) {
  348. additionalClassSet.delete(autoformatTableClass);
  349. this.setState({additionalClassSet});
  350. }
  351. }
  352. }
  353. /**
  354. * CodeMirror paste event handler
  355. * see: https://codemirror.net/doc/manual.html#events
  356. * @param {any} editor An editor instance of CodeMirror
  357. * @param {any} event
  358. */
  359. pasteHandler(editor, event) {
  360. const types = event.clipboardData.types;
  361. // text
  362. if (types.includes('text/plain')) {
  363. pasteHelper.pasteText(this, event);
  364. }
  365. // files
  366. else if (types.includes('Files')) {
  367. this.dispatchPasteFiles(event);
  368. }
  369. }
  370. renderLoadingKeymapOverlay() {
  371. const style = {
  372. top: 0,
  373. right: 0,
  374. bottom: 0,
  375. left: 0,
  376. };
  377. return this.state.isLoadingKeymap
  378. ? <div className="overlay overlay-loading-keymap">
  379. <span style={style} className="overlay-content">
  380. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  381. </span>
  382. </div>
  383. : '';
  384. }
  385. render() {
  386. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  387. const defaultEditorOptions = {
  388. theme: 'elegant',
  389. lineNumbers: true,
  390. };
  391. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  392. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  393. return <React.Fragment>
  394. <ReactCodeMirror
  395. ref="cm"
  396. className={additionalClasses}
  397. editorDidMount={(editor) => {
  398. // add event handlers
  399. editor.on('paste', this.pasteHandler);
  400. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  401. }}
  402. value={this.state.value}
  403. options={{
  404. mode: mode,
  405. theme: editorOptions.theme,
  406. styleActiveLine: editorOptions.styleActiveLine,
  407. lineNumbers: this.props.lineNumbers,
  408. tabSize: 4,
  409. indentUnit: 4,
  410. lineWrapping: true,
  411. autoRefresh: {force: true}, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  412. autoCloseTags: true,
  413. matchBrackets: true,
  414. matchTags: {bothTags: true},
  415. // folding
  416. foldGutter: this.props.lineNumbers,
  417. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  418. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  419. highlightSelectionMatches: {annotateScrollbar: true},
  420. // markdown mode options
  421. highlightFormatting: true,
  422. // continuelist, indentlist
  423. extraKeys: {
  424. 'Enter': this.handleEnterKey,
  425. 'Ctrl-Enter': this.handleCtrlEnterKey,
  426. 'Cmd-Enter': this.handleCtrlEnterKey,
  427. 'Tab': 'indentMore',
  428. 'Shift-Tab': 'indentLess',
  429. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  430. }
  431. }}
  432. onCursor={this.cursorHandler}
  433. onScroll={(editor, data) => {
  434. if (this.props.onScroll != null) {
  435. // add line data
  436. const line = editor.lineAtHeight(data.top, 'local');
  437. data.line = line;
  438. this.props.onScroll(data);
  439. }
  440. }}
  441. onChange={(editor, data, value) => {
  442. if (this.props.onChange != null) {
  443. this.props.onChange(value);
  444. }
  445. // Emoji AutoComplete
  446. if (this.state.isEnabledEmojiAutoComplete) {
  447. this.emojiAutoCompleteHelper.showHint(editor);
  448. }
  449. }}
  450. onDragEnter={(editor, event) => {
  451. if (this.props.onDragEnter != null) {
  452. this.props.onDragEnter(event);
  453. }
  454. }}
  455. />
  456. { this.renderLoadingKeymapOverlay() }
  457. </React.Fragment>;
  458. }
  459. }
  460. CodeMirrorEditor.propTypes = Object.assign({
  461. emojiStrategy: PropTypes.object,
  462. lineNumbers: PropTypes.bool,
  463. }, AbstractEditor.propTypes);
  464. CodeMirrorEditor.defaultProps = {
  465. lineNumbers: true,
  466. };