Editor.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/selection/active-line');
  16. require('codemirror/addon/scroll/annotatescrollbar');
  17. require('codemirror/addon/fold/foldcode');
  18. require('codemirror/addon/fold/foldgutter');
  19. require('codemirror/addon/fold/foldgutter.css');
  20. require('codemirror/addon/fold/markdown-fold');
  21. require('codemirror/addon/fold/brace-fold');
  22. require('codemirror/mode/gfm/gfm');
  23. require('codemirror/theme/elegant.css');
  24. require('codemirror/theme/neo.css');
  25. require('codemirror/theme/mdn-like.css');
  26. require('codemirror/theme/material.css');
  27. require('codemirror/theme/monokai.css');
  28. require('codemirror/theme/twilight.css');
  29. import Dropzone from 'react-dropzone';
  30. import pasteHelper from './PasteHelper';
  31. import emojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  32. export default class Editor extends React.Component {
  33. constructor(props) {
  34. super(props);
  35. // https://regex101.com/r/7BN2fR/2
  36. this.indentAndMarkPattern = /^([ \t]*)(?:>|\-|\+|\*|\d+\.) /;
  37. this.state = {
  38. value: this.props.value,
  39. dropzoneActive: false,
  40. isUploading: false,
  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. // scroll to the bottom for a moment
  80. const eol = editor.getDoc().lineCount() - 1;
  81. editor.scrollIntoView(eol);
  82. const linePosition = Math.max(0, line - 1);
  83. editor.scrollIntoView(linePosition);
  84. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  85. }
  86. /**
  87. * remove overlay and set isUploading to false
  88. */
  89. terminateUploadingState() {
  90. this.setState({
  91. dropzoneActive: false,
  92. isUploading: false,
  93. });
  94. }
  95. /**
  96. * insert text
  97. * @param {string} text
  98. */
  99. insertText(text) {
  100. const editor = this.getCodeMirror();
  101. editor.getDoc().replaceSelection(text);
  102. }
  103. /**
  104. * dispatch onSave event
  105. */
  106. dispatchSave() {
  107. if (this.props.onSave != null) {
  108. this.props.onSave();
  109. }
  110. }
  111. /**
  112. * dispatch onUpload event
  113. */
  114. dispatchUpload(files) {
  115. if (this.props.onUpload != null) {
  116. this.props.onUpload(files);
  117. }
  118. }
  119. /**
  120. * CodeMirror paste event handler
  121. * see: https://codemirror.net/doc/manual.html#events
  122. * @param {any} editor An editor instance of CodeMirror
  123. * @param {any} event
  124. */
  125. onPaste(editor, event) {
  126. const types = event.clipboardData.types;
  127. // text
  128. if (types.includes('text/plain')) {
  129. pasteHelper.pasteText(editor, event);
  130. }
  131. // files
  132. else if (types.includes('Files')) {
  133. const dropzone = this.refs.dropzone;
  134. const items = event.clipboardData.items || event.clipboardData.files || [];
  135. // abort if length is not 1
  136. if (items.length != 1) {
  137. return;
  138. }
  139. const file = items[0].getAsFile();
  140. // check type and size
  141. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  142. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  143. this.dispatchUpload(file);
  144. this.setState({ isUploading: true });
  145. }
  146. }
  147. }
  148. onDragEnterForCM(editor, event) {
  149. const dataTransfer = event.dataTransfer;
  150. // do nothing if contents is not files
  151. if (!dataTransfer.types.includes('Files')) {
  152. return;
  153. }
  154. this.setState({ dropzoneActive: true });
  155. }
  156. onDragLeave() {
  157. this.setState({ dropzoneActive: false });
  158. }
  159. onDrop(accepted, rejected) {
  160. // rejected
  161. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  162. this.setState({ dropzoneActive: false });
  163. return;
  164. }
  165. const file = accepted[0];
  166. this.dispatchUpload(file);
  167. this.setState({ isUploading: true });
  168. }
  169. getDropzoneAccept() {
  170. let accept = 'null'; // reject all
  171. if (this.props.isUploadable) {
  172. if (!this.props.isUploadableFile) {
  173. accept = 'image/*' // image only
  174. }
  175. else {
  176. accept = ''; // allow all
  177. }
  178. }
  179. return accept;
  180. }
  181. getDropzoneClassName() {
  182. let className = 'dropzone';
  183. if (!this.props.isUploadable) {
  184. className += ' dropzone-unuploadable';
  185. }
  186. else {
  187. className += ' dropzone-uploadable';
  188. if (this.props.isUploadableFile) {
  189. className += ' dropzone-uploadablefile';
  190. }
  191. }
  192. // uploading
  193. if (this.state.isUploading) {
  194. className += ' dropzone-uploading';
  195. }
  196. return className;
  197. }
  198. renderOverlay() {
  199. const overlayStyle = {
  200. position: 'absolute',
  201. zIndex: 1060, // FIXME: required because .content-main.on-edit has 'z-index:1050'
  202. top: 0,
  203. right: 0,
  204. bottom: 0,
  205. left: 0,
  206. };
  207. return (
  208. <div style={overlayStyle} className="dropzone-overlay">
  209. {this.state.isUploading &&
  210. <span className="dropzone-overlay-content">
  211. <i className="fa fa-spinner fa-pulse fa-fw"></i>
  212. <span className="sr-only">Uploading...</span>
  213. </span>
  214. }
  215. {!this.state.isUploading && <span className="dropzone-overlay-content"></span>}
  216. </div>
  217. );
  218. }
  219. render() {
  220. const flexContainer = {
  221. height: '100%',
  222. display: 'flex',
  223. flexDirection: 'column',
  224. }
  225. const expandHeight = {
  226. height: 'calc(100% - 20px)'
  227. }
  228. const theme = this.props.editorOptions.theme || 'elegant';
  229. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  230. return (
  231. <div style={flexContainer}>
  232. <Dropzone
  233. ref="dropzone"
  234. disableClick
  235. disablePreview={true}
  236. style={expandHeight}
  237. accept={this.getDropzoneAccept()}
  238. className={this.getDropzoneClassName()}
  239. acceptClassName="dropzone-accepted"
  240. rejectClassName="dropzone-rejected"
  241. multiple={false}
  242. onDragLeave={this.onDragLeave}
  243. onDrop={this.onDrop}
  244. >
  245. { this.state.dropzoneActive && this.renderOverlay() }
  246. <ReactCodeMirror
  247. ref="cm"
  248. editorDidMount={(editor) => {
  249. // add event handlers
  250. editor.on('paste', this.onPaste);
  251. }}
  252. value={this.state.value}
  253. options={{
  254. mode: 'gfm',
  255. theme: theme,
  256. styleActiveLine: styleActiveLine,
  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. options: PropTypes.object,
  309. isUploadable: PropTypes.bool,
  310. isUploadableFile: PropTypes.bool,
  311. onChange: PropTypes.func,
  312. onScroll: PropTypes.func,
  313. onSave: PropTypes.func,
  314. onUpload: PropTypes.func,
  315. };