Editor.js 6.2 KB

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