2
0

Editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import urljoin from 'url-join';
  4. const loadScript = require('simple-load-script');
  5. const loadCssSync = require('load-css-file');
  6. import * as codemirror from 'codemirror';
  7. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  8. require('codemirror/addon/display/autorefresh');
  9. require('codemirror/addon/edit/matchbrackets');
  10. require('codemirror/addon/edit/matchtags');
  11. require('codemirror/addon/edit/closetag');
  12. require('codemirror/addon/edit/continuelist');
  13. require('codemirror/addon/hint/show-hint');
  14. require('codemirror/addon/hint/show-hint.css');
  15. require('codemirror/addon/search/searchcursor');
  16. require('codemirror/addon/search/match-highlighter');
  17. require('codemirror/addon/selection/active-line');
  18. require('codemirror/addon/scroll/annotatescrollbar');
  19. require('codemirror/addon/fold/foldcode');
  20. require('codemirror/addon/fold/foldgutter');
  21. require('codemirror/addon/fold/foldgutter.css');
  22. require('codemirror/addon/fold/markdown-fold');
  23. require('codemirror/addon/fold/brace-fold');
  24. require('codemirror/mode/gfm/gfm');
  25. import Dropzone from 'react-dropzone';
  26. import pasteHelper from './PasteHelper';
  27. import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
  28. import InterceptorManager from '../../../../lib/util/interceptor-manager';
  29. import MarkdownListInterceptor from './MarkdownListInterceptor';
  30. import MarkdownTableInterceptor from './MarkdownTableInterceptor';
  31. export default class Editor extends React.Component {
  32. constructor(props) {
  33. super(props);
  34. this.cmCdnRoot = 'https://cdn.jsdelivr.net/npm/codemirror@5.37.0';
  35. this.interceptorManager = new InterceptorManager();
  36. this.interceptorManager.addInterceptors([
  37. new MarkdownListInterceptor(),
  38. new MarkdownTableInterceptor(),
  39. ]);
  40. this.state = {
  41. value: this.props.value,
  42. dropzoneActive: false,
  43. isEnabledEmojiAutoComplete: false,
  44. isUploading: false,
  45. isLoadingKeymap: false,
  46. };
  47. this.loadedThemeSet = new Set(['eclipse', 'elegant']); // themes imported in _vendor.scss
  48. this.loadedKeymapSet = new Set();
  49. this.getCodeMirror = this.getCodeMirror.bind(this);
  50. this.setCaretLine = this.setCaretLine.bind(this);
  51. this.setScrollTopByLine = this.setScrollTopByLine.bind(this);
  52. this.loadTheme = this.loadTheme.bind(this);
  53. this.loadKeymapMode = this.loadKeymapMode.bind(this);
  54. this.setKeymapMode = this.setKeymapMode.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.renderDropzoneOverlay = this.renderDropzoneOverlay.bind(this);
  66. this.renderLoadingKeymapOverlay = this.renderLoadingKeymapOverlay.bind(this);
  67. }
  68. componentWillMount() {
  69. if (this.props.emojiStrategy != null) {
  70. this.emojiAutoCompleteHelper = new EmojiAutoCompleteHelper(this.props.emojiStrategy);
  71. this.setState({isEnabledEmojiAutoComplete: true});
  72. }
  73. }
  74. componentDidMount() {
  75. // initialize caret line
  76. this.setCaretLine(0);
  77. // set save handler
  78. codemirror.commands.save = this.dispatchSave;
  79. // set CodeMirror instance as 'CodeMirror' so that CDN addons can reference
  80. window.CodeMirror = require('codemirror');
  81. }
  82. componentWillReceiveProps(nextProps) {
  83. // load theme
  84. const theme = nextProps.editorOptions.theme;
  85. this.loadTheme(theme);
  86. // set keymap
  87. const keymapMode = nextProps.editorOptions.keymapMode;
  88. this.setKeymapMode(keymapMode);
  89. }
  90. getCodeMirror() {
  91. return this.refs.cm.editor;
  92. }
  93. loadCss(source) {
  94. return new Promise((resolve) => {
  95. loadCssSync(source);
  96. resolve();
  97. });
  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. * load Theme
  137. * @see https://codemirror.net/doc/manual.html#config
  138. *
  139. * @param {string} theme
  140. */
  141. loadTheme(theme) {
  142. if (!this.loadedThemeSet.has(theme)) {
  143. this.loadCss(urljoin(this.cmCdnRoot, `theme/${theme}.min.css`));
  144. // update Set
  145. this.loadedThemeSet.add(theme);
  146. }
  147. }
  148. /**
  149. * load assets for Key Maps
  150. * @param {*} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  151. */
  152. loadKeymapMode(keymapMode) {
  153. const loadCss = this.loadCss;
  154. let scriptList = [];
  155. let cssList = [];
  156. // add dependencies
  157. if (this.loadedKeymapSet.size == 0) {
  158. scriptList.push(loadScript(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.js')));
  159. cssList.push(loadCss(urljoin(this.cmCdnRoot, 'addon/dialog/dialog.min.css')));
  160. }
  161. // load keymap
  162. if (!this.loadedKeymapSet.has(keymapMode)) {
  163. scriptList.push(loadScript(urljoin(this.cmCdnRoot, `keymap/${keymapMode}.min.js`)));
  164. // update Set
  165. this.loadedKeymapSet.add(keymapMode);
  166. }
  167. // set loading state
  168. this.setState({ isLoadingKeymap: true });
  169. return Promise.all(scriptList.concat(cssList))
  170. .then(() => {
  171. this.setState({ isLoadingKeymap: false });
  172. });
  173. }
  174. /**
  175. * set Key Maps
  176. * @see https://codemirror.net/doc/manual.html#keymaps
  177. *
  178. * @param {string} keymapMode 'default' or 'vim' or 'emacs' or 'sublime'
  179. */
  180. setKeymapMode(keymapMode) {
  181. if (!keymapMode.match(/^(vim|emacs|sublime)$/)) {
  182. // reset
  183. this.getCodeMirror().setOption('keyMap', 'default');
  184. return;
  185. }
  186. this.loadKeymapMode(keymapMode)
  187. .then(() => {
  188. this.getCodeMirror().setOption('keyMap', keymapMode);
  189. });
  190. }
  191. /**
  192. * remove overlay and set isUploading to false
  193. */
  194. terminateUploadingState() {
  195. this.setState({
  196. dropzoneActive: false,
  197. isUploading: false,
  198. });
  199. }
  200. /**
  201. * insert text
  202. * @param {string} text
  203. */
  204. insertText(text) {
  205. const editor = this.getCodeMirror();
  206. editor.getDoc().replaceSelection(text);
  207. }
  208. /**
  209. * dispatch onSave event
  210. */
  211. dispatchSave() {
  212. if (this.props.onSave != null) {
  213. this.props.onSave();
  214. }
  215. }
  216. /**
  217. * dispatch onUpload event
  218. */
  219. dispatchUpload(files) {
  220. if (this.props.onUpload != null) {
  221. this.props.onUpload(files);
  222. }
  223. }
  224. /**
  225. * handle ENTER key
  226. */
  227. handleEnterKey() {
  228. const editor = this.getCodeMirror();
  229. var context = {
  230. handlers: [], // list of handlers which process enter key
  231. editor: editor,
  232. };
  233. const interceptorManager = this.interceptorManager;
  234. interceptorManager.process('preHandleEnter', context)
  235. .then(() => {
  236. if (context.handlers.length == 0) {
  237. codemirror.commands.newlineAndIndentContinueMarkdownList(editor);
  238. }
  239. });
  240. }
  241. onScrollCursorIntoView(editor, event) {
  242. if (this.props.onScrollCursorIntoView != null) {
  243. const line = editor.getCursor().line;
  244. this.props.onScrollCursorIntoView(line);
  245. }
  246. }
  247. /**
  248. * CodeMirror paste event handler
  249. * see: https://codemirror.net/doc/manual.html#events
  250. * @param {any} editor An editor instance of CodeMirror
  251. * @param {any} event
  252. */
  253. onPaste(editor, event) {
  254. const types = event.clipboardData.types;
  255. // text
  256. if (types.includes('text/plain')) {
  257. pasteHelper.pasteText(editor, event);
  258. }
  259. // files
  260. else if (types.includes('Files')) {
  261. const dropzone = this.refs.dropzone;
  262. const items = event.clipboardData.items || event.clipboardData.files || [];
  263. // abort if length is not 1
  264. if (items.length != 1) {
  265. return;
  266. }
  267. const file = items[0].getAsFile();
  268. // check type and size
  269. if (pasteHelper.fileAccepted(file, dropzone.props.accept) &&
  270. pasteHelper.fileMatchSize(file, dropzone.props.maxSize, dropzone.props.minSize)) {
  271. this.dispatchUpload(file);
  272. this.setState({ isUploading: true });
  273. }
  274. }
  275. }
  276. onDragEnterForCM(editor, event) {
  277. const dataTransfer = event.dataTransfer;
  278. // do nothing if contents is not files
  279. if (!dataTransfer.types.includes('Files')) {
  280. return;
  281. }
  282. this.setState({ dropzoneActive: true });
  283. }
  284. onDragLeave() {
  285. this.setState({ dropzoneActive: false });
  286. }
  287. onDrop(accepted, rejected) {
  288. // rejected
  289. if (accepted.length != 1) { // length should be 0 or 1 because `multiple={false}` is set
  290. this.setState({ dropzoneActive: false });
  291. return;
  292. }
  293. const file = accepted[0];
  294. this.dispatchUpload(file);
  295. this.setState({ isUploading: true });
  296. }
  297. getDropzoneAccept() {
  298. let accept = 'null'; // reject all
  299. if (this.props.isUploadable) {
  300. if (!this.props.isUploadableFile) {
  301. accept = 'image/*'; // image only
  302. }
  303. else {
  304. accept = ''; // allow all
  305. }
  306. }
  307. return accept;
  308. }
  309. getDropzoneClassName() {
  310. let className = 'dropzone';
  311. if (!this.props.isUploadable) {
  312. className += ' dropzone-unuploadable';
  313. }
  314. else {
  315. className += ' dropzone-uploadable';
  316. if (this.props.isUploadableFile) {
  317. className += ' dropzone-uploadablefile';
  318. }
  319. }
  320. // uploading
  321. if (this.state.isUploading) {
  322. className += ' dropzone-uploading';
  323. }
  324. return className;
  325. }
  326. getOverlayStyle() {
  327. return {
  328. position: 'absolute',
  329. zIndex: 4, // forward than .CodeMirror-gutters
  330. top: 0,
  331. right: 0,
  332. bottom: 0,
  333. left: 0,
  334. };
  335. }
  336. renderDropzoneOverlay() {
  337. const overlayStyle = this.getOverlayStyle();
  338. return (
  339. <div style={overlayStyle} className="overlay">
  340. {this.state.isUploading &&
  341. <span className="overlay-content">
  342. <div className="speeding-wheel d-inline-block"></div>
  343. <span className="sr-only">Uploading...</span>
  344. </span>
  345. }
  346. {!this.state.isUploading && <span className="overlay-content"></span>}
  347. </div>
  348. );
  349. }
  350. renderLoadingKeymapOverlay() {
  351. const overlayStyle = this.getOverlayStyle();
  352. return this.state.isLoadingKeymap
  353. ? <div style={overlayStyle} className="loading-keymap overlay">
  354. <span className="overlay-content">
  355. <div className="speeding-wheel d-inline-block"></div> Loading Keymap ...
  356. </span>
  357. </div>
  358. : '';
  359. }
  360. render() {
  361. const flexContainer = {
  362. height: '100%',
  363. display: 'flex',
  364. flexDirection: 'column',
  365. };
  366. const theme = this.props.editorOptions.theme || 'elegant';
  367. const styleActiveLine = this.props.editorOptions.styleActiveLine || undefined;
  368. return <React.Fragment>
  369. <div style={flexContainer}>
  370. <Dropzone
  371. ref="dropzone"
  372. disableClick
  373. disablePreview={true}
  374. accept={this.getDropzoneAccept()}
  375. className={this.getDropzoneClassName()}
  376. acceptClassName="dropzone-accepted"
  377. rejectClassName="dropzone-rejected"
  378. multiple={false}
  379. onDragLeave={this.onDragLeave}
  380. onDrop={this.onDrop}
  381. >
  382. { this.state.dropzoneActive && this.renderDropzoneOverlay() }
  383. <ReactCodeMirror
  384. ref="cm"
  385. editorDidMount={(editor) => {
  386. // add event handlers
  387. editor.on('paste', this.onPaste);
  388. editor.on('scrollCursorIntoView', this.onScrollCursorIntoView);
  389. }}
  390. value={this.state.value}
  391. options={{
  392. mode: 'gfm',
  393. theme: theme,
  394. styleActiveLine: styleActiveLine,
  395. lineNumbers: true,
  396. tabSize: 4,
  397. indentUnit: 4,
  398. lineWrapping: true,
  399. autoRefresh: true,
  400. autoCloseTags: true,
  401. matchBrackets: true,
  402. matchTags: {bothTags: true},
  403. // folding
  404. foldGutter: true,
  405. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
  406. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  407. highlightSelectionMatches: {annotateScrollbar: true},
  408. // markdown mode options
  409. highlightFormatting: true,
  410. // continuelist, indentlist
  411. extraKeys: {
  412. 'Enter': this.handleEnterKey,
  413. 'Tab': 'indentMore',
  414. 'Shift-Tab': 'indentLess',
  415. 'Ctrl-Q': (cm) => { cm.foldCode(cm.getCursor()); },
  416. }
  417. }}
  418. onScroll={(editor, data) => {
  419. if (this.props.onScroll != null) {
  420. // add line data
  421. const line = editor.lineAtHeight(data.top, 'local');
  422. data.line = line;
  423. this.props.onScroll(data);
  424. }
  425. }}
  426. onChange={(editor, data, value) => {
  427. if (this.props.onChange != null) {
  428. this.props.onChange(value);
  429. }
  430. // Emoji AutoComplete
  431. if (this.state.isEnabledEmojiAutoComplete) {
  432. this.emojiAutoCompleteHelper.showHint(editor);
  433. }
  434. }}
  435. onDragEnter={this.onDragEnterForCM}
  436. />
  437. </Dropzone>
  438. <button type="button" className="btn btn-default btn-block btn-open-dropzone"
  439. onClick={() => {this.refs.dropzone.open();}}>
  440. <i className="icon-paper-clip" aria-hidden="true"></i>&nbsp;
  441. Attach files by dragging &amp; dropping,&nbsp;
  442. <span className="btn-link">selecting them</span>,&nbsp;
  443. or pasting from the clipboard.
  444. </button>
  445. { this.renderLoadingKeymapOverlay() }
  446. </div>
  447. </React.Fragment>;
  448. }
  449. }
  450. Editor.propTypes = {
  451. value: PropTypes.string,
  452. options: PropTypes.object,
  453. editorOptions: PropTypes.object,
  454. isUploadable: PropTypes.bool,
  455. isUploadableFile: PropTypes.bool,
  456. emojiStrategy: PropTypes.object,
  457. onChange: PropTypes.func,
  458. onScroll: PropTypes.func,
  459. onScrollCursorIntoView: PropTypes.func,
  460. onSave: PropTypes.func,
  461. onUpload: PropTypes.func,
  462. };