CodeMirrorEditor.js 12 KB

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