Editor.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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://regex101.com/r/gy3i03/1
  76. const pattern = /:[^:\s]+/
  77. const currentPos = cm.getCursor();
  78. // find previous ':shortname'
  79. const sc = cm.getSearchCursor(pattern, currentPos, { multiline: false });
  80. if (sc.findPrevious()) {
  81. const isInputtingEmoji = (currentPos.line === sc.to().line && currentPos.ch === sc.to().ch);
  82. // return if it isn't inputting emoji
  83. if (!isInputtingEmoji) {
  84. return;
  85. }
  86. }
  87. // see https://codemirror.net/doc/manual.html#addon_show-hint
  88. cm.showHint({
  89. completeSingle: false,
  90. // closeOnUnfocus: false, // for debug
  91. hint: () => {
  92. const matched = cm.getDoc().getRange(sc.from(), sc.to());
  93. const term = matched.replace(':', ''); // remove ':' in the head
  94. // get a list of shortnames
  95. const shortnames = this.searchEmojiShortnames(term);
  96. if (shortnames.length >= 1) {
  97. return {
  98. list: this.generateEmojiRenderer(shortnames),
  99. from: sc.from(),
  100. to: sc.to(),
  101. };
  102. }
  103. },
  104. });
  105. }
  106. /**
  107. * see https://codemirror.net/doc/manual.html#addon_show-hint
  108. * @param {any}
  109. */
  110. generateEmojiRenderer(emojiShortnames) {
  111. return emojiShortnames.map((shortname) => {
  112. return {
  113. text: shortname,
  114. className: 'crowi-emoji-autocomplete',
  115. render: (element) => {
  116. element.innerHTML =
  117. `<div class="img-container">${this.emojiShortnameImageMap[shortname]}</div>` +
  118. `<span class="shortname-container">${shortname}</span>`;
  119. }
  120. }
  121. });
  122. }
  123. /**
  124. * transplanted from https://github.com/emojione/emojione/blob/master/examples/OTHER.md
  125. * @param {string} term
  126. * @returns {string[]} a list of shortname
  127. */
  128. searchEmojiShortnames(term) {
  129. const maxLength = 12;
  130. var results = [];
  131. var results2 = [];
  132. var results3 = [];
  133. var results4 = [];
  134. // TODO performance tune
  135. // when total length of all results is less than `maxLength`
  136. for (let unicode in emojiStrategy) {
  137. const data = emojiStrategy[unicode];
  138. // prefix match to shortname
  139. if (maxLength <= results.length) {
  140. break;
  141. }
  142. else if (data.shortname.indexOf(`:${term}`) > -1) {
  143. results.push(data.shortname);
  144. continue;
  145. }
  146. // partial match to shortname
  147. if (maxLength <= results.length) {
  148. continue;
  149. }
  150. else if (data.shortname.indexOf(term) > -1) {
  151. results2.push(data.shortname);
  152. continue;
  153. }
  154. // partial match to aliases
  155. if (maxLength <= results.length + results2.length) {
  156. continue;
  157. }
  158. else if ((data.aliases != null) && (data.aliases.indexOf(term) > -1)) {
  159. results3.push(data.shortname);
  160. continue;
  161. }
  162. // partial match to keywords
  163. if (maxLength <= results.length + results2.length + results3.length) {
  164. continue;
  165. }
  166. else if ((data.keywords != null) && (data.keywords.indexOf(term) > -1)) {
  167. results4.push(data.shortname);
  168. }
  169. };
  170. if (term.length >= 3) {
  171. results.sort(function(a,b) { return (a.length > b.length); });
  172. results2.sort(function(a,b) { return (a.length > b.length); });
  173. results3.sort(function(a,b) { return (a.length > b.length); });
  174. results4.sort();
  175. }
  176. var newResults = results.concat(results2).concat(results3).concat(results4);
  177. newResults = newResults.slice(0, maxLength);
  178. return newResults;
  179. }
  180. /**
  181. * dispatch onSave event
  182. */
  183. dispatchSave() {
  184. if (this.props.onSave != null) {
  185. this.props.onSave();
  186. }
  187. }
  188. render() {
  189. return (
  190. <ReactCodeMirror
  191. ref="cm"
  192. value={this.state.value}
  193. options={{
  194. mode: 'gfm',
  195. theme: 'eclipse',
  196. lineNumbers: true,
  197. tabSize: 4,
  198. indentUnit: 4,
  199. lineWrapping: true,
  200. autoRefresh: true,
  201. autoCloseTags: true,
  202. matchBrackets: true,
  203. matchTags: {bothTags: true},
  204. // match-highlighter, matchesonscrollbar, annotatescrollbar options
  205. highlightSelectionMatches: {annotateScrollbar: true},
  206. // markdown mode options
  207. highlightFormatting: true,
  208. // continuelist, indentlist
  209. extraKeys: {
  210. "Enter": "newlineAndIndentContinueMarkdownList",
  211. "Tab": "indentMore",
  212. "Shift-Tab": "indentLess",
  213. }
  214. }}
  215. onScroll={(editor, data) => {
  216. if (this.props.onScroll != null) {
  217. this.props.onScroll(data);
  218. }
  219. }}
  220. onChange={(editor, data, value) => {
  221. if (this.props.onChange != null) {
  222. this.props.onChange(value);
  223. }
  224. // Emoji AutoComplete
  225. this.autoCompleteEmoji(editor);
  226. }}
  227. />
  228. )
  229. }
  230. }
  231. Editor.propTypes = {
  232. value: PropTypes.string,
  233. onChange: PropTypes.func,
  234. onScroll: PropTypes.func,
  235. onSave: PropTypes.func,
  236. };