Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- const SEP = ', '
- const input = document.querySelector('#say')
- const getUsers = () => [...document.querySelectorAll('#table-user>li>h4')].map(el => el.innerText)
- const normalize = str => str
- .toLowerCase()
- .normalize("NFD")
- .replace(/[\u0300-\u036f]/g, "")
- .replace('–', '-') // because –MM–
- let prefix = '' // part of user input against which are nicks being matched
- let nickIndex = 0 // currently selected nick
- const autoComplete = (event) => {
- if (event.key !== 'Tab') {
- if (event.key !== 'Shift') {
- nickIndex = 0
- prefix = ''
- }
- return
- }
- event.preventDefault()
- prefix = prefix || normalize(input.value.split(' ').pop())
- const nicks = getUsers().filter(nick => normalize(nick).startsWith(prefix))
- if (nicks.length === 0) { // no match - do nothing
- return
- }
- if (nickIndex >= nicks.length) { // decrease index if someone left since previous call
- nickIndex = nicks.length-1
- }
- const previous = input.value.split(SEP).slice(0,input.value.endsWith(SEP)?-2:-1).join(SEP)
- // when adressing several nicks, `previous` should contain already prefilled nicks
- input.value = (previous && previous + SEP) + nicks[nickIndex] + SEP
- if (!event.shiftKey) { // rotate index forward ...
- nickIndex++
- nickIndex %= nicks.length
- } else { // ... or backwards
- nickIndex--
- nickIndex += nicks.length
- nickIndex %= nicks.length
- }
- }
- input.addEventListener('keydown', autoComplete)
- }
Add Comment
Please, Sign In to add comment