CodeMirrorEditor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. * return the postion of the BOL(beginning of line)
  164. */
  165. getBol() {
  166. const editor = this.getCodeMirror();
  167. const curPos = editor.getCursor();
  168. return { line: curPos.line, ch: 0 };
  169. }
  170. /**
  171. * return the postion of the EOL(end of line)
  172. */
  173. getEol() {
  174. const editor = this.getCodeMirror();
  175. const curPos = editor.getCursor();
  176. const lineLength = editor.getDoc().getLine(curPos.line).length;
  177. return { line: curPos.line, ch: lineLength };
  178. }
  179. insertLinebreak(strToEol) {
  180. const editor = this.getCodeMirror();
  181. codemirror.commands.newlineAndIndent(editor);
  182. // replace the line with strToEol (abort auto indent)
  183. editor.getDoc().replaceRange(strToEol, this.getBol(), this.getEol());
  184. }
  185. loadCss(source) {
  186. return new Promise((resolve) => {
  187. loadCssSync(source);
  188. resolve();
  189. });
  190. }
  191. /**
  192. * load Theme
  193. * @see https://codemirror.net/doc/manual.html#config
  194. *
  195. * @param {string} theme
  196. */
  197. loadTheme(theme) {
  198. if (!this.loadedThemeSet.has(theme)) {
  199. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  200. // update Set
  201. this.loadedThemeSet.add(theme);
  202. }
  203. }
  204. /**
  205. * load assets for Key Maps
  206. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  207. */
  208. loadKeymapMode(keymapMode) {
  209. const loadCss = this.loadCss;
  210. let scriptList = [];
  211. let cssList = [];
  212. // add dependencies
  213. if (this.loadedKeymapSet.size == 0) {
  214. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  215. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  216. }
  217. // load keymap
  218. if (!this.loadedKeymapSet.has(keymapMode)) {
  219. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  220. // update Set
  221. this.loadedKeymapSet.add(keymapMode);
  222. }
  223. // set loading state
  224. this.setState({ isLoadingKeymap: true });
  225. return Promise.all(scriptList.concat(cssList))
  226. .then(() => {
  227. this.setState({ isLoadingKeymap: false });
  228. });
  229. }
  230. /**
  231. * set Key Maps
  232. * @see https://codemirror.net/doc/manual.html#keymaps
  233. *
  234. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  235. */
  236. setKeymapMode(keymapMode) {
  237. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  238. // reset
  239. this.getCodeMirror().setOption('keyMap', 'default');
  240. return;
  241. }
  242. this.loadKeymapMode(keymapMode)
  243. .then(() => {
  244. this.getCodeMirror().setOption('keyMap', keymapMode);
  245. });
  246. }
  247. /**
  248. * handle ENTER key
  249. */
  250. handleEnterKey() {
  251. // TODO refactor
  252. // input both of AbstractEditor and CodeMirror
  253. var context = {
  254. handlers: [], // list of handlers which process enter key
  255. editor: this,
  256. };
  257. const interceptorManager = this.interceptorManager;
  258. interceptorManager.process('preHandleEnter', context)
  259. .then(() => {
  260. if (context.handlers.length == 0) {
  261. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  262. }
  263. });
  264. }
  265. scrollCursorIntoViewHandler(editor, event) {
  266. if (this.props.onScrollCursorIntoView != null) {
  267. const line = editor.getCursor().line;
  268. this.props.onScrollCursorIntoView(line);
  269. }
  270. }
  271. /**
  272. * CodeMirror paste event handler
  273. * see: https://codemirror.net/doc/manual.html#events
  274. * @param {any} editor An editor instance of CodeMirror
  275. * @param {any} event
  276. */
  277. pasteHandler(editor, event) {
  278. const types = event.clipboardData.types;
  279. // text
  280. if (types.includes('text/plain')) {
  281. // TODO refactor
  282. // pasteHelper.pasteText(editor, event);
  283. }
  284. // files
  285. else if (types.includes('Files')) {
  286. this.dispatchPasteFiles(event);
  287. }
  288. }
  289. dispatchPasteFiles(event) {
  290. if (this.props.onPasteFiles != null) {
  291. this.props.onPasteFiles(event);
  292. }
  293. }
  294. getOverlayStyle() {
  295. return {
  296. position: 'absolute',
  297. zIndex: 4, // forward than .CodeMirror-gutters
  298. top: 0,
  299. right: 0,
  300. bottom: 0,
  301. left: 0,
  302. };
  303. }
  304. renderLoadingKeymapOverlay() {
  305. const overlayStyle = this.getOverlayStyle();
  306. return this.state.isLoadingKeymap
  307. ? <div style={overlayStyle} className="loading-keymap overlay">
  308. <span className="overlay-content">
  309. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  310. </span>
  311. </div>
  312. : '';
  313. }
  314. render() {
  315. const theme = this.props.editorOptions.theme || 'elegant';
  316. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  317. return <React.Fragment>
  318. <ReactCodeMirror
  319. ref="cm"
  320. editorDidMount={(editor) => {
  321. // add event handlers
  322. editor.on('paste', this.pasteHandler);
  323. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  324. }}
  325. value={this.state.value}
  326. options={{
  327. mode: 'gfm',
  328. theme: theme,
  329. styleActiveLine: styleActiveLine,
  330. lineNumbers: true,
  331. tabSize: 4,
  332. indentUnit: 4,
  333. lineWrapping: true,
  334. autoRefresh: true,
  335. autoCloseTags: true,
  336. matchBrackets: true,
  337. matchTags: {bothTags: true},
  338. // folding
  339. foldGutter: true,
  340. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
  341. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  342. highlightSelectionMatches: {annotateScrollbar: true},
  343. // markdown mode options
  344. highlightFormatting: true,
  345. // continuelist, indentlist
  346. extraKeys: {
  347. 'Enter': this.handleEnterKey,
  348. 'Tab': 'indentMore',
  349. 'Shift-Tab': 'indentLess',
  350. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  351. }
  352. }}
  353. onScroll={(editor, data) => {
  354. if (this.props.onScroll != null) {
  355. // add line data
  356. const line = editor.lineAtHeight(data.top, 'local');
  357. data.line = line;
  358. this.props.onScroll(data);
  359. }
  360. }}
  361. onChange={(editor, data, value) => {
  362. if (this.props.onChange != null) {
  363. this.props.onChange(value);
  364. }
  365. // Emoji AutoComplete
  366. if (this.state.isEnabledEmojiAutoComplete) {
  367. this.emojiAutoCompleteHelper.showHint(editor);
  368. }
  369. }}
  370. onDragEnter={(editor, event) => {
  371. if (this.props.onDragEnter != null) {
  372. this.props.onDragEnter(event);
  373. }
  374. }}
  375. />
  376. { this.renderLoadingKeymapOverlay() }
  377. </React.Fragment>;
  378. }
  379. }
  380. CodeMirrorEditor.propTypes = Object.assign({
  381. emojiStrategy: PropTypes.object,
  382. onDragEnter: PropTypes.func,
  383. }, AbstractEditor.propTypes);