Editor.js 15 KB

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