Editor.js 16 KB

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