Editor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import * as codemirror from 'codemirror';
  4. import mtu from './MarkdownTableUtil';
  5. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  6. require('codemirror/lib/codemirror.css');
  7. require('codemirror/addon/display/autorefresh');
  8. require('codemirror/addon/edit/matchbrackets');
  9. require('codemirror/addon/edit/matchtags');
  10. require('codemirror/addon/edit/closetag');
  11. require('codemirror/addon/edit/continuelist');
  12. require('codemirror/addon/hint/show-hint');
  13. require('codemirror/addon/hint/show-hint.css');
  14. require('codemirror/addon/search/searchcursor');
  15. require('codemirror/addon/search/match-highlighter');
  16. require('codemirror/addon/selection/active-line');
  17. require('codemirror/addon/scroll/annotatescrollbar');
  18. require('codemirror/addon/fold/foldcode');
  19. require('codemirror/addon/fold/foldgutter');
  20. require('codemirror/addon/fold/foldgutter.css');
  21. require('codemirror/addon/fold/markdown-fold');
  22. require('codemirror/addon/fold/brace-fold');
  23. require('codemirror/mode/gfm/gfm');
  24. require('codemirror/theme/elegant.css');
  25. require('codemirror/theme/neo.css');
  26. require('codemirror/theme/mdn-like.css');
  27. require('codemirror/theme/material.css');
  28. require('codemirror/theme/monokai.css');
  29. require('codemirror/theme/twilight.css');
  30. import Dropzone from 'react-dropzone';
  31. import pasteHelper from './PasteHelper';
  32. import emojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  33. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  34. import MarkdownListInterceptor from './MarkdownListInterceptor';
  35. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  36. export default class Editor extends React.Component {
  37. constructor(props) {
  38. super(props);
  39. // https://regex101.com/r/7BN2fR/2
  40. this.indentAndMarkPattern = /^([ \t]*)(?:>|\-|\+|\*|\d+\.) /;
  41. this.interceptorManager = new InterceptorManager();
  42. this.interceptorManager.addInterceptors([
  43. new MarkdownListInterceptor(),
  44. new MarkdownTableInterceptor(),
  45. ]);
  46. this.state = {
  47. value: this.props.value,
  48. dropzoneActive: false,
  49. isUploading: false,
  50. };
  51. this.getCodeMirror = this.getCodeMirror.bind(this);
  52. this.setCaretLine = this.setCaretLine.bind(this);
  53. this.setScrollTopByLine = this.setScrollTopByLine.bind(this);
  54. this.forceToFocus = this.forceToFocus.bind(this);
  55. this.dispatchSave = this.dispatchSave.bind(this);
  56. this.handleEnterKey = this.handleEnterKey.bind(this);
  57. this.onScrollCursorIntoView = this.onScrollCursorIntoView.bind(this);
  58. this.onPaste = this.onPaste.bind(this);
  59. this.onDragEnterForCM = this.onDragEnterForCM.bind(this);
  60. this.onDragLeave = this.onDragLeave.bind(this);
  61. this.onDrop = this.onDrop.bind(this);
  62. this.getDropzoneAccept = this.getDropzoneAccept.bind(this);
  63. this.getDropzoneClassName = this.getDropzoneClassName.bind(this);
  64. this.renderOverlay = this.renderOverlay.bind(this);
  65. }
  66. componentDidMount() {
  67. // initialize caret line
  68. this.setCaretLine(0);
  69. // set save handler
  70. codemirror.commands.save = this.dispatchSave;
  71. }
  72. getCodeMirror() {
  73. return this.refs.cm.editor;
  74. }
  75. forceToFocus() {
  76. const editor = this.getCodeMirror();
  77. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  78. const intervalId = setInterval(() => {
  79. this.getCodeMirror().focus();
  80. if (editor.hasFocus()) {
  81. clearInterval(intervalId);
  82. }
  83. }, 100);
  84. }
  85. /**
  86. * set caret position of codemirror
  87. * @param {string} number
  88. */
  89. setCaretLine(line) {
  90. if (isNaN(line)) {
  91. return;
  92. }
  93. const editor = this.getCodeMirror();
  94. const linePosition = Math.max(0, line);
  95. editor.setCursor({line: linePosition}); // leave 'ch' field as null/undefined to indicate the end of line
  96. this.setScrollTopByLine(linePosition);
  97. }
  98. /**
  99. * scroll
  100. * @param {number} line
  101. */
  102. setScrollTopByLine(line) {
  103. if (isNaN(line)) {
  104. return;
  105. }
  106. const editor = this.getCodeMirror();
  107. // get top position of the line
  108. var top = editor.charCoords({line, ch: 0}, 'local').top;
  109. editor.scrollTo(null, top);
  110. }
  111. /**
  112. * remove overlay and set isUploading to false
  113. */
  114. terminateUploadingState() {
  115. this.setState({
  116. dropzoneActive: false,
  117. isUploading: false,
  118. });
  119. }
  120. /**
  121. * insert text
  122. * @param {string} text
  123. */
  124. insertText(text) {
  125. const editor = this.getCodeMirror();
  126. editor.getDoc().replaceSelection(text);
  127. }
  128. /**
  129. * dispatch onSave event
  130. */
  131. dispatchSave() {
  132. if (this.props.onSave != null) {
  133. this.props.onSave();
  134. }
  135. }
  136. /**
  137. * dispatch onUpload event
  138. */
  139. dispatchUpload(files) {
  140. if (this.props.onUpload != null) {
  141. this.props.onUpload(files);
  142. }
  143. }
  144. /**
  145. * handle ENTER key
  146. */
  147. handleEnterKey() {
  148. const editor = this.getCodeMirror();
  149. var context = {
  150. handlers: [], // list of handlers which process enter key
  151. editor: editor,
  152. };
  153. const interceptorManager = this.interceptorManager;
  154. interceptorManager.process('preHandleEnter', context)
  155. .then(() => {
  156. if (context.handlers.length == 0) {
  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: 4, // forward than .CodeMirror-gutters
  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 theme = this.props.editorOptions.theme || 'elegant';
  274. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  275. return (
  276. <div style={flexContainer}>
  277. <Dropzone
  278. ref="dropzone"
  279. disableClick
  280. disablePreview={true}
  281. accept={this.getDropzoneAccept()}
  282. className={this.getDropzoneClassName()}
  283. acceptClassName="dropzone-accepted"
  284. rejectClassName="dropzone-rejected"
  285. multiple={false}
  286. onDragLeave={this.onDragLeave}
  287. onDrop={this.onDrop}
  288. >
  289. { this.state.dropzoneActive && this.renderOverlay() }
  290. <ReactCodeMirror
  291. ref="cm"
  292. editorDidMount={(editor) => {
  293. // add event handlers
  294. editor.on('paste', this.onPaste);
  295. editor.on('scrollCursorIntoView', this.onScrollCursorIntoView);
  296. }}
  297. value={this.state.value}
  298. options={{
  299. mode: 'gfm',
  300. theme: theme,
  301. styleActiveLine: styleActiveLine,
  302. lineNumbers: true,
  303. tabSize: 4,
  304. indentUnit: 4,
  305. lineWrapping: true,
  306. autoRefresh: true,
  307. autoCloseTags: true,
  308. matchBrackets: true,
  309. matchTags: {bothTags: true},
  310. // folding
  311. foldGutter: true,
  312. gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
  313. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  314. highlightSelectionMatches: {annotateScrollbar: true},
  315. // markdown mode options
  316. highlightFormatting: true,
  317. // continuelist, indentlist
  318. extraKeys: {
  319. "Enter": this.handleEnterKey,
  320. "Tab": "indentMore",
  321. "Shift-Tab": "indentLess",
  322. "Ctrl-Q": (cm) => { cm.foldCode(cm.getCursor()) },
  323. }
  324. }}
  325. onScroll={(editor, data) => {
  326. if (this.props.onScroll != null) {
  327. // add line data
  328. const line = editor.lineAtHeight(data.top, 'local');
  329. data.line = line;
  330. this.props.onScroll(data);
  331. }
  332. }}
  333. onChange={(editor, data, value) => {
  334. if (this.props.onChange != null) {
  335. this.props.onChange(value);
  336. }
  337. // Emoji AutoComplete
  338. emojiAutoCompleteHelper.showHint(editor);
  339. }}
  340. onCursor={(editor, event) => {
  341. const strFromBol = mtu.getStrFromBol(editor);
  342. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)){
  343. console.log("console.log()")
  344. }
  345. }}
  346. onDragEnter={this.onDragEnterForCM}
  347. />
  348. </Dropzone>
  349. <button type="button" className="btn btn-default btn-block btn-open-dropzone"
  350. onClick={() => {this.refs.dropzone.open()}}>
  351. <i className="icon-paper-clip" aria-hidden="true"></i>&nbsp;
  352. Attach files by dragging &amp; dropping,&nbsp;
  353. <span className="btn-link">selecting them</span>,&nbsp;
  354. or pasting from the clipboard.
  355. </button>
  356. </div>
  357. )
  358. }
  359. }
  360. Editor.propTypes = {
  361. value: PropTypes.string,
  362. options: PropTypes.object,
  363. isUploadable: PropTypes.bool,
  364. isUploadableFile: PropTypes.bool,
  365. onChange: PropTypes.func,
  366. onScroll: PropTypes.func,
  367. onScrollCursorIntoView: PropTypes.func,
  368. onSave: PropTypes.func,
  369. onUpload: PropTypes.func,
  370. };