Editor.js 9.3 KB

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