Editor.js 14 KB

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