Editor.js 9.6 KB

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