CodeMirrorEditor.js 13 KB

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