Editor.js 12 KB

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