Editor.js 9.7 KB

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