CodeMirrorEditor.js 12 KB

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