Editor.js 13 KB

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