-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (61 loc) · 2.35 KB
/
index.js
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
const messageBox = document.getElementById('message-box')
const mentionBox = document.getElementById('mention-box')
const mentionComplete = document.getElementById('mention-complete')
messageBox.focus()
let preserveSelection = null
let characterAfterMention = null
let debounceForPrevCharacter = null
function userTypesCharacters(event) {
preserveSelection = window.getSelection()
if(event.key === ' ' && mentionBox.classList.contains('show')) {
mentionBox.classList.toggle('show')
}
if(event.key === '@' && checkForEmptySpace()) {
if(!mentionBox.classList.contains('show')) {
mentionBox.classList.toggle('show')
}
}
if(debounceForPrevCharacter) {
clearTimeout(debounceForPrevCharacter)
}
debounceForPrevCharacter = setTimeout(trackCharsAfterMentionSymbol, 100)
}
function checkForEmptySpace() {
const selection = window.getSelection()
selection.modify('extend', 'backward', 'character')
const prevCharacter = selection.toString().charCodeAt(0)
selection.collapseToEnd()
return !prevCharacter || prevCharacter === 160
}
function trackCharsAfterMentionSymbol() {
if(!mentionBox.classList.contains('show')) {
return
}
const selection = window.getSelection()
selection.modify('extend', 'backward', 'word')
characterAfterMention = selection.toString()
selection.collapseToEnd()
}
function mentionCompleteListener(event) {
if(!preserveSelection) {
return
}
if(characterAfterMention && characterAfterMention.length > 1) {
preserveSelection.modify('extend', 'backward', 'word')
if(!preserveSelection.toString()?.startsWith('@')) {
preserveSelection.modify('extend', 'backward', 'character')
}
} else {
preserveSelection.modify('extend', 'backward', 'character');
}
preserveSelection.getRangeAt(0).deleteContents()
const node = document.createElement('b')
node.innerHTML = ' @shahab '
preserveSelection.getRangeAt(0).insertNode(node)
node.insertAdjacentHTML('afterend', '<span> </span>')
preserveSelection.modify('extend', 'forward', 'word')
preserveSelection.collapseToEnd()
mentionBox.classList.toggle('show')
}
mentionComplete.addEventListener('click', mentionCompleteListener)
messageBox.addEventListener('keypress', userTypesCharacters)