Editor.js 7.6 KB

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