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(extension): #40: pause ApproveDeny component when out of focus #43

Merged
merged 1 commit into from
Jun 19, 2024
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
6 changes: 2 additions & 4 deletions apps/extension/src/routes/popup/approval/approve-deny.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Button } from '@penumbra-zone/ui/components/ui/button';
import { useEffect } from 'react';
import { useCountdown } from 'usehooks-ts';
import { useWindowCountdown } from './use-window-countdown';

export const ApproveDeny = ({
approve,
Expand All @@ -13,8 +12,7 @@ export const ApproveDeny = ({
ignore?: () => void;
wait?: number;
}) => {
const [count, { startCountdown }] = useCountdown({ countStart: wait });
useEffect(startCountdown, [startCountdown]);
const count = useWindowCountdown(wait);

return (
<div className='flex flex-row flex-wrap justify-center gap-4 bg-black p-4 shadow-lg'>
Expand Down
37 changes: 37 additions & 0 deletions apps/extension/src/routes/popup/approval/use-window-countdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect } from 'react';
import { useCountdown } from 'usehooks-ts';

/**
* A hook that counts down each second from a given number only when the window is focused.
* If the window is out of focus, the countdown will reset and start from the beginning.
*/
export const useWindowCountdown = (wait = 0) => {
const [count, { startCountdown, stopCountdown, resetCountdown }] = useCountdown({
countStart: wait,
});

const onFocus = () => {
resetCountdown();
startCountdown();
};

const onBlur = () => {
stopCountdown();
};

useEffect(() => {
if (document.hasFocus()) {
startCountdown();
}

window.addEventListener('focus', onFocus);
window.addEventListener('blur', onBlur);

return () => {
window.removeEventListener('focus', onFocus);
window.removeEventListener('blur', onBlur);
};
}, [startCountdown]);

return count;
};
Loading