CodeMirrorEditor.js 14 KB

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