Editor.js 8.9 KB

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