CodeMirrorEditor.js 14 KB

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