Editor.js 15 KB

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