Editor.js 14 KB

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