Editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import urljoin from 'url-join';
  4. const loadScript = require('simple-load-script');
  5. const loadCssSync = require('load-css-file');
  6. import * as codemirror from 'codemirror';
  7. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  8. require('codemirror/addon/display/autorefresh');
  9. require('codemirror/addon/edit/matchbrackets');
  10. require('codemirror/addon/edit/matchtags');
  11. require('codemirror/addon/edit/closetag');
  12. require('codemirror/addon/edit/continuelist');
  13. require('codemirror/addon/hint/show-hint');
  14. require('codemirror/addon/hint/show-hint.css');
  15. require('codemirror/addon/search/searchcursor');
  16. require('codemirror/addon/search/match-highlighter');
  17. require('codemirror/addon/selection/active-line');
  18. require('codemirror/addon/scroll/annotatescrollbar');
  19. require('codemirror/addon/fold/foldcode');
  20. require('codemirror/addon/fold/foldgutter');
  21. require('codemirror/addon/fold/foldgutter.css');
  22. require('codemirror/addon/fold/markdown-fold');
  23. require('codemirror/addon/fold/brace-fold');
  24. require('codemirror/mode/gfm/gfm');
  25. import Dropzone from 'react-dropzone';
  26. import pasteHelper from './PasteHelper';
  27. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  28. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  29. import MarkdownListInterceptor from './MarkdownListInterceptor';
  30. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  31. export default class Editor extends React.Component {
  32. constructor(props) {
  33. super(props);
  34. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  35. this.interceptorManager = new InterceptorManager();
  36. this.interceptorManager.addInterceptors([
  37. new MarkdownListInterceptor(),
  38. new MarkdownTableInterceptor(),
  39. ]);
  40. this.state = {
  41. value: this.props.value,
  42. dropzoneActive: false,
  43. isEnabledEmojiAutoComplete: false,
  44. isUploading: false,
  45. isLoadingKeymap: false,
  46. };
  47. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  48. this.loadedKeymapSet = new Set();
  49. this.getCodeMirror = this.getCodeMirror.bind(this);
  50. this.setCaretLine = this.setCaretLine.bind(this);
  51. this.setScrollTopByLine = this.setScrollTopByLine.bind(this);
  52. this.loadTheme = this.loadTheme.bind(this);
  53. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  54. this.setKeymapMode = this.setKeymapMode.bind(this);
  55. this.forceToFocus = this.forceToFocus.bind(this);
  56. this.dispatchSave = this.dispatchSave.bind(this);
  57. this.handleEnterKey = this.handleEnterKey.bind(this);
  58. this.onScrollCursorIntoView = this.onScrollCursorIntoView.bind(this);
  59. this.onPaste = this.onPaste.bind(this);
  60. this.onDragEnterForCM = this.onDragEnterForCM.bind(this);
  61. this.onDragLeave = this.onDragLeave.bind(this);
  62. this.onDrop = this.onDrop.bind(this);
  63. this.getDropzoneAccept = this.getDropzoneAccept.bind(this);
  64. this.getDropzoneClassName = this.getDropzoneClassName.bind(this);
  65. this.renderDropzoneOverlay = this.renderDropzoneOverlay.bind(this);
  66. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  67. }
  68. componentWillMount() {
  69. if (this.props.emojiStrategy != null) {
  70. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  71. this.setState({isEnabledEmojiAutoComplete: true});
  72. }
  73. }
  74. componentDidMount() {
  75. // initialize caret line
  76. this.setCaretLine(0);
  77. // set save handler
  78. codemirror.commands.save = this.dispatchSave;
  79. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  80. window.CodeMirror = require('codemirror');
  81. }
  82. componentWillReceiveProps(nextProps) {
  83. // load theme
  84. const theme = nextProps.editorOptions.theme;
  85. this.loadTheme(theme);
  86. // set keymap
  87. const keymapMode = nextProps.editorOptions.keymapMode;
  88. this.setKeymapMode(keymapMode);
  89. }
  90. getCodeMirror() {
  91. return this.refs.cm.editor;
  92. }
  93. loadCss(source) {
  94. return new Promise((resolve) => {
  95. loadCssSync(source);
  96. resolve();
  97. });
  98. }
  99. forceToFocus() {
  100. const editor = this.getCodeMirror();
  101. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  102. const intervalId = setInterval(() => {
  103. this.getCodeMirror().focus();
  104. if (editor.hasFocus()) {
  105. clearInterval(intervalId);
  106. // refresh
  107. editor.refresh();
  108. }
  109. }, 100);
  110. }
  111. /**
  112. * set caret position of codemirror
  113. * @param {string} number
  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. * scroll
  126. * @param {number} line
  127. */
  128. setScrollTopByLine(line) {
  129. if (isNaN(line)) {
  130. return;
  131. }
  132. const editor = this.getCodeMirror();
  133. // get top position of the line
  134. var top = editor.charCoords({line, ch: 0}, 'local').top;
  135. editor.scrollTo(null, top);
  136. }
  137. /**
  138. * load Theme
  139. * @see https://codemirror.net/doc/manual.html#config
  140. *
  141. * @param {string} theme
  142. */
  143. loadTheme(theme) {
  144. if (!this.loadedThemeSet.has(theme)) {
  145. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  146. // update Set
  147. this.loadedThemeSet.add(theme);
  148. }
  149. }
  150. /**
  151. * load assets for Key Maps
  152. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  153. */
  154. loadKeymapMode(keymapMode) {
  155. const loadCss = this.loadCss;
  156. let scriptList = [];
  157. let cssList = [];
  158. // add dependencies
  159. if (this.loadedKeymapSet.size == 0) {
  160. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  161. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  162. }
  163. // load keymap
  164. if (!this.loadedKeymapSet.has(keymapMode)) {
  165. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  166. // update Set
  167. this.loadedKeymapSet.add(keymapMode);
  168. }
  169. // set loading state
  170. this.setState({ isLoadingKeymap: true });
  171. return Promise.all(scriptList.concat(cssList))
  172. .then(() => {
  173. this.setState({ isLoadingKeymap: false });
  174. });
  175. }
  176. /**
  177. * set Key Maps
  178. * @see https://codemirror.net/doc/manual.html#keymaps
  179. *
  180. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  181. */
  182. setKeymapMode(keymapMode) {
  183. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  184. // reset
  185. this.getCodeMirror().setOption('keyMap', 'default');
  186. return;
  187. }
  188. this.loadKeymapMode(keymapMode)
  189. .then(() => {
  190. this.getCodeMirror().setOption('keyMap', keymapMode);
  191. });
  192. }
  193. /**
  194. * remove overlay and set isUploading to false
  195. */
  196. terminateUploadingState() {
  197. this.setState({
  198. dropzoneActive: false,
  199. isUploading: false,
  200. });
  201. }
  202. /**
  203. * insert text
  204. * @param {string} text
  205. */
  206. insertText(text) {
  207. const editor = this.getCodeMirror();
  208. editor.getDoc().replaceSelection(text);
  209. }
  210. /**
  211. * dispatch onSave event
  212. */
  213. dispatchSave() {
  214. if (this.props.onSave != null) {
  215. this.props.onSave();
  216. }
  217. }
  218. /**
  219. * dispatch onUpload event
  220. */
  221. dispatchUpload(files) {
  222. if (this.props.onUpload != null) {
  223. this.props.onUpload(files);
  224. }
  225. }
  226. /**
  227. * handle ENTER key
  228. */
  229. handleEnterKey() {
  230. const editor = this.getCodeMirror();
  231. var context = {
  232. handlers: [], // list of handlers which process enter key
  233. editor: editor,
  234. };
  235. const interceptorManager = this.interceptorManager;
  236. interceptorManager.process('preHandleEnter', context)
  237. .then(() => {
  238. if (context.handlers.length == 0) {
  239. codemirror.commands.newlineAndIndentContinueMarkdownList(editor);
  240. }
  241. });
  242. }
  243. onScrollCursorIntoView(editor, event) {
  244. if (this.props.onScrollCursorIntoView != null) {
  245. const line = editor.getCursor().line;
  246. this.props.onScrollCursorIntoView(line);
  247. }
  248. }
  249. /**
  250. * CodeMirror paste event handler
  251. * see: https://codemirror.net/doc/manual.html#events
  252. * @param {any} editor An editor instance of CodeMirror
  253. * @param {any} event
  254. */
  255. onPaste(editor, event) {
  256. const types = event.clipboardData.types;
  257. // text
  258. if (types.includes('text/plain')) {
  259. pasteHelper.pasteText(editor, event);
  260. }
  261. // files
  262. else if (types.includes('Files')) {
  263. const dropzone = this.refs.dropzone;
  264. const items = event.clipboardData.items || event.clipboardData.files || [];
  265. // abort if length is not 1
  266. if (items.length != 1) {
  267. return;
  268. }
  269. const file = items[0].getAsFile();
  270. // check type and size
  271. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  272. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  273. this.dispatchUpload(file);
  274. this.setState({ isUploading: true });
  275. }
  276. }
  277. }
  278. onDragEnterForCM(editor, event) {
  279. const dataTransfer = event.dataTransfer;
  280. // do nothing if contents is not files
  281. if (!dataTransfer.types.includes('Files')) {
  282. return;
  283. }
  284. this.setState({ dropzoneActive: true });
  285. }
  286. onDragLeave() {
  287. this.setState({ dropzoneActive: false });
  288. }
  289. onDrop(accepted, rejected) {
  290. // rejected
  291. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  292. this.setState({ dropzoneActive: false });
  293. return;
  294. }
  295. const file = accepted[0];
  296. this.dispatchUpload(file);
  297. this.setState({ isUploading: true });
  298. }
  299. getDropzoneAccept() {
  300. let accept = 'null'; // reject all
  301. if (this.props.isUploadable) {
  302. if (!this.props.isUploadableFile) {
  303. accept = 'image/*'; // image only
  304. }
  305. else {
  306. accept = ''; // allow all
  307. }
  308. }
  309. return accept;
  310. }
  311. getDropzoneClassName() {
  312. let className = 'dropzone';
  313. if (!this.props.isUploadable) {
  314. className += ' dropzone-unuploadable';
  315. }
  316. else {
  317. className += ' dropzone-uploadable';
  318. if (this.props.isUploadableFile) {
  319. className += ' dropzone-uploadablefile';
  320. }
  321. }
  322. // uploading
  323. if (this.state.isUploading) {
  324. className += ' dropzone-uploading';
  325. }
  326. return className;
  327. }
  328. getOverlayStyle() {
  329. return {
  330. position: 'absolute',
  331. zIndex: 4, // forward than .CodeMirror-gutters
  332. top: 0,
  333. right: 0,
  334. bottom: 0,
  335. left: 0,
  336. };
  337. }
  338. renderDropzoneOverlay() {
  339. const overlayStyle = this.getOverlayStyle();
  340. return (
  341. <div style={overlayStyle} className="overlay">
  342. {this.state.isUploading &&
  343. <span className="overlay-content">
  344. <div className="speeding-wheel d-inline-block"></div>
  345. <span className="sr-only">Uploading...</span>
  346. </span>
  347. }
  348. {!this.state.isUploading && <span className="overlay-content"></span>}
  349. </div>
  350. );
  351. }
  352. renderLoadingKeymapOverlay() {
  353. const overlayStyle = this.getOverlayStyle();
  354. return this.state.isLoadingKeymap
  355. ? <div style={overlayStyle} className="loading-keymap overlay">
  356. <span className="overlay-content">
  357. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  358. </span>
  359. </div>
  360. : '';
  361. }
  362. render() {
  363. const flexContainer = {
  364. height: '100%',
  365. display: 'flex',
  366. flexDirection: 'column',
  367. };
  368. const theme = this.props.editorOptions.theme || 'elegant';
  369. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  370. return <React.Fragment>
  371. <div style={flexContainer}>
  372. <Dropzone
  373. ref="dropzone"
  374. disableClick
  375. disablePreview={true}
  376. accept={this.getDropzoneAccept()}
  377. className={this.getDropzoneClassName()}
  378. acceptClassName="dropzone-accepted"
  379. rejectClassName="dropzone-rejected"
  380. multiple={false}
  381. onDragLeave={this.onDragLeave}
  382. onDrop={this.onDrop}
  383. >
  384. { this.state.dropzoneActive && this.renderDropzoneOverlay() }
  385. <ReactCodeMirror
  386. ref="cm"
  387. editorDidMount={(editor) => {
  388. // add event handlers
  389. editor.on('paste', this.onPaste);
  390. editor.on('scrollCursorIntoView', this.onScrollCursorIntoView);
  391. }}
  392. value={this.state.value}
  393. options={{
  394. mode: 'gfm',
  395. theme: theme,
  396. styleActiveLine: styleActiveLine,
  397. lineNumbers: true,
  398. tabSize: 4,
  399. indentUnit: 4,
  400. lineWrapping: true,
  401. autoRefresh: true,
  402. autoCloseTags: true,
  403. matchBrackets: true,
  404. matchTags: {bothTags: true},
  405. // folding
  406. foldGutter: true,
  407. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
  408. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  409. highlightSelectionMatches: {annotateScrollbar: true},
  410. // markdown mode options
  411. highlightFormatting: true,
  412. // continuelist, indentlist
  413. extraKeys: {
  414. 'Enter': this.handleEnterKey,
  415. 'Tab': 'indentMore',
  416. 'Shift-Tab': 'indentLess',
  417. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()) },
  418. }
  419. }}
  420. onScroll={(editor, data) => {
  421. if (this.props.onScroll != null) {
  422. // add line data
  423. const line = editor.lineAtHeight(data.top, 'local');
  424. data.line = line;
  425. this.props.onScroll(data);
  426. }
  427. }}
  428. onChange={(editor, data, value) => {
  429. if (this.props.onChange != null) {
  430. this.props.onChange(value);
  431. }
  432. // Emoji AutoComplete
  433. if (this.state.isEnabledEmojiAutoComplete) {
  434. this.emojiAutoCompleteHelper.showHint(editor);
  435. }
  436. }}
  437. onDragEnter={this.onDragEnterForCM}
  438. />
  439. </Dropzone>
  440. <button type="button" className="btn btn-default btn-block btn-open-dropzone"
  441. onClick={() => {this.refs.dropzone.open()}}>
  442. <i className="icon-paper-clip" aria-hidden="true"></i>&nbsp;
  443. Attach files by dragging &amp; dropping,&nbsp;
  444. <span className="btn-link">selecting them</span>,&nbsp;
  445. or pasting from the clipboard.
  446. </button>
  447. { this.renderLoadingKeymapOverlay() }
  448. </div>
  449. </React.Fragment>;
  450. }
  451. }
  452. Editor.propTypes = {
  453. value: PropTypes.string,
  454. options: PropTypes.object,
  455. editorOptions: PropTypes.object,
  456. isUploadable: PropTypes.bool,
  457. isUploadableFile: PropTypes.bool,
  458. emojiStrategy: PropTypes.object,
  459. onChange: PropTypes.func,
  460. onScroll: PropTypes.func,
  461. onScrollCursorIntoView: PropTypes.func,
  462. onSave: PropTypes.func,
  463. onUpload: PropTypes.func,
  464. };