Editor.js 16 KB

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