Editor.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import * as codemirror from 'codemirror';
  4. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  5. require('codemirror/lib/codemirror.css');
  6. require('codemirror/addon/display/autorefresh');
  7. require('codemirror/addon/edit/matchbrackets');
  8. require('codemirror/addon/edit/matchtags');
  9. require('codemirror/addon/edit/closetag');
  10. require('codemirror/addon/edit/continuelist');
  11. require('codemirror/addon/hint/show-hint');
  12. require('codemirror/addon/hint/show-hint.css');
  13. require('codemirror/addon/search/searchcursor');
  14. require('codemirror/addon/search/match-highlighter');
  15. require('codemirror/addon/scroll/annotatescrollbar');
  16. require('codemirror/mode/gfm/gfm');
  17. require('codemirror/theme/eclipse.css');
  18. import Dropzone from 'react-dropzone';
  19. import pasteHelper from './PasteHelper';
  20. import emojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  21. export default class Editor extends React.Component {
  22. constructor(props) {
  23. super(props);
  24. // https://regex101.com/r/7BN2fR/2
  25. this.indentAndMarkPattern = /^([ \t]*)(?:>|\-|\+|\*|\d+\.) /;
  26. this.state = {
  27. value: this.props.value,
  28. dropzoneActive: false,
  29. isUploading: false,
  30. };
  31. this.getCodeMirror = this.getCodeMirror.bind(this);
  32. this.setCaretLine = this.setCaretLine.bind(this);
  33. this.forceToFocus = this.forceToFocus.bind(this);
  34. this.dispatchSave = this.dispatchSave.bind(this);
  35. this.onPaste = this.onPaste.bind(this);
  36. this.onDragEnterForCM = this.onDragEnterForCM.bind(this);
  37. this.onDragLeave = this.onDragLeave.bind(this);
  38. this.onDrop = this.onDrop.bind(this);
  39. this.renderOverlay = this.renderOverlay.bind(this);
  40. }
  41. componentDidMount() {
  42. // initialize caret line
  43. this.setCaretLine(0);
  44. // set save handler
  45. codemirror.commands.save = this.dispatchSave;
  46. }
  47. getCodeMirror() {
  48. return this.refs.cm.editor;
  49. }
  50. forceToFocus() {
  51. const editor = this.getCodeMirror();
  52. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  53. const intervalId = setInterval(() => {
  54. this.getCodeMirror().focus();
  55. if (editor.hasFocus()) {
  56. clearInterval(intervalId);
  57. }
  58. }, 100);
  59. }
  60. /**
  61. * set caret position of codemirror
  62. * @param {string} number
  63. */
  64. setCaretLine(line) {
  65. const editor = this.getCodeMirror();
  66. editor.setCursor({line: line-1}); // leave 'ch' field as null/undefined to indicate the end of line
  67. }
  68. /**
  69. * remove overlay and set isUploading to false
  70. */
  71. terminateUploadingState() {
  72. this.setState({
  73. dropzoneActive: false,
  74. isUploading: false,
  75. });
  76. }
  77. /**
  78. * insert text
  79. * @param {string} text
  80. */
  81. insertText(text) {
  82. const editor = this.getCodeMirror();
  83. editor.getDoc().replaceSelection(text);
  84. }
  85. /**
  86. * dispatch onSave event
  87. */
  88. dispatchSave() {
  89. if (this.props.onSave != null) {
  90. this.props.onSave();
  91. }
  92. }
  93. /**
  94. * dispatch onUpload event
  95. */
  96. dispatchUpload(files) {
  97. if (this.props.onUpload != null) {
  98. this.props.onUpload(files);
  99. }
  100. }
  101. /**
  102. * CodeMirror paste event handler
  103. * see: https://codemirror.net/doc/manual.html#events
  104. * @param {any} editor An editor instance of CodeMirror
  105. * @param {any} event
  106. */
  107. onPaste(editor, event) {
  108. const types = event.clipboardData.types;
  109. // text
  110. if (types.includes('text/plain')) {
  111. pasteHelper.pasteText(editor, event);
  112. }
  113. // files
  114. else if (types.includes('Files')) {
  115. const dropzone = this.refs.dropzone;
  116. const items = event.clipboardData.items || event.clipboardData.files || [];
  117. // abort if length is not 1
  118. if (items.length != 1) {
  119. return;
  120. }
  121. const file = items[0].getAsFile();
  122. // check type and size
  123. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  124. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  125. this.dispatchUpload(file);
  126. this.setState({ isUploading: true });
  127. }
  128. }
  129. }
  130. onDragEnterForCM(editor, event) {
  131. const dataTransfer = event.dataTransfer;
  132. // do nothing if contents is not files
  133. if (!dataTransfer.types.includes('Files')) {
  134. return;
  135. }
  136. this.setState({ dropzoneActive: true });
  137. }
  138. onDragLeave() {
  139. this.setState({ dropzoneActive: false });
  140. }
  141. onDrop(accepted, rejected) {
  142. // rejected
  143. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  144. this.setState({ dropzoneActive: false });
  145. return;
  146. }
  147. const file = accepted[0];
  148. this.dispatchUpload(file);
  149. this.setState({ isUploading: true });
  150. }
  151. renderOverlay() {
  152. const overlayStyle = {
  153. position: 'absolute',
  154. zIndex: 1060, // FIXME: required because .content-main.on-edit has 'z-index:1050'
  155. top: 0,
  156. right: 0,
  157. bottom: 0,
  158. left: 0,
  159. };
  160. return (
  161. <div style={overlayStyle} className="dropzone-overlay">
  162. {this.state.isUploading &&
  163. <span className="dropzone-overlay-content">
  164. <i className="fa fa-spinner fa-pulse fa-fw"></i>
  165. <span className="sr-only">Uploading...</span>
  166. </span>
  167. }
  168. {!this.state.isUploading && <span className="dropzone-overlay-content"></span>}
  169. </div>
  170. );
  171. }
  172. render() {
  173. const flexContainer = {
  174. height: '100%',
  175. display: 'flex',
  176. flexDirection: 'column',
  177. }
  178. const expandHeight = {
  179. height: '100%',
  180. }
  181. let accept = 'null'; // reject all
  182. let className = 'dropzone';
  183. if (!this.props.isUploadable) {
  184. className += ' dropzone-unuploadable';
  185. }
  186. else {
  187. accept = 'image/*'
  188. className += ' dropzone-uploadable';
  189. if (this.props.isUploadableFile) {
  190. className += ' dropzone-uploadablefile';
  191. accept = ''; // allow all
  192. }
  193. }
  194. // uploading
  195. if (this.state.isUploading) {
  196. className += ' dropzone-uploading';
  197. }
  198. return (
  199. <div style={flexContainer}>
  200. <Dropzone
  201. ref="dropzone"
  202. disableClick
  203. disablePreview={true}
  204. style={expandHeight}
  205. accept={accept}
  206. className={className}
  207. acceptClassName="dropzone-accepted"
  208. rejectClassName="dropzone-rejected"
  209. multiple={false}
  210. onDragLeave={this.onDragLeave}
  211. onDrop={this.onDrop}
  212. >
  213. { this.state.dropzoneActive && this.renderOverlay() }
  214. <ReactCodeMirror
  215. ref="cm"
  216. editorDidMount={(editor) => {
  217. // add event handlers
  218. editor.on('paste', this.onPaste);
  219. }}
  220. value={this.state.value}
  221. options={{
  222. mode: 'gfm',
  223. theme: 'eclipse',
  224. lineNumbers: true,
  225. tabSize: 4,
  226. indentUnit: 4,
  227. lineWrapping: true,
  228. autoRefresh: true,
  229. autoCloseTags: true,
  230. matchBrackets: true,
  231. matchTags: {bothTags: true},
  232. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  233. highlightSelectionMatches: {annotateScrollbar: true},
  234. // markdown mode options
  235. highlightFormatting: true,
  236. // continuelist, indentlist
  237. extraKeys: {
  238. "Enter": "newlineAndIndentContinueMarkdownList",
  239. "Tab": "indentMore",
  240. "Shift-Tab": "indentLess",
  241. }
  242. }}
  243. onScroll={(editor, data) => {
  244. if (this.props.onScroll != null) {
  245. this.props.onScroll(data);
  246. }
  247. }}
  248. onChange={(editor, data, value) => {
  249. if (this.props.onChange != null) {
  250. this.props.onChange(value);
  251. }
  252. // Emoji AutoComplete
  253. emojiAutoCompleteHelper.showHint(editor);
  254. }}
  255. onDragEnter={this.onDragEnterForCM}
  256. />
  257. </Dropzone>
  258. <button type="button" className="btn btn-default btn-block btn-open-dropzone" onClick={() => {this.refs.dropzone.open()}}>
  259. <i className="fa fa-paperclip" aria-hidden="true"></i>&nbsp;
  260. Attach files by dragging &amp; dropping,&nbsp;
  261. <span className="btn-link">selecting them</span>,&nbsp;
  262. or pasting from the clipboard.
  263. </button>
  264. </div>
  265. )
  266. }
  267. }
  268. Editor.propTypes = {
  269. value: PropTypes.string,
  270. isUploadable: PropTypes.bool,
  271. isUploadableFile: PropTypes.bool,
  272. onChange: PropTypes.func,
  273. onScroll: PropTypes.func,
  274. onSave: PropTypes.func,
  275. onUpload: PropTypes.func,
  276. };