8272126cf91bbdca5d81460ab0ef5b2c311c604f605e91a64aa22e406b916ba3c432c1d1035e3d564a9d732909b04eaeb7f43f3d55a25c9792329b05cea50d-exec 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import watchSizeForBrowsersOtherThanIE9 from 'watch-size'
  2. import { removeFromArray } from './removeFromArray'
  3. let intervalId
  4. const registered = []
  5. const INTERVAL_DURATION = 100
  6. function run() {
  7. intervalId = setInterval(() => {
  8. registered.forEach(test)
  9. }, INTERVAL_DURATION)
  10. }
  11. function stop() {
  12. clearInterval(intervalId)
  13. intervalId = null
  14. }
  15. function test(item) {
  16. const { $el, listener, lastWidth, lastHeight } = item
  17. const width = $el.offsetWidth
  18. const height = $el.offsetHeight
  19. if (lastWidth !== width || lastHeight !== height) {
  20. item.lastWidth = width
  21. item.lastHeight = height
  22. listener({ width, height })
  23. }
  24. }
  25. function watchSizeForIE9($el, listener) {
  26. const item = {
  27. $el,
  28. listener,
  29. lastWidth: null,
  30. lastHeight: null,
  31. }
  32. const unwatch = () => {
  33. removeFromArray(registered, item)
  34. if (!registered.length) stop()
  35. }
  36. registered.push(item)
  37. // The original watch-size will call the listener on initialization.
  38. // Keep the same behavior here.
  39. test(item)
  40. run()
  41. return unwatch
  42. }
  43. export function watchSize($el, listener) {
  44. // See: https://stackoverflow.com/a/31293352
  45. const isIE9 = document.documentMode === 9
  46. // watch-size will call the listener on initialization.
  47. // Disable this behavior with a lock to achieve a clearer code logic.
  48. let locked = true
  49. const wrappedListener = (...args) => locked || listener(...args)
  50. const implementation = isIE9
  51. ? watchSizeForIE9
  52. : watchSizeForBrowsersOtherThanIE9
  53. const removeSizeWatcher = implementation($el, wrappedListener)
  54. locked = false // unlock after initialization
  55. return removeSizeWatcher
  56. }