PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/static/scripts/main/username.coffee

https://github.com/danielgtaylor/malt.io
CoffeeScript | 88 lines | 57 code | 13 blank | 18 comment | 4 complexity | 76f2e6734141d0bc9062ab0228ae74bb MD5 | raw file
  1. # A class to help process potential usernames and update the user interface
  2. # to reflect whether a username is valid or not, used on the profile page.
  3. class Username
  4. # A timeout to track when to do a new AJAX call to check the currently
  5. # typed username.
  6. @checkTimeout = null
  7. # Javascript spinner styling options
  8. @spinOpts =
  9. lines: 13
  10. length: 2
  11. width: 2
  12. radius: 4
  13. rotate: 0
  14. color: '#000'
  15. speed: 1
  16. trail: 56
  17. shadow: false
  18. hwaccel: false
  19. className: 'spinner'
  20. zIndex: 1000
  21. top: 'auto'
  22. left: 'auto'
  23. # The current spinner, if one exists
  24. @spinner = null
  25. # Initialize events
  26. @init: =>
  27. $('#username').keyup(->
  28. Username.fixUsername(this)
  29. )
  30. $('#username').keypress(->
  31. Username.fixUsername(this)
  32. )
  33. # Do an AJAX request to check a username to see if it is valid. This
  34. # disables the submit button until the check completes, and if the
  35. # name is valid the button is enabled again.
  36. @checkUsername: =>
  37. username = $('#username')[0].value
  38. element = $('#username-spinner')
  39. # Clear spinner or success/fail data
  40. element.html('')
  41. # Start spinner
  42. if @spinner
  43. @spinner.spin(element[0])
  44. else
  45. @spinner = new Spinner(@spinOpts).spin(element[0])
  46. # Do an AJAX call to find out if this name is valid and available
  47. $.ajax(
  48. url: '/username'
  49. type: 'post'
  50. data:
  51. username: username
  52. success: (data, status, xhr) =>
  53. # Stop the spinner
  54. @spinner.stop()
  55. # Update the UI, showing whether or not the name is valid
  56. parent = element.parent().parent().parent()
  57. if data.available
  58. element.html('✓')
  59. parent.removeClass('error').addClass('success')
  60. $('#profile-save').removeAttr('disabled').removeClass('disabled')
  61. else
  62. element.html('∅')
  63. parent.removeClass('success').addClass('error')
  64. )
  65. # Fix potential issues with the username, such as making it all lowercase
  66. # and removing all spaces, then set the timeout to check to ensure it is
  67. # both valid and available.
  68. @fixUsername: (element) =>
  69. if @spinner
  70. @spinner.stop()
  71. element.value = element.value.replace(' ', '').toLowerCase()
  72. if @checkTimeout
  73. clearTimeout(@checkTimeout)
  74. $('#profile-save').attr('disabled', 'disabled').addClass('disabled')
  75. @checkTimeout = setTimeout(@checkUsername, 500)