index.coffee 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. document.head.insertAdjacentHTML('beforeend','<style type="text/tailwindcss" component="ImageSlider">'+stylFns['app/shared/ImageSlider/index.styl']+'</style>')
  2. module.exports =
  3. name: 'ImageSlider'
  4. render: (new Function '_ctx', '_cache', renderFns['app/shared/ImageSlider/index.pug'])()
  5. props:
  6. slides:
  7. type: Array
  8. required: true
  9. default: -> []
  10. autoplay:
  11. type: Boolean
  12. default: true
  13. duration:
  14. type: Number
  15. default: 5000
  16. startIndex:
  17. type: Number
  18. default: 0
  19. data: ->
  20. currentIndex: @startIndex
  21. progress: 0
  22. autoplayTimer: null
  23. touchStartX: 0
  24. touchEndX: 0
  25. mounted: ->
  26. @startAutoplay()
  27. @setupKeyboardNavigation()
  28. debug.log "slider ok"
  29. beforeUnmount: ->
  30. debug.log "slider start"
  31. @stopAutoplay()
  32. watch:
  33. currentIndex:
  34. handler: ->
  35. @progress = 0
  36. immediate: false
  37. methods:
  38. nextSlide: ->
  39. @currentIndex = if @currentIndex >= @slides.length - 1 then 0 else @currentIndex + 1
  40. @$emit 'slide-change', @currentIndex
  41. prevSlide: ->
  42. @currentIndex = if @currentIndex <= 0 then @slides.length - 1 else @currentIndex - 1
  43. @$emit 'slide-change', @currentIndex
  44. goToSlide: (index) ->
  45. @currentIndex = index
  46. @$emit 'slide-change', index
  47. startAutoplay: ->
  48. return unless @autoplay and @slides.length > 1
  49. @stopAutoplay()
  50. @autoplayTimer = setInterval =>
  51. @progress += 1
  52. if @progress >= 100
  53. @nextSlide()
  54. , @duration / 100
  55. stopAutoplay: ->
  56. clearInterval @autoplayTimer if @autoplayTimer
  57. handleTouchStart: (event) ->
  58. @touchStartX = event.touches[0].clientX
  59. @stopAutoplay()
  60. handleTouchMove: (event) ->
  61. @touchEndX = event.touches[0].clientX
  62. handleTouchEnd: ->
  63. return if @touchEndX == 0
  64. diff = @touchStartX - @touchEndX
  65. if Math.abs(diff) > 50
  66. if diff > 0 then @nextSlide() else @prevSlide()
  67. @touchStartX = 0
  68. @touchEndX = 0
  69. @startAutoplay()
  70. setupKeyboardNavigation: ->
  71. document.addEventListener 'keydown', (event) =>
  72. return unless event.target == document.body
  73. switch event.key
  74. when 'ArrowLeft' then @prevSlide()
  75. when 'ArrowRight' then @nextSlide()
  76. emits: ['slide-change', 'slide-click']