Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Gallery): timeout inactive tab issue #5954

Merged
merged 1 commit into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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],
);
}