Editor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 AbortContinueMarkdownListInterceptor from '../../util/interceptor/AbortContinueMarkdownListInterceptor';
  34. import ReformMarkdownTableInterceptor from '../../util/interceptor/ReformMarkdownTableInterceptor';
  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 AbortContinueMarkdownListInterceptor(),
  43. new ReformMarkdownTableInterceptor(),
  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. console.log('codemirror.commands.newlineAndIndentContinueMarkdownList(editor)');
  157. codemirror.commands.newlineAndIndentContinueMarkdownList(editor);
  158. }
  159. });
  160. }
  161. onScrollCursorIntoView(editor, event) {
  162. if (this.props.onScrollCursorIntoView != null) {
  163. const line = editor.getCursor().line;
  164. this.props.onScrollCursorIntoView(line);
  165. }
  166. }
  167. /**
  168. * CodeMirror paste event handler
  169. * see: https://codemirror.net/doc/manual.html#events
  170. * @param {any} editor An editor instance of CodeMirror
  171. * @param {any} event
  172. */
  173. onPaste(editor, event) {
  174. const types = event.clipboardData.types;
  175. // text
  176. if (types.includes('text/plain')) {
  177. pasteHelper.pasteText(editor, event);
  178. }
  179. // files
  180. else if (types.includes('Files')) {
  181. const dropzone = this.refs.dropzone;
  182. const items = event.clipboardData.items || event.clipboardData.files || [];
  183. // abort if length is not 1
  184. if (items.length != 1) {
  185. return;
  186. }
  187. const file = items[0].getAsFile();
  188. // check type and size
  189. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  190. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  191. this.dispatchUpload(file);
  192. this.setState({ isUploading: true });
  193. }
  194. }
  195. }
  196. onDragEnterForCM(editor, event) {
  197. const dataTransfer = event.dataTransfer;
  198. // do nothing if contents is not files
  199. if (!dataTransfer.types.includes('Files')) {
  200. return;
  201. }
  202. this.setState({ dropzoneActive: true });
  203. }
  204. onDragLeave() {
  205. this.setState({ dropzoneActive: false });
  206. }
  207. onDrop(accepted, rejected) {
  208. // rejected
  209. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  210. this.setState({ dropzoneActive: false });
  211. return;
  212. }
  213. const file = accepted[0];
  214. this.dispatchUpload(file);
  215. this.setState({ isUploading: true });
  216. }
  217. getDropzoneAccept() {
  218. let accept = 'null'; // reject all
  219. if (this.props.isUploadable) {
  220. if (!this.props.isUploadableFile) {
  221. accept = 'image/*' // image only
  222. }
  223. else {
  224. accept = ''; // allow all
  225. }
  226. }
  227. return accept;
  228. }
  229. getDropzoneClassName() {
  230. let className = 'dropzone';
  231. if (!this.props.isUploadable) {
  232. className += ' dropzone-unuploadable';
  233. }
  234. else {
  235. className += ' dropzone-uploadable';
  236. if (this.props.isUploadableFile) {
  237. className += ' dropzone-uploadablefile';
  238. }
  239. }
  240. // uploading
  241. if (this.state.isUploading) {
  242. className += ' dropzone-uploading';
  243. }
  244. return className;
  245. }
  246. renderOverlay() {
  247. const overlayStyle = {
  248. position: 'absolute',
  249. zIndex: 1060, // FIXME: required because .content-main.on-edit has 'z-index:1050'
  250. top: 0,
  251. right: 0,
  252. bottom: 0,
  253. left: 0,
  254. };
  255. return (
  256. <div style={overlayStyle} className="dropzone-overlay">
  257. {this.state.isUploading &&
  258. <span className="dropzone-overlay-content">
  259. <i className="fa fa-spinner fa-pulse fa-fw"></i>
  260. <span className="sr-only">Uploading...</span>
  261. </span>
  262. }
  263. {!this.state.isUploading && <span className="dropzone-overlay-content"></span>}
  264. </div>
  265. );
  266. }
  267. render() {
  268. const flexContainer = {
  269. height: '100%',
  270. display: 'flex',
  271. flexDirection: 'column',
  272. }
  273. const expandHeight = {
  274. height: 'calc(100% - 20px)'
  275. }
  276. const theme = this.props.editorOptions.theme || 'elegant';
  277. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  278. return (
  279. <div style={flexContainer}>
  280. <Dropzone
  281. ref="dropzone"
  282. disableClick
  283. disablePreview={true}
  284. style={expandHeight}
  285. accept={this.getDropzoneAccept()}
  286. className={this.getDropzoneClassName()}
  287. acceptClassName="dropzone-accepted"
  288. rejectClassName="dropzone-rejected"
  289. multiple={false}
  290. onDragLeave={this.onDragLeave}
  291. onDrop={this.onDrop}
  292. >
  293. { this.state.dropzoneActive && this.renderOverlay() }
  294. <ReactCodeMirror
  295. ref="cm"
  296. editorDidMount={(editor) => {
  297. // add event handlers
  298. editor.on('paste', this.onPaste);
  299. editor.on('scrollCursorIntoView', this.onScrollCursorIntoView);
  300. }}
  301. value={this.state.value}
  302. options={{
  303. mode: 'gfm',
  304. theme: theme,
  305. styleActiveLine: styleActiveLine,
  306. lineNumbers: true,
  307. tabSize: 4,
  308. indentUnit: 4,
  309. lineWrapping: true,
  310. autoRefresh: true,
  311. autoCloseTags: true,
  312. matchBrackets: true,
  313. matchTags: {bothTags: true},
  314. // folding
  315. foldGutter: true,
  316. gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
  317. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  318. highlightSelectionMatches: {annotateScrollbar: true},
  319. // markdown mode options
  320. highlightFormatting: true,
  321. // continuelist, indentlist
  322. extraKeys: {
  323. "Enter": this.handleEnterKey,
  324. "Tab": "indentMore",
  325. "Shift-Tab": "indentLess",
  326. "Ctrl-Q": (cm) => { cm.foldCode(cm.getCursor()) },
  327. }
  328. }}
  329. onScroll={(editor, data) => {
  330. if (this.props.onScroll != null) {
  331. // add line data
  332. const line = editor.lineAtHeight(data.top, 'local');
  333. data.line = line;
  334. this.props.onScroll(data);
  335. }
  336. }}
  337. onChange={(editor, data, value) => {
  338. if (this.props.onChange != null) {
  339. this.props.onChange(value);
  340. }
  341. // Emoji AutoComplete
  342. emojiAutoCompleteHelper.showHint(editor);
  343. }}
  344. onDragEnter={this.onDragEnterForCM}
  345. />
  346. </Dropzone>
  347. <button type="button" className="btn btn-default btn-block btn-open-dropzone"
  348. onClick={() => {this.refs.dropzone.open()}}>
  349. <i className="fa fa-paperclip" aria-hidden="true"></i>&nbsp;
  350. Attach files by dragging &amp; dropping,&nbsp;
  351. <span className="btn-link">selecting them</span>,&nbsp;
  352. or pasting from the clipboard.
  353. </button>
  354. </div>
  355. )
  356. }
  357. }
  358. Editor.propTypes = {
  359. value: PropTypes.string,
  360. options: PropTypes.object,
  361. isUploadable: PropTypes.bool,
  362. isUploadableFile: PropTypes.bool,
  363. onChange: PropTypes.func,
  364. onScroll: PropTypes.func,
  365. onScrollCursorIntoView: PropTypes.func,
  366. onSave: PropTypes.func,
  367. onUpload: PropTypes.func,
  368. };