resize.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { getWindow } from 'ssr-window';
  2. export default function Resize(_ref) {
  3. let {
  4. swiper,
  5. on,
  6. emit
  7. } = _ref;
  8. const window = getWindow();
  9. let observer = null;
  10. let animationFrame = null;
  11. const resizeHandler = () => {
  12. if (!swiper || swiper.destroyed || !swiper.initialized) return;
  13. emit('beforeResize');
  14. emit('resize');
  15. };
  16. const createObserver = () => {
  17. if (!swiper || swiper.destroyed || !swiper.initialized) return;
  18. observer = new ResizeObserver(entries => {
  19. animationFrame = window.requestAnimationFrame(() => {
  20. const {
  21. width,
  22. height
  23. } = swiper;
  24. let newWidth = width;
  25. let newHeight = height;
  26. entries.forEach(_ref2 => {
  27. let {
  28. contentBoxSize,
  29. contentRect,
  30. target
  31. } = _ref2;
  32. if (target && target !== swiper.el) return;
  33. newWidth = contentRect ? contentRect.width : (contentBoxSize[0] || contentBoxSize).inlineSize;
  34. newHeight = contentRect ? contentRect.height : (contentBoxSize[0] || contentBoxSize).blockSize;
  35. });
  36. if (newWidth !== width || newHeight !== height) {
  37. resizeHandler();
  38. }
  39. });
  40. });
  41. observer.observe(swiper.el);
  42. };
  43. const removeObserver = () => {
  44. if (animationFrame) {
  45. window.cancelAnimationFrame(animationFrame);
  46. }
  47. if (observer && observer.unobserve && swiper.el) {
  48. observer.unobserve(swiper.el);
  49. observer = null;
  50. }
  51. };
  52. const orientationChangeHandler = () => {
  53. if (!swiper || swiper.destroyed || !swiper.initialized) return;
  54. emit('orientationchange');
  55. };
  56. on('init', () => {
  57. if (swiper.params.resizeObserver && typeof window.ResizeObserver !== 'undefined') {
  58. createObserver();
  59. return;
  60. }
  61. window.addEventListener('resize', resizeHandler);
  62. window.addEventListener('orientationchange', orientationChangeHandler);
  63. });
  64. on('destroy', () => {
  65. removeObserver();
  66. window.removeEventListener('resize', resizeHandler);
  67. window.removeEventListener('orientationchange', orientationChangeHandler);
  68. });
  69. }