Skip to content

Commit

Permalink
Merge pull request #97 from FrogTheFrog/patch-29
Browse files Browse the repository at this point in the history
fix(useQuickAccessVisible): use the "Page Visibility API" instead of focus/blur
  • Loading branch information
TrainDoctor authored Oct 10, 2023
2 parents 678084e + 4c4fda4 commit de914b1
Showing 1 changed file with 9 additions and 17 deletions.
26 changes: 9 additions & 17 deletions src/custom-hooks/useQuickAccessVisible.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,7 @@ function getQuickAccessWindow(): Window | null {
/**
* Returns state indicating the visibility of quick access menu.
*
* @remarks
* During development it is possible to open the quick access menu without giving it
* focus in some cases. In such cases, the quick access menu state is invisible.
*
* This seems to be impossible to replicate when running the deck normally. Even in
* the edge cases it always seems to have a focus.
*
* @returns `true` if quick access menu is visible (focused) and `false` otherwise.
* @returns `true` if quick access menu is visible and `false` otherwise.
*
* @example
* import { VFC, useEffect } from "react";
Expand Down Expand Up @@ -44,7 +37,10 @@ function getQuickAccessWindow(): Window | null {
* };
*/
export function useQuickAccessVisible(): boolean {
const [isVisible, setIsVisible] = useState(getQuickAccessWindow()?.document.hasFocus() ?? true);
// By default we say that document is not hidden, unless we know otherwise.
// This would cover the cases when Valve breaks something and the quick access window
// cannot be accessed anymore - the plugins that use this would continue working somewhat.
const [isHidden, setIsHidden] = useState(getQuickAccessWindow()?.document.hidden ?? false);

useEffect(() => {
const quickAccessWindow = getQuickAccessWindow();
Expand All @@ -53,16 +49,12 @@ export function useQuickAccessVisible(): boolean {
return;
}

const onBlur = () => setIsVisible(false);
const onFocus = () => setIsVisible(true);

quickAccessWindow.addEventListener('blur', onBlur);
quickAccessWindow.addEventListener('focus', onFocus);
const onVisibilityChange = () => setIsHidden(quickAccessWindow.document.hidden);
quickAccessWindow.addEventListener('visibilitychange', onVisibilityChange);
return () => {
quickAccessWindow.removeEventListener('blur', onBlur);
quickAccessWindow.removeEventListener('focus', onFocus);
quickAccessWindow.removeEventListener('visibilitychange', onVisibilityChange);
};
}, []);

return isVisible;
return !isHidden;
}

0 comments on commit de914b1

Please sign in to comment.