CodeMirrorEditor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. additionalClassSet: new Set(),
  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. // update state
  126. const additionalClassSet = this.state.additionalClassSet;
  127. this.setState({
  128. isGfmMode: bool,
  129. isEnabledEmojiAutoComplete: bool,
  130. additionalClassSet,
  131. });
  132. // update CodeMirror option
  133. const mode = bool ? 'gfm' : undefined;
  134. this.getCodeMirror().setOption('mode', mode);
  135. }
  136. /**
  137. * @inheritDoc
  138. */
  139. setCaretLine(line) {
  140. if (isNaN(line)) {
  141. return;
  142. }
  143. const editor = this.getCodeMirror();
  144. const linePosition = Math.max(0, line);
  145. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  146. this.setScrollTopByLine(linePosition);
  147. }
  148. /**
  149. * @inheritDoc
  150. */
  151. setScrollTopByLine(line) {
  152. if (isNaN(line)) {
  153. return;
  154. }
  155. const editor = this.getCodeMirror();
  156. // get top position of the line
  157. const top = editor.charCoords({line, ch: 0}, 'local').top;
  158. editor.scrollTo(null, top);
  159. }
  160. /**
  161. * @inheritDoc
  162. */
  163. getStrFromBol() {
  164. const editor = this.getCodeMirror();
  165. const curPos = editor.getCursor();
  166. return editor.getDoc().getRange(this.getBol(), curPos);
  167. }
  168. /**
  169. * @inheritDoc
  170. */
  171. getStrToEol() {
  172. const editor = this.getCodeMirror();
  173. const curPos = editor.getCursor();
  174. return editor.getDoc().getRange(curPos, this.getEol());
  175. }
  176. /**
  177. * @inheritDoc
  178. */
  179. getStrFromBolToSelectedUpperPos() {
  180. const editor = this.getCodeMirror();
  181. const pos = this.selectUpperPos(editor.getCursor('from'), editor.getCursor('to'));
  182. return editor.getDoc().getRange(this.getBol(), pos);
  183. }
  184. /**
  185. * @inheritDoc
  186. */
  187. replaceBolToCurrentPos(text) {
  188. const editor = this.getCodeMirror();
  189. const pos = this.selectLowerPos(editor.getCursor('from'), editor.getCursor('to'));
  190. editor.getDoc().replaceRange(text, this.getBol(), pos);
  191. }
  192. /**
  193. * @inheritDoc
  194. */
  195. insertText(text) {
  196. const editor = this.getCodeMirror();
  197. editor.getDoc().replaceSelection(text);
  198. }
  199. /**
  200. * return the postion of the BOL(beginning of line)
  201. */
  202. getBol() {
  203. const editor = this.getCodeMirror();
  204. const curPos = editor.getCursor();
  205. return { line: curPos.line, ch: 0 };
  206. }
  207. /**
  208. * return the postion of the EOL(end of line)
  209. */
  210. getEol() {
  211. const editor = this.getCodeMirror();
  212. const curPos = editor.getCursor();
  213. const lineLength = editor.getDoc().getLine(curPos.line).length;
  214. return { line: curPos.line, ch: lineLength };
  215. }
  216. /**
  217. * select the upper position of pos1 and pos2
  218. * @param {{line: number, ch: number}} pos1
  219. * @param {{line: number, ch: number}} pos2
  220. */
  221. selectUpperPos(pos1, pos2) {
  222. // if both is in same line
  223. if (pos1.line === pos2.line) {
  224. return (pos1.ch < pos2.ch) ? pos1 : pos2;
  225. }
  226. return (pos1.line < pos2.line) ? pos1 : pos2;
  227. }
  228. /**
  229. * select the lower position of pos1 and pos2
  230. * @param {{line: number, ch: number}} pos1
  231. * @param {{line: number, ch: number}} pos2
  232. */
  233. selectLowerPos(pos1, pos2) {
  234. // if both is in same line
  235. if (pos1.line === pos2.line) {
  236. return (pos1.ch < pos2.ch) ? pos2 : pos1;
  237. }
  238. return (pos1.line < pos2.line) ? pos2 : pos1;
  239. }
  240. loadCss(source) {
  241. return new Promise((resolve) => {
  242. loadCssSync(source);
  243. resolve();
  244. });
  245. }
  246. /**
  247. * load Theme
  248. * @see https://codemirror.net/doc/manual.html#config
  249. *
  250. * @param {string} theme
  251. */
  252. loadTheme(theme) {
  253. if (!this.loadedThemeSet.has(theme)) {
  254. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  255. // update Set
  256. this.loadedThemeSet.add(theme);
  257. }
  258. }
  259. /**
  260. * load assets for Key Maps
  261. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  262. */
  263. loadKeymapMode(keymapMode) {
  264. const loadCss = this.loadCss;
  265. let scriptList = [];
  266. let cssList = [];
  267. // add dependencies
  268. if (this.loadedKeymapSet.size == 0) {
  269. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  270. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  271. }
  272. // load keymap
  273. if (!this.loadedKeymapSet.has(keymapMode)) {
  274. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  275. // update Set
  276. this.loadedKeymapSet.add(keymapMode);
  277. }
  278. // set loading state
  279. this.setState({ isLoadingKeymap: true });
  280. return Promise.all(scriptList.concat(cssList))
  281. .then(() => {
  282. this.setState({ isLoadingKeymap: false });
  283. });
  284. }
  285. /**
  286. * set Key Maps
  287. * @see https://codemirror.net/doc/manual.html#keymaps
  288. *
  289. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  290. */
  291. setKeymapMode(keymapMode) {
  292. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  293. // reset
  294. this.getCodeMirror().setOption('keyMap', 'default');
  295. return;
  296. }
  297. this.loadKeymapMode(keymapMode)
  298. .then(() => {
  299. this.getCodeMirror().setOption('keyMap', keymapMode);
  300. });
  301. }
  302. /**
  303. * handle ENTER key
  304. */
  305. handleEnterKey() {
  306. if (!this.state.isGfmMode) {
  307. codemirror.commands.newlineAndIndent(this.getCodeMirror());
  308. return;
  309. }
  310. const context = {
  311. handlers: [], // list of handlers which process enter key
  312. editor: this,
  313. };
  314. const interceptorManager = this.interceptorManager;
  315. interceptorManager.process('preHandleEnter', context)
  316. .then(() => {
  317. if (context.handlers.length == 0) {
  318. codemirror.commands.newlineAndIndentContinueMarkdownList(this.getCodeMirror());
  319. }
  320. });
  321. }
  322. /**
  323. * handle Ctrl+ENTER key
  324. */
  325. handleCtrlEnterKey() {
  326. if (this.props.onCtrlEnter != null) {
  327. this.props.onCtrlEnter();
  328. }
  329. }
  330. scrollCursorIntoViewHandler(editor, event) {
  331. if (this.props.onScrollCursorIntoView != null) {
  332. const line = editor.getCursor().line;
  333. this.props.onScrollCursorIntoView(line);
  334. }
  335. }
  336. cursorHandler(editor, event) {
  337. const strFromBol = this.getStrFromBol();
  338. const autoformatTableClass = 'autoformat-markdown-table-activated';
  339. const additionalClassSet = this.state.additionalClassSet;
  340. const hasCustomClass = additionalClassSet.has(autoformatTableClass);
  341. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  342. if (!hasCustomClass) {
  343. additionalClassSet.add(autoformatTableClass);
  344. this.setState({additionalClassSet});
  345. }
  346. }
  347. else {
  348. if (hasCustomClass) {
  349. additionalClassSet.delete(autoformatTableClass);
  350. this.setState({additionalClassSet});
  351. }
  352. }
  353. }
  354. /**
  355. * CodeMirror paste event handler
  356. * see: https://codemirror.net/doc/manual.html#events
  357. * @param {any} editor An editor instance of CodeMirror
  358. * @param {any} event
  359. */
  360. pasteHandler(editor, event) {
  361. const types = event.clipboardData.types;
  362. // text
  363. if (types.includes('text/plain')) {
  364. pasteHelper.pasteText(this, event);
  365. }
  366. // files
  367. else if (types.includes('Files')) {
  368. this.dispatchPasteFiles(event);
  369. }
  370. }
  371. renderLoadingKeymapOverlay() {
  372. const style = {
  373. top: 0,
  374. right: 0,
  375. bottom: 0,
  376. left: 0,
  377. };
  378. return this.state.isLoadingKeymap
  379. ? <div className="overlay overlay-loading-keymap">
  380. <span style={style} className="overlay-content">
  381. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  382. </span>
  383. </div>
  384. : '';
  385. }
  386. render() {
  387. const mode = this.state.isGfmMode ? 'gfm' : undefined;
  388. const defaultEditorOptions = {
  389. theme: 'elegant',
  390. lineNumbers: true,
  391. };
  392. const additionalClasses = Array.from(this.state.additionalClassSet).join(' ');
  393. const editorOptions = Object.assign(defaultEditorOptions, this.props.editorOptions || {});
  394. return <React.Fragment>
  395. <ReactCodeMirror
  396. ref="cm"
  397. className={additionalClasses}
  398. placeholder="search"
  399. editorDidMount={(editor) => {
  400. // add event handlers
  401. editor.on('paste', this.pasteHandler);
  402. editor.on('scrollCursorIntoView', this.scrollCursorIntoViewHandler);
  403. }}
  404. value={this.state.value}
  405. options={{
  406. mode: mode,
  407. theme: editorOptions.theme,
  408. styleActiveLine: editorOptions.styleActiveLine,
  409. lineNumbers: this.props.lineNumbers,
  410. tabSize: 4,
  411. indentUnit: 4,
  412. lineWrapping: true,
  413. autoRefresh: {force: true}, // force option is enabled by autorefresh.ext.js -- Yuki Takei
  414. autoCloseTags: true,
  415. matchBrackets: true,
  416. matchTags: {bothTags: true},
  417. // folding
  418. foldGutter: this.props.lineNumbers,
  419. gutters: this.props.lineNumbers ? ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] : [],
  420. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  421. highlightSelectionMatches: {annotateScrollbar: true},
  422. // markdown mode options
  423. highlightFormatting: true,
  424. // continuelist, indentlist
  425. extraKeys: {
  426. 'Enter': this.handleEnterKey,
  427. 'Ctrl-Enter': this.handleCtrlEnterKey,
  428. 'Cmd-Enter': this.handleCtrlEnterKey,
  429. 'Tab': 'indentMore',
  430. 'Shift-Tab': 'indentLess',
  431. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  432. }
  433. }}
  434. onCursor={this.cursorHandler}
  435. onScroll={(editor, data) => {
  436. if (this.props.onScroll != null) {
  437. // add line data
  438. const line = editor.lineAtHeight(data.top, 'local');
  439. data.line = line;
  440. this.props.onScroll(data);
  441. }
  442. }}
  443. onChange={(editor, data, value) => {
  444. if (this.props.onChange != null) {
  445. this.props.onChange(value);
  446. }
  447. // Emoji AutoComplete
  448. if (this.state.isEnabledEmojiAutoComplete) {
  449. this.emojiAutoCompleteHelper.showHint(editor);
  450. }
  451. }}
  452. onDragEnter={(editor, event) => {
  453. if (this.props.onDragEnter != null) {
  454. this.props.onDragEnter(event);
  455. }
  456. }}
  457. />
  458. { this.renderLoadingKeymapOverlay() }
  459. </React.Fragment>;
  460. }
  461. }
  462. CodeMirrorEditor.propTypes = Object.assign({
  463. emojiStrategy: PropTypes.object,
  464. lineNumbers: PropTypes.bool,
  465. }, AbstractEditor.propTypes);
  466. CodeMirrorEditor.defaultProps = {
  467. lineNumbers: true,
  468. };