Created
May 5, 2025 02:03
-
-
Save celsowm/d0c06a33fbe05260127b6df0801d50b7 to your computer and use it in GitHub Desktop.
auto complete metionsjs com lazy load
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="pt-BR"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Autocomplete @mentions com Lazy-Load</title> | |
<!-- CSS do Tribute.js --> | |
<link | |
rel="stylesheet" | |
href="https://cdnjs.cloudflare.com/ajax/libs/tributejs/5.1.3/tribute.css" | |
> | |
</head> | |
<body> | |
<h3>Digite @ para carregar e mencionar usuários (lazy-load):</h3> | |
<textarea id="my-textarea" rows="5" cols="40" placeholder="Escreva algo..."></textarea> | |
<!-- JS do Tribute.js --> | |
<script | |
src="https://cdnjs.cloudflare.com/ajax/libs/tributejs/5.1.3/tribute.min.js" | |
></script> | |
<script> | |
(function() { | |
const textarea = document.getElementById('my-textarea'); | |
let usersCache = null; // null = ainda não carregou | |
let isLoading = false; // evita fetchs concorrentes | |
const tribute = new Tribute({ | |
trigger: '@', | |
lookup: 'name', | |
fillAttr: 'username', | |
values: function(text, cb) { | |
// Se ainda não carregou e não está carregando, faz o fetch | |
if (usersCache === null && !isLoading) { | |
isLoading = true; | |
fetch('https://jsonplaceholder.typicode.com/users') | |
.then(res => res.json()) | |
.then(data => { | |
usersCache = data; | |
isLoading = false; | |
// filtra localmente pelo texto já digitado | |
const matches = usersCache.filter(u => | |
u.name.toLowerCase().includes(text.toLowerCase()) | |
); | |
cb(matches); | |
}) | |
.catch(err => { | |
console.error('Erro ao carregar usuários:', err); | |
isLoading = false; | |
cb([]); // sem sugestões | |
}); | |
} | |
// Se já tiver cache, filtra imediatamente | |
else if (usersCache) { | |
const matches = usersCache.filter(u => | |
u.name.toLowerCase().includes(text.toLowerCase()) | |
); | |
cb(matches); | |
} | |
// Se ainda estiver carregando, devolve lista vazia (ou pode mostrar “carregando…”) | |
else { | |
cb([]); | |
} | |
}, | |
menuItemTemplate: item => { | |
return `${item.original.name} (@${item.original.username})`; | |
}, | |
selectTemplate: item => { | |
return `@${item.original.username}`; | |
} | |
}); | |
tribute.attach(textarea); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment