Editor.js 11 KB

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