-
-
Notifications
You must be signed in to change notification settings - Fork 880
Expand file tree
/
Copy pathaddComposerAutocomplete.js
More file actions
182 lines (149 loc) · 7.27 KB
/
Copy pathaddComposerAutocomplete.js
File metadata and controls
182 lines (149 loc) · 7.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { extend } from 'flarum/common/extend';
import TextEditorButton from 'flarum/common/components/TextEditorButton';
import KeyboardNavigatable from 'flarum/common/utils/KeyboardNavigatable';
import Tooltip from 'flarum/common/components/Tooltip';
import AutocompleteReader from 'flarum/common/utils/AutocompleteReader';
import AutocompleteDropdown from './fragments/AutocompleteDropdown';
import getEmojiIconCode from './helpers/getEmojiIconCode';
import cdn from '../common/cdn';
export default function addComposerAutocomplete() {
let emojiMap = null;
extend('flarum/common/components/TextEditor', 'oninit', function () {
this._loaders.push(async () => await import('./emojiMap').then((m) => (emojiMap = m.default)));
// prettier-ignore
this.commonEmoji = [
'😀', '😁', '😂', '😃', '😄', '😅', '😆', '😇', '😈', '😉', '😊', '😋', '😌', '😍', '😎', '😏', '😐️', '😑', '😒',
'😓', '😔', '😕', '😖', '😗', '😘', '😙', '😚', '😛', '😜', '😝', '😞', '😟', '😠', '😡', '😢', '😣', '😤', '😥',
'😦', '😧', '😨', '😩', '😪', '😫', '😬', '😭', '😮', '😮💨', '😯', '😰', '😱', '😲', '😳', '😴', '😵', '😵💫',
'😶', '😶🌫️', '😷', '😸', '😹', '😺', '😻', '😼', '😽', '😾', '😿', '🙀', '🙁', '🙂', '🙃', '🙄',
];
});
extend('flarum/common/components/TextEditor', 'onbuild', function () {
this.emojiDropdown = new AutocompleteDropdown();
const editor = this.element.querySelector('.TextEditor-editor');
editor.outerHTML = `<div class="ComposerBody-emojiWrapper">${editor.outerHTML}</div>`;
this.navigator = new KeyboardNavigatable();
this.navigator
.when(() => this.emojiDropdown.active)
.onUp(() => this.emojiDropdown.navigate(-1))
.onDown(() => this.emojiDropdown.navigate(1))
.onSelect(this.emojiDropdown.complete.bind(this.emojiDropdown))
.onCancel(this.emojiDropdown.hide.bind(this.emojiDropdown))
.bindTo(editor);
editor.outerHTML = editor.outerHTML + '<div class="ComposerBody-emojiDropdownContainer"></div>';
});
extend('flarum/common/components/TextEditor', 'buildEditorParams', function (params) {
const emojiKeys = Object.keys(emojiMap);
const resolvedCdn = cdn();
const autocompleteReader = new AutocompleteReader(':');
params.inputListeners.push(() => {
const selection = this.attrs.composer.editor.getSelectionRange();
const cursor = selection[0];
if (selection[1] - cursor > 0) return;
const lastChunk = this.attrs.composer.editor.getLastNChars(15);
const autocompleting = autocompleteReader.check(lastChunk, cursor, /[a-z0-9]|\+|\-|_|\:/);
this.emojiDropdown.hide();
this.emojiDropdown.active = false;
if (autocompleting) {
const typed = autocompleting.typed;
const emojiDropdown = this.emojiDropdown;
const applySuggestion = (replacement) => {
this.attrs.composer.editor.replaceBeforeCursor(autocompleting.absoluteStart - 1, replacement + ' ');
this.emojiDropdown.hide();
};
const makeSuggestion = function ({ emoji, name, code }) {
return (
<Tooltip text={name}>
<button
key={emoji}
onclick={() => applySuggestion(emoji)}
onmouseenter={function () {
emojiDropdown.setIndex($(this).parent().index() - 1);
}}
>
<img alt={emoji} className="emoji" draggable="false" loading="lazy" src={`${resolvedCdn}72x72/${code}.png`} title={name} />
</button>
</Tooltip>
);
};
const buildSuggestions = () => {
const similarEmoji = [];
// Build a regular expression to do a fuzzy match of the given input string
const fuzzyRegexp = function (str) {
const reEscape = new RegExp('\\(([' + '+.*?[]{}()^$|\\'.replace(/(.)/g, '\\$1') + '])\\)', 'g');
return new RegExp('(.*)' + str.toLowerCase().replace(/(.)/g, '($1)(.*?)').replace(reEscape, '(\\$1)') + '$', 'i');
};
const regTyped = fuzzyRegexp(typed);
let maxSuggestions = 40;
const findMatchingEmojis = (matcher) => {
for (let i = 0; i < emojiKeys.length && maxSuggestions > 0; i++) {
const curEmoji = emojiKeys[i];
if (similarEmoji.indexOf(curEmoji) === -1) {
const names = emojiMap[curEmoji];
for (let name of names) {
if (matcher(name, curEmoji)) {
--maxSuggestions;
similarEmoji.push(curEmoji);
break;
}
}
}
}
};
// First, try to find all emojis starting with the given string
findMatchingEmojis((emojiName, emoji) => {
// If no input is provided yet, match the most common emojis.
if (!typed) {
return this.commonEmoji?.includes(emoji);
}
return emojiName.indexOf(typed) === 0;
});
// If there are still suggestions left, try for some fuzzy matches
findMatchingEmojis((emojiName) => regTyped.test(emojiName));
const suggestions = similarEmoji
.map((emoji) => ({
emoji,
name: emojiMap[emoji][0],
code: getEmojiIconCode(emoji),
}))
.map(makeSuggestion);
if (suggestions.length) {
this.emojiDropdown.items = suggestions;
m.render(this.element.querySelector('.ComposerBody-emojiDropdownContainer'), this.emojiDropdown.render());
this.emojiDropdown.show();
const coordinates = this.attrs.composer.editor.getCaretCoordinates(autocompleting.absoluteStart);
const rect = this.emojiDropdown.element.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
const parent = this.emojiDropdown.element.offsetParent;
let left = coordinates.left;
let top = coordinates.top + 15;
// Keep the dropdown inside the editor.
if (top + height > parent.clientHeight) {
top = coordinates.top - height - 15;
}
if (left + width > parent.clientWidth) {
left = parent.clientWidth - width;
}
// Prevent the dropdown from going off screen on mobile
top = Math.max(-(parent.getBoundingClientRect().top), top);
left = Math.max(-parent.getBoundingClientRect().left + document.documentElement.scrollLeft, left);
this.emojiDropdown.show(left, top);
}
};
buildSuggestions();
this.emojiDropdown.setIndex(0);
this.emojiDropdown.element.scrollTo({ top: 0 });
this.emojiDropdown.active = true;
}
});
});
extend('flarum/common/components/TextEditor', 'toolbarItems', function (items) {
items.add(
'emoji',
<TextEditorButton onclick={() => this.attrs.composer.editor.insertAtCursor(' :')} icon="far fa-smile">
{app.translator.trans('flarum-emoji.forum.composer.emoji_tooltip')}
</TextEditorButton>
);
});
}