Skip to content

Instantly share code, notes, and snippets.

@Leko
Created July 8, 2016 08:49
Show Gist options
  • Save Leko/40039e11fed89a580526f157bb71f395 to your computer and use it in GitHub Desktop.
Save Leko/40039e11fed89a580526f157bb71f395 to your computer and use it in GitHub Desktop.
WIP
const setUp = () => {
const org = document.getElementById('_emoticon')
org.dispatchEvent(new MouseEvent('click'))
org.dispatchEvent(new MouseEvent('click'))
}
setUp()
const getter = (attr) => (obj) => obj[attr]
const trigger = ':'
const editor = document.getElementById('_chatText')
const dummy = document.createElement('div')
const emoticonList = document.getElementById('_emoticonList')
var emoticons = null
document.body.appendChild(dummy)
function position(el) {
for (var x = 0, y = 0; el != null; el = el.offsetParent) {
x += el.offsetLeft
y += el.offsetTop
}
return { x, y }
}
const calclate = (original, selectionStart) => {
const cursor = document.createElement('span')
const txt = editor.value.substring(0, selectionStart)
dummy.style = editor.style
dummy.style.position = 'absolute'
dummy.style.top = '-100000px'
dummy.style.left = '-100000px'
dummy.innerText = txt
dummy.appendChild(cursor)
const pos = position(original)
const top = pos.y + cursor.offsetTop
const left = pos.x + cursor.offsetLeft
dummy.removeChild(cursor)
return { top, left }
}
editor.addEventListener('keyup', (e) => {
const selectionStart = editor.selectionStart + 1
const txt = editor.value.substring(0, selectionStart).split(' ').slice(-1)[0]
const query = txt.substring(txt.lastIndexOf(trigger) + 1)
const matched = Array.from(emoticonList.querySelectorAll('li')).filter((el) => {
return query === '' || getter('alt')(el.querySelector('img')).includes(query)
})
if (!txt.includes(trigger) || matched.length === 0) {
if (emoticons !== null) {
document.body.removeChild(emoticons)
emoticons = null
}
return;
}
if (emoticons === null) {
emoticons = emoticonList.cloneNode(true)
document.body.appendChild(emoticons)
}
const pos = calclate(editor, selectionStart)
const ul = emoticons.querySelector('ul')
emoticons.querySelector('ul').innerHTML = ''
matched.map(el => el.cloneNode(true)).forEach(el => ul.appendChild(el))
emoticons.id = null
emoticons.style.display = 'block'
emoticons.style.top = (pos.top - emoticons.clientHeight) + 'px'
emoticons.style.left = (pos.left - emoticons.clientWidth / 2) + 'px'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment