Editor.js 9.9 KB

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