Editor.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import emojione from 'emojione';
  4. import emojiStrategy from 'emojione/emoji_strategy.json';
  5. import * as codemirror from 'codemirror';
  6. import { UnControlled as ReactCodeMirror } from 'react-codemirror2';
  7. require('codemirror/lib/codemirror.css');
  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/scroll/annotatescrollbar');
  18. require('codemirror/mode/gfm/gfm');
  19. require('codemirror/theme/eclipse.css');
  20. export default class Editor extends React.Component {
  21. constructor(props) {
  22. super(props);
  23. this.state = {
  24. value: this.props.value,
  25. };
  26. this.initEmojiImageMap = this.initEmojiImageMap.bind(this);
  27. this.getCodeMirror = this.getCodeMirror.bind(this);
  28. this.setCaretLine = this.setCaretLine.bind(this);
  29. this.forceToFocus = this.forceToFocus.bind(this);
  30. this.dispatchSave = this.dispatchSave.bind(this);
  31. this.autoCompleteEmoji = this.autoCompleteEmoji.bind(this);
  32. this.initEmojiImageMap()
  33. }
  34. componentDidMount() {
  35. // initialize caret line
  36. this.setCaretLine(0);
  37. // set save handler
  38. codemirror.commands.save = this.dispatchSave;
  39. }
  40. initEmojiImageMap() {
  41. this.emojiShortnameImageMap = {};
  42. for (let unicode in emojiStrategy) {
  43. const data = emojiStrategy[unicode];
  44. const shortname = data.shortname;
  45. // add image tag
  46. this.emojiShortnameImageMap[shortname] = emojione.shortnameToImage(shortname);
  47. }
  48. }
  49. getCodeMirror() {
  50. return this.refs.cm.editor;
  51. }
  52. forceToFocus() {
  53. const editor = this.getCodeMirror();
  54. // use setInterval with reluctance -- 2018.01.11 Yuki Takei
  55. const intervalId = setInterval(() => {
  56. this.getCodeMirror().focus();
  57. if (editor.hasFocus()) {
  58. clearInterval(intervalId);
  59. }
  60. }, 100);
  61. }
  62. /**
  63. * set caret position of codemirror
  64. * @param {string} number
  65. */
  66. setCaretLine(line) {
  67. const editor = this.getCodeMirror();
  68. editor.setCursor({line: line-1}); // leave 'ch' field as null/undefined to indicate the end of line
  69. }
  70. /**
  71. * try to find emoji terms and show hint
  72. */
  73. autoCompleteEmoji() {
  74. const cm = this.getCodeMirror();
  75. // see https://codemirror.net/doc/manual.html#addon_show-hint
  76. cm.showHint({
  77. completeSingle: false,
  78. hint: () => {
  79. // see https://regex101.com/r/gy3i03/1
  80. const pattern = /:[^:\s]+/
  81. const currentPos = cm.getCursor();
  82. // find previous ':shortname'
  83. const sc = cm.getSearchCursor(pattern, currentPos, { multiline: false });
  84. if (sc.findPrevious()) {
  85. const isInputtingEmoji = (currentPos.line === sc.to().line && currentPos.ch === sc.to().ch);
  86. // return if it isn't inputting emoji
  87. if (!isInputtingEmoji) {
  88. return;
  89. }
  90. const matched = cm.getDoc().getRange(sc.from(), sc.to());
  91. const term = matched.replace(':', ''); // remove ':' in the head
  92. // get a list of shortnames
  93. const shortnames = this.searchEmojiShortnames(term);
  94. if (shortnames.length >= 1) {
  95. return {
  96. list: this.generateEmojiRenderer(shortnames),
  97. from: sc.from(),
  98. to: sc.to(),
  99. };
  100. }
  101. }
  102. },
  103. });
  104. }
  105. /**
  106. * see https://codemirror.net/doc/manual.html#addon_show-hint
  107. * @param {any}
  108. */
  109. generateEmojiRenderer(emojiShortnames) {
  110. return emojiShortnames.map((shortname) => {
  111. return {
  112. text: shortname,
  113. render: (element) => {
  114. element.innerHTML = `${this.emojiShortnameImageMap[shortname]} ${shortname}`;
  115. }
  116. }
  117. });
  118. }
  119. /**
  120. * transplanted from https://github.com/emojione/emojione/blob/master/examples/OTHER.md
  121. * @param {string} term
  122. * @returns {string[]} a list of shortname
  123. */
  124. searchEmojiShortnames(term) {
  125. var results = [];
  126. var results2 = [];
  127. var results3 = [];
  128. for (let unicode in emojiStrategy) {
  129. const data = emojiStrategy[unicode];
  130. if (data.shortname.indexOf(term) > -1) {
  131. results.push(data.shortname);
  132. }
  133. else {
  134. if((data.aliases != null) && (data.aliases.indexOf(term) > -1)) {
  135. results2.push(data.shortname);
  136. }
  137. else if ((data.keywords != null) && (data.keywords.indexOf(term) > -1)) {
  138. results3.push(data.shortname);
  139. }
  140. }
  141. };
  142. if (term.length >= 3) {
  143. results.sort(function(a,b) { return (a.length > b.length); });
  144. results2.sort(function(a,b) { return (a.length > b.length); });
  145. results3.sort();
  146. }
  147. var newResults = results.concat(results2).concat(results3);
  148. // limit 10
  149. newResults = newResults.slice(0, 10);
  150. return newResults;
  151. }
  152. /**
  153. * dispatch onSave event
  154. */
  155. dispatchSave() {
  156. if (this.props.onSave != null) {
  157. this.props.onSave();
  158. }
  159. }
  160. render() {
  161. return (
  162. <ReactCodeMirror
  163. ref="cm"
  164. value={this.state.value}
  165. options={{
  166. mode: 'gfm',
  167. theme: 'eclipse',
  168. lineNumbers: true,
  169. tabSize: 4,
  170. indentUnit: 4,
  171. lineWrapping: true,
  172. autoRefresh: true,
  173. autoCloseTags: true,
  174. matchBrackets: true,
  175. matchTags: {bothTags: true},
  176. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  177. highlightSelectionMatches: {annotateScrollbar: true},
  178. // markdown mode options
  179. highlightFormatting: true,
  180. // continuelist, indentlist
  181. extraKeys: {
  182. "Enter": "newlineAndIndentContinueMarkdownList",
  183. "Tab": "indentMore",
  184. "Shift-Tab": "indentLess",
  185. }
  186. }}
  187. onScroll={(editor, data) => {
  188. if (this.props.onScroll != null) {
  189. this.props.onScroll(data);
  190. }
  191. }}
  192. onChange={(editor, data, value) => {
  193. if (this.props.onChange != null) {
  194. this.props.onChange(value);
  195. }
  196. // Emoji AutoComplete
  197. this.autoCompleteEmoji(editor);
  198. }}
  199. />
  200. )
  201. }
  202. }
  203. Editor.propTypes = {
  204. value: PropTypes.string,
  205. onChange: PropTypes.func,
  206. onScroll: PropTypes.func,
  207. onSave: PropTypes.func,
  208. };