CodeMirrorEditor.js 13 KB

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