Editor.js 11 KB

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