Skip to content

Commit

Permalink
fix(Gallery): timeout inactive tab issue (#5954)
Browse files Browse the repository at this point in the history
  • Loading branch information
BlackySoul authored and actions-user committed Oct 11, 2023
1 parent 6e6c438 commit 23168d6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
8 changes: 2 additions & 6 deletions packages/vkui/src/components/Gallery/Gallery.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as React from 'react';
import { clamp } from '../../helpers/math';
import { useIsClient } from '../../hooks/useIsClient';
import { useTimeout } from '../../hooks/useTimeout';
import { BaseGallery } from '../BaseGallery/BaseGallery';
import { CarouselBase } from '../BaseGallery/CarouselBase/CarouselBase';
import { BaseGalleryProps } from '../BaseGallery/types';
import { useAutoPlay } from './hooks';

export interface GalleryProps extends BaseGalleryProps {
initialSlideIndex?: number;
Expand Down Expand Up @@ -47,11 +47,7 @@ export const Gallery = ({
[isControlled, onChange, slideIndex],
);

const autoplay = useTimeout(() => handleChange((slideIndex + 1) % childCount), timeout);
React.useEffect(
() => (timeout ? autoplay.set() : autoplay.clear()),
[timeout, slideIndex, autoplay],
);
useAutoPlay(timeout, slideIndex, () => handleChange((slideIndex + 1) % childCount));

// prevent invalid slideIndex
// any slide index is invalid with no slides, just keep it as is
Expand Down
39 changes: 39 additions & 0 deletions packages/vkui/src/components/Gallery/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as React from 'react';
import { useTimeout } from '../../hooks/useTimeout';
import { useDOM } from '../../lib/dom';

export function useAutoPlay(timeout: number, slideIndex: number, callbackFn: VoidFunction) {
const { clear: clearAutoPlay, set: setAutoPlay } = useTimeout(callbackFn, timeout);
const { document } = useDOM();

React.useEffect(
() => (timeout ? setAutoPlay() : clearAutoPlay()),
[timeout, slideIndex, clearAutoPlay, setAutoPlay],
);

// Отключаем прокрутку слайдов при неактивной вкладке
React.useEffect(
function preventSlideChange() {
if (!document || !timeout) {
return;
}

const changeAutoPlay = () => {
if (document.visibilityState === 'visible') {
clearAutoPlay();
setAutoPlay();
}
if (document.visibilityState === 'hidden') {
clearAutoPlay();
}
};

document.addEventListener('visibilitychange', changeAutoPlay);

return () => {
document.removeEventListener('visibilitychange', changeAutoPlay);
};
},
[document, timeout, clearAutoPlay, setAutoPlay],
);
}

0 comments on commit 23168d6

Please sign in to comment.