summaryrefslogtreecommitdiff
path: root/templates/assets/bootstrap-material-design/js/ripples.js
blob: c28d2870956b395ab0239440b6a731b7219e2b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import Util from './util'

const Ripples = (($) => {

  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */
  const NAME = 'ripples'
  const DATA_KEY = `bmd.${NAME}`
  const JQUERY_NAME = `bmd${NAME.charAt(0).toUpperCase() + NAME.slice(1)}`
  const JQUERY_NO_CONFLICT = $.fn[JQUERY_NAME]

  const ClassName = {
    CONTAINER: 'ripple-container',
    DECORATOR: 'ripple-decorator'
  }

  const Selector = {
    CONTAINER: `.${ClassName.CONTAINER}`,
    DECORATOR: `.${ClassName.DECORATOR}` //,
  }


  const Default = {
    container: {
      template: `<div class='${ClassName.CONTAINER}'></div>`
    },
    decorator: {
      template: `<div class='${ClassName.DECORATOR}'></div>`
    },
    trigger: {
      start: 'mousedown touchstart',
      end: 'mouseup mouseleave touchend'
    },
    touchUserAgentRegex: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i,
    duration: 500
  }

  /**
   * ------------------------------------------------------------------------
   * Class Definition
   * ------------------------------------------------------------------------
   */
  class Ripples {

    constructor($element, config) {
      this.$element = $element

      //console.log(`Adding ripples to ${Util.describe(this.$element)}`)  // eslint-disable-line no-console
      this.config = $.extend(true, {}, Default, config)

      // attach initial listener
      this.$element.on(this.config.trigger.start, (event) => {
        this._onStartRipple(event)
      })
    }


    dispose() {
      this.$element.data(DATA_KEY, null)
      this.$element = null
      this.$container = null
      this.$decorator = null
      this.config = null
    }

    // ------------------------------------------------------------------------
    // private

    _onStartRipple(event) {

      // Verify if the user is just touching on a device and return if so
      if (this._isTouch() && event.type === 'mousedown') {
        return
      }

      // Find or create the ripple container element
      this._findOrCreateContainer()

      // Get relY and relX positions of the container element
      let relY = this._getRelY(event)
      let relX = this._getRelX(event)

      // If relY and/or relX are false, return the event
      if (!relY && !relX) {
        return
      }

      // set the location and color each time (even if element is cached)
      this.$decorator.css({
        left: relX,
        top: relY,
        'background-color': this._getRipplesColor()
      })

      // Make sure the ripple has the styles applied (ugly hack but it works)
      this._forceStyleApplication()

      // Turn on the ripple animation
      this.rippleOn()

      // Call the rippleEnd function when the transition 'on' ends
      setTimeout(() => {
        this.rippleEnd()
      }, this.config.duration)

      // Detect when the user leaves the element to cleanup if not already done?
      this.$element.on(this.config.trigger.end, () => {
        if (this.$decorator) { // guard against race condition/mouse attack
          this.$decorator.data('mousedown', 'off')

          if (this.$decorator.data('animating') === 'off') {
            this.rippleOut()
          }
        }
      })
    }

    _findOrCreateContainer() {
      if (!this.$container || !this.$container.length > 0) {
        this.$element.append(this.config.container.template)
        this.$container = this.$element.find(Selector.CONTAINER)
      }

      // always add the rippleElement, it is always removed
      this.$container.append(this.config.decorator.template)
      this.$decorator = this.$container.find(Selector.DECORATOR)
    }

    // Make sure the ripple has the styles applied (ugly hack but it works)
    _forceStyleApplication() {
      return window.getComputedStyle(this.$decorator[0]).opacity
    }


    /**
     * Get the relX
     */
    _getRelX(event) {
      let wrapperOffset = this.$container.offset()

      let result = null
      if (!this._isTouch()) {
        // Get the mouse position relative to the ripple wrapper
        result = event.pageX - wrapperOffset.left
      } else {
        // Make sure the user is using only one finger and then get the touch
        //  position relative to the ripple wrapper
        event = event.originalEvent

        if (event.touches.length === 1) {
          result = event.touches[0].pageX - wrapperOffset.left
        } else {
          result = false
        }
      }

      return result
    }

    /**
     * Get the relY
     */
    _getRelY(event) {
      let containerOffset = this.$container.offset()
      let result = null

      if (!this._isTouch()) {
        /**
         * Get the mouse position relative to the ripple wrapper
         */
        result = event.pageY - containerOffset.top
      } else {
        /**
         * Make sure the user is using only one finger and then get the touch
         * position relative to the ripple wrapper
         */
        event = event.originalEvent

        if (event.touches.length === 1) {
          result = event.touches[0].pageY - containerOffset.top
        } else {
          result = false
        }
      }

      return result
    }

    /**
     * Get the ripple color
     */
    _getRipplesColor() {
      let color = this.$element.data('ripple-color') ? this.$element.data('ripple-color') : window.getComputedStyle(this.$element[0]).color
      return color
    }

    /**
     * Verify if the client is using a mobile device
     */
    _isTouch() {
      return this.config.touchUserAgentRegex.test(navigator.userAgent)
    }

    /**
     * End the animation of the ripple
     */
    rippleEnd() {
      if (this.$decorator) { // guard against race condition/mouse attack
        this.$decorator.data('animating', 'off')

        if (this.$decorator.data('mousedown') === 'off') {
          this.rippleOut(this.$decorator)
        }
      }
    }

    /**
     * Turn off the ripple effect
     */
    rippleOut() {
      this.$decorator.off()

      if (Util.transitionEndSupported()) {
        this.$decorator.addClass('ripple-out')
      } else {
        this.$decorator.animate({opacity: 0}, 100, () => {
          this.$decorator.trigger('transitionend')
        })
      }

      this.$decorator.on(Util.transitionEndSelector(), () => {
        if (this.$decorator) {
          this.$decorator.remove()
          this.$decorator = null
        }
      })
    }

    /**
     * Turn on the ripple effect
     */
    rippleOn() {
      let size = this._getNewSize()

      if (Util.transitionEndSupported()) {
        this.$decorator
          .css({
            '-ms-transform': `scale(${size})`,
            '-moz-transform': `scale(${size})`,
            '-webkit-transform': `scale(${size})`,
            transform: `scale(${size})`
          })
          .addClass('ripple-on')
          .data('animating', 'on')
          .data('mousedown', 'on')
      } else {
        this.$decorator.animate({
          width: Math.max(this.$element.outerWidth(), this.$element.outerHeight()) * 2,
          height: Math.max(this.$element.outerWidth(), this.$element.outerHeight()) * 2,
          'margin-left': Math.max(this.$element.outerWidth(), this.$element.outerHeight()) * (-1),
          'margin-top': Math.max(this.$element.outerWidth(), this.$element.outerHeight()) * (-1),
          opacity: 0.2
        }, this.config.duration, () => {
          this.$decorator.trigger('transitionend')
        })
      }
    }

    /**
     * Get the new size based on the element height/width and the ripple width
     */
    _getNewSize() {
      return (Math.max(this.$element.outerWidth(), this.$element.outerHeight()) / this.$decorator.outerWidth()) * 2.5
    }

    // ------------------------------------------------------------------------
    // static

    static _jQueryInterface(config) {
      return this.each(function () {
        let $element = $(this)
        let data = $element.data(DATA_KEY)

        if (!data) {
          data = new Ripples($element, config)
          $element.data(DATA_KEY, data)
        }
      })
    }
  }

  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */
  $.fn[JQUERY_NAME] = Ripples._jQueryInterface
  $.fn[JQUERY_NAME].Constructor = Ripples
  $.fn[JQUERY_NAME].noConflict = () => {
    $.fn[JQUERY_NAME] = JQUERY_NO_CONFLICT
    return Ripples._jQueryInterface
  }

  return Ripples

})(jQuery)

export default Ripples