draho

Alik auto nick doplnovac

Jul 10th, 2021 (edited)
1,650
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {
  2.     const SEP = ', '
  3.  
  4.     const input = document.querySelector('#say')
  5.     const getUsers = () => [...document.querySelectorAll('#table-user>li>h4')].map(el => el.innerText)
  6.     const normalize = str => str
  7.       .toLowerCase()
  8.       .normalize("NFD")
  9.       .replace(/[\u0300-\u036f]/g, "")
  10.       .replace('–', '-') // because –MM–
  11.    
  12.     let prefix = '' // part of user input against which are nicks being matched
  13.     let nickIndex = 0 // currently selected nick
  14.    
  15.     const autoComplete = (event) => {
  16.         if (event.key !== 'Tab') {
  17.             if (event.key !== 'Shift') {
  18.                 nickIndex = 0
  19.                 prefix = ''
  20.             }
  21.             return
  22.         }
  23.         event.preventDefault()
  24.  
  25.         prefix = prefix || normalize(input.value.split(' ').pop())
  26.  
  27.         const nicks = getUsers().filter(nick => normalize(nick).startsWith(prefix))
  28.         if (nicks.length === 0) { // no match - do nothing
  29.             return
  30.         }
  31.         if (nickIndex >= nicks.length) { // decrease index if someone left since previous call
  32.             nickIndex = nicks.length-1
  33.         }
  34.         const previous = input.value.split(SEP).slice(0,input.value.endsWith(SEP)?-2:-1).join(SEP)
  35.         // when adressing several nicks, `previous` should contain already prefilled nicks
  36.         input.value = (previous && previous + SEP) + nicks[nickIndex] + SEP
  37.  
  38.         if (!event.shiftKey) { // rotate index forward ...
  39.             nickIndex++
  40.             nickIndex %= nicks.length
  41.         } else { // ... or backwards
  42.             nickIndex--
  43.             nickIndex += nicks.length
  44.             nickIndex %= nicks.length
  45.         }
  46.     }
  47.  
  48.     input.addEventListener('keydown', autoComplete)
  49. }
Add Comment
Please, Sign In to add comment