Editor.js 11 KB

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