Editor.js 12 KB

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