Skip to content

Commit

Permalink
Merge a9f34ba into ee6a79f
Browse files Browse the repository at this point in the history
  • Loading branch information
igorarkhipenko committed Jun 17, 2020
2 parents ee6a79f + a9f34ba commit 0a40bf2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/components/LocationSelector/LocationSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { FieldWrapper } from '../FieldWrapper';
import { LocationSelectorDialogWithGoogleLoader } from './LocationSelectorDialogWithGoogleLoader';
import { Location, findCenter, getRadiusInMeters, getAddressComponents } from './utils';
import { TAB_KEY, ESCAPE_KEY } from '../../constants';
import { useBrowserTabVisibilityChange } from '../../hooks';
import styles from './LocationSelector.scss';

const { block, elem } = bem('LocationSelector', styles);
Expand Down Expand Up @@ -129,20 +130,21 @@ export const LocationSelector: React.FC<Props> = (props) => {

const [isOpen, setIsOpen] = React.useState(false);
const [isWrapperFocused, setIsWrapperFocused] = React.useState(false);
const isBrowserTabVisible = useBrowserTabVisibilityChange();
const buttonRef = React.useRef<HTMLButtonElement>();

const hasLocationsSelected = selectedLocations && selectedLocations.length > 0;

function handleOpenModal() {
if (!isOpen && !isWrapperFocused) {
if (!isOpen && !isWrapperFocused && isBrowserTabVisible) {
buttonRef.current?.focus();
setIsOpen(true);
}
setIsWrapperFocused(true);
}

function handleCloseModal() {
if (isOpen) {
if (isOpen && isBrowserTabVisible) {
setIsOpen(false);
onBlur();
}
Expand Down
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { useDebounce } from './useDebounce';
export { usePrevious } from './usePrevious';
export { useBrowserTabVisibilityChange } from './useBrowserTabVisibilityChange';
22 changes: 22 additions & 0 deletions src/hooks/useBrowserTabVisibilityChange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import * as React from 'react';

export function useBrowserTabVisibilityChange() {
const [isBrowserTabVisible, setIsBrowserTabVisible] = React.useState(true);
const handleFocusHandleVisibilityChange = () => {
if (document.hidden) {
setIsBrowserTabVisible(false);
} else {
setTimeout(() => setIsBrowserTabVisible(true), 250);
}
};

React.useEffect(() => {
document.addEventListener('visibilitychange', handleFocusHandleVisibilityChange);

return () => {
document.removeEventListener('visibilitychange', handleFocusHandleVisibilityChange);
};
});

return isBrowserTabVisible;
}

0 comments on commit 0a40bf2

Please sign in to comment.