Editor.js 14 KB

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