Editor.js 10 KB

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