Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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