Last active
August 7, 2019 17:07
-
-
Save maburdi94/7bc55f156ef90282e1ed5e65a9991b6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener('DOMContentLoaded', function() { | |
let textarea = document.getElementById('comment'); | |
let sc = document.createElement('div'); | |
sc.classList.add('autocomplete-suggestions'); | |
sc.setAttribute('autocomplete', 'off'); | |
let timer = null, rangeStart = null, rangeEnd = null; | |
textarea.addEventListener('keyup', (e) => { | |
if (/^[\w ]$/i.test(e.key)) { | |
let re = /(?<=@(\w+))/ig; | |
re.lastIndex = textarea.selectionEnd; | |
sc.remove(); | |
// @'text...' is typed | |
if (re.test(textarea.value)) { | |
let match = re.exec(textarea.value); | |
let search = match[1]; | |
rangeEnd = match.index; | |
rangeStart = rangeEnd - search.length - 1; | |
clearTimeout(timer); | |
timer = setTimeout(async () => { | |
suggest(await source(search)); | |
sc = textarea.insertAdjacentElement("afterend", sc); | |
}, 150); | |
} | |
} | |
}); | |
sc.addEventListener('mousedown', (e) => { | |
e.preventDefault(); | |
if (e.target.classList.contains('autocomplete-suggestion')) { | |
let replace = `<a href="">@${e.target.dataset.val} </a> `; | |
textarea.setRangeText(replace, rangeStart, rangeEnd); | |
textarea.selectionStart = rangeStart + replace.length + 1; | |
sc.remove(); | |
} | |
}); | |
textarea.addEventListener('blur', () => sc.remove()); | |
function source(search) { | |
return fetch('/wp-admin/admin-ajax.php', { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | |
body: 'action=shepherd_mention&search=' + search, | |
}).then(res => res.json()); | |
} | |
function suggest(data){ | |
if (data.length) { | |
sc.innerHTML = ''; | |
sc.append(...data.map(renderItem)); | |
} | |
} | |
function renderItem(item){ | |
let div = document.createElement('div'); | |
div.classList.add('autocomplete-suggestion'); | |
div.dataset.val = item['display_name']; | |
div.innerText = item['display_name']; | |
return div; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment