CodeMirrorEditor.js 16 KB

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