CodeMirrorEditor.js 12 KB

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