mirror of
https://github.com/gethomepage/homepage.git
synced 2026-10-04 01:41:16 -07:00
window focus set-state-in-effect
This commit is contained in:
@@ -1,26 +1,17 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useSyncExternalStore } from "react";
|
||||||
|
|
||||||
const hasFocus = () => typeof document !== "undefined" && document.hasFocus();
|
const hasFocus = () => typeof document !== "undefined" && document.hasFocus();
|
||||||
|
|
||||||
const useWindowFocus = () => {
|
const subscribe = (onFocusChange) => {
|
||||||
const [focused, setFocused] = useState(hasFocus);
|
window.addEventListener("focus", onFocusChange);
|
||||||
|
window.addEventListener("blur", onFocusChange);
|
||||||
|
|
||||||
useEffect(() => {
|
return () => {
|
||||||
setFocused(hasFocus());
|
window.removeEventListener("focus", onFocusChange);
|
||||||
|
window.removeEventListener("blur", onFocusChange);
|
||||||
const onFocus = () => setFocused(true);
|
};
|
||||||
const onBlur = () => setFocused(false);
|
|
||||||
|
|
||||||
window.addEventListener("focus", onFocus);
|
|
||||||
window.addEventListener("blur", onBlur);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener("focus", onFocus);
|
|
||||||
window.removeEventListener("blur", onBlur);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return focused;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const useWindowFocus = () => useSyncExternalStore(subscribe, hasFocus, () => false);
|
||||||
|
|
||||||
export default useWindowFocus;
|
export default useWindowFocus;
|
||||||
|
|||||||
@@ -12,15 +12,17 @@ function Fixture() {
|
|||||||
|
|
||||||
describe("utils/hooks/window-focus", () => {
|
describe("utils/hooks/window-focus", () => {
|
||||||
it("tracks focus/blur events", async () => {
|
it("tracks focus/blur events", async () => {
|
||||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||||
|
|
||||||
render(<Fixture />);
|
render(<Fixture />);
|
||||||
|
|
||||||
expect(screen.getByTestId("focused")).toHaveTextContent("true");
|
expect(screen.getByTestId("focused")).toHaveTextContent("true");
|
||||||
|
|
||||||
|
hasFocus.mockReturnValue(false);
|
||||||
window.dispatchEvent(new Event("blur"));
|
window.dispatchEvent(new Event("blur"));
|
||||||
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("false"));
|
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("false"));
|
||||||
|
|
||||||
|
hasFocus.mockReturnValue(true);
|
||||||
window.dispatchEvent(new Event("focus"));
|
window.dispatchEvent(new Event("focus"));
|
||||||
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("true"));
|
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("true"));
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user