CodeMirrorEditor.js 12 KB

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