CodeMirrorEditor.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. additionalClass: '',
  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. this.setState({
  125. isGfmMode: bool,
  126. isEnabledEmojiAutoComplete: bool,
  127. });
  128. const mode = bool ? 'gfm' : undefined;
  129. this.getCodeMirror().setOption('mode', mode);
  130. }
  131. /**
  132. * @inheritDoc
  133. */
  134. setCaretLine(line) {
  135. if (isNaN(line)) {
  136. return;
  137. }
  138. const editor = this.getCodeMirror();
  139. const linePosition = Math.max(0, line);
  140. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  141. this.setScrollTopByLine(linePosition);
  142. }
  143. /**
  144. * @inheritDoc
  145. */
  146. setScrollTopByLine(line) {
  147. if (isNaN(line)) {
  148. return;
  149. }
  150. const editor = this.getCodeMirror();
  151. // get top position of the line
  152. const top = editor.charCoords({line, ch: 0}, 'local').top;
  153. editor.scrollTo(null, top);
  154. }
  155. /**
  156. * @inheritDoc
  157. */
  158. getStrFromBol() {
  159. const editor = this.getCodeMirror();
  160. const curPos = editor.getCursor();
  161. return editor.getDoc().getRange(this.getBol(), curPos);
  162. }
  163. /**
  164. * @inheritDoc
  165. */
  166. getStrToEol() {
  167. const editor = this.getCodeMirror();
  168. const curPos = editor.getCursor();
  169. return editor.getDoc().getRange(curPos, this.getEol());
  170. }
  171. /**
  172. * @inheritDoc
  173. */
  174. getStrFromBolToSelectedUpperPos() {
  175. const editor = this.getCodeMirror();
  176. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  177. return editor.getDoc().getRange(this.getBol(), pos);
  178. }
  179. /**
  180. * @inheritDoc
  181. */
  182. replaceBolToCurrentPos(text) {
  183. const editor = this.getCodeMirror();
  184. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  185. editor.getDoc().replaceRange(text, this.getBol(), pos);
  186. }
  187. /**
  188. * @inheritDoc
  189. */
  190. insertText(text) {
  191. const editor = this.getCodeMirror();
  192. editor.getDoc().replaceSelection(text);
  193. }
  194. /**
  195. * return the postion of the BOL(beginning of line)
  196. */
  197. getBol() {
  198. const editor = this.getCodeMirror();
  199. const curPos = editor.getCursor();
  200. return { line: curPos.line, ch: 0 };
  201. }
  202. /**
  203. * return the postion of the EOL(end of line)
  204. */
  205. getEol() {
  206. const editor = this.getCodeMirror();
  207. const curPos = editor.getCursor();
  208. const lineLength = editor.getDoc().getLine(curPos.line).length;
  209. return { line: curPos.line, ch: lineLength };
  210. }
  211. /**
  212. * select the upper position of pos1 and pos2
  213. * @param {{line: number, ch: number}} pos1
  214. * @param {{line: number, ch: number}} pos2
  215. */
  216. selectUpperPos(pos1, pos2) {
  217. // if both is in same line
  218. if (pos1.line === pos2.line) {
  219. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  220. }
  221. return (pos1.line < pos2.line) ? pos1 : pos2;
  222. }
  223. /**
  224. * select the lower position of pos1 and pos2
  225. * @param {{line: number, ch: number}} pos1
  226. * @param {{line: number, ch: number}} pos2
  227. */
  228. selectLowerPos(pos1, pos2) {
  229. // if both is in same line
  230. if (pos1.line === pos2.line) {
  231. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  232. }
  233. return (pos1.line < pos2.line) ? pos2 : pos1;
  234. }
  235. loadCss(source) {
  236. return new Promise((resolve) => {
  237. loadCssSync(source);
  238. resolve();
  239. });
  240. }
  241. /**
  242. * load Theme
  243. * @see https://codemirror.net/doc/manual.html#config
  244. *
  245. * @param {string} theme
  246. */
  247. loadTheme(theme) {
  248. if (!this.loadedThemeSet.has(theme)) {
  249. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  250. // update Set
  251. this.loadedThemeSet.add(theme);
  252. }
  253. }
  254. /**
  255. * load assets for Key Maps
  256. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  257. */
  258. loadKeymapMode(keymapMode) {
  259. const loadCss = this.loadCss;
  260. let scriptList = [];
  261. let cssList = [];
  262. // add dependencies
  263. if (this.loadedKeymapSet.size == 0) {
  264. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  265. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  266. }
  267. // load keymap
  268. if (!this.loadedKeymapSet.has(keymapMode)) {
  269. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  270. // update Set
  271. this.loadedKeymapSet.add(keymapMode);
  272. }
  273. // set loading state
  274. this.setState({ isLoadingKeymap: true });
  275. return Promise.all(scriptList.concat(cssList))
  276. .then(() => {
  277. this.setState({ isLoadingKeymap: false });
  278. });
  279. }
  280. /**
  281. * set Key Maps
  282. * @see https://codemirror.net/doc/manual.html#keymaps
  283. *
  284. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  285. */
  286. setKeymapMode(keymapMode) {
  287. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  288. // reset
  289. this.getCodeMirror().setOption('keyMap', 'default');
  290. return;
  291. }
  292. this.loadKeymapMode(keymapMode)
  293. .then(() => {
  294. this.getCodeMirror().setOption('keyMap', keymapMode);
  295. });
  296. }
  297. /**
  298. * handle ENTER key
  299. */
  300. handleEnterKey() {
  301. if (!this.state.isGfmMode) {
  302. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  303. return;
  304. }
  305. const context = {
  306. handlers: [], // list of handlers which process enter key
  307. editor: this,
  308. };
  309. const interceptorManager = this.interceptorManager;
  310. interceptorManager.process('preHandleEnter', context)
  311. .then(() => {
  312. if (context.handlers.length == 0) {
  313. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  314. }
  315. });
  316. }
  317. /**
  318. * handle Ctrl+ENTER key
  319. */
  320. handleCtrlEnterKey() {
  321. if (this.props.onCtrlEnter != null) {
  322. this.props.onCtrlEnter();
  323. }
  324. }
  325. scrollCursorIntoViewHandler(editor, event) {
  326. if (this.props.onScrollCursorIntoView != null) {
  327. const line = editor.getCursor().line;
  328. this.props.onScrollCursorIntoView(line);
  329. }
  330. }
  331. cursorHandler(editor, event) {
  332. const strFromBol = this.getStrFromBol();
  333. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  334. this.setState({additionalClass: 'autoformat-markdown-table-activated'});
  335. }
  336. else {
  337. this.setState({additionalClass: ''});
  338. }
  339. }
  340. /**
  341. * CodeMirror paste event handler
  342. * see: https://codemirror.net/doc/manual.html#events
  343. * @param {any} editor An editor instance of CodeMirror
  344. * @param {any} event
  345. */
  346. pasteHandler(editor, event) {
  347. const types = event.clipboardData.types;
  348. // text
  349. if (types.includes('text/plain')) {
  350. pasteHelper.pasteText(this, event);
  351. }
  352. // files
  353. else if (types.includes('Files')) {
  354. this.dispatchPasteFiles(event);
  355. }
  356. }
  357. getOverlayStyle() {
  358. return {
  359. position: 'absolute',
  360. zIndex: 4, // forward than .CodeMirror-gutters
  361. top: 0,
  362. right: 0,
  363. bottom: 0,
  364. left: 0,
  365. };
  366. }
  367. renderLoadingKeymapOverlay() {
  368. const overlayStyle = this.getOverlayStyle();
  369. return this.state.isLoadingKeymap
  370. ? <div style={overlayStyle} className="loading-keymap overlay">
  371. <span className="overlay-content">
  372. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  373. </span>
  374. </div>
  375. : '';
  376. }
  377. render() {
  378. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  379. const defaultEditorOptions = {
  380. theme: 'elegant',
  381. lineNumbers: true,
  382. };
  383. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  384. return <React.Fragment>
  385. <ReactCodeMirror
  386. ref="cm"
  387. className={this.state.additionalClass}
  388. editorDidMount={(editor) => {
  389. // add event handlers
  390. editor.on('paste', this.pasteHandler);
  391. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  392. }}
  393. value={this.state.value}
  394. options={{
  395. mode: mode,
  396. theme: editorOptions.theme,
  397. styleActiveLine: editorOptions.styleActiveLine,
  398. lineNumbers: this.props.lineNumbers,
  399. tabSize: 4,
  400. indentUnit: 4,
  401. lineWrapping: true,
  402. autoRefresh: {force: true}, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  403. autoCloseTags: true,
  404. matchBrackets: true,
  405. matchTags: {bothTags: true},
  406. // folding
  407. foldGutter: this.props.lineNumbers,
  408. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  409. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  410. highlightSelectionMatches: {annotateScrollbar: true},
  411. // markdown mode options
  412. highlightFormatting: true,
  413. // continuelist, indentlist
  414. extraKeys: {
  415. 'Enter': this.handleEnterKey,
  416. 'Ctrl-Enter': this.handleCtrlEnterKey,
  417. 'Cmd-Enter': this.handleCtrlEnterKey,
  418. 'Tab': 'indentMore',
  419. 'Shift-Tab': 'indentLess',
  420. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  421. }
  422. }}
  423. onCursor={this.cursorHandler}
  424. onScroll={(editor, data) => {
  425. if (this.props.onScroll != null) {
  426. // add line data
  427. const line = editor.lineAtHeight(data.top, 'local');
  428. data.line = line;
  429. this.props.onScroll(data);
  430. }
  431. }}
  432. onChange={(editor, data, value) => {
  433. if (this.props.onChange != null) {
  434. this.props.onChange(value);
  435. }
  436. // Emoji AutoComplete
  437. if (this.state.isEnabledEmojiAutoComplete) {
  438. this.emojiAutoCompleteHelper.showHint(editor);
  439. }
  440. }}
  441. onDragEnter={(editor, event) => {
  442. if (this.props.onDragEnter != null) {
  443. this.props.onDragEnter(event);
  444. }
  445. }}
  446. />
  447. { this.renderLoadingKeymapOverlay() }
  448. </React.Fragment>;
  449. }
  450. }
  451. CodeMirrorEditor.propTypes = Object.assign({
  452. emojiStrategy: PropTypes.object,
  453. lineNumbers: PropTypes.bool,
  454. }, AbstractEditor.propTypes);
  455. CodeMirrorEditor.defaultProps = {
  456. lineNumbers: true,
  457. };