CodeMirrorEditor.js 14 KB

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