Skip to content
This repository was archived by the owner on Jan 24, 2025. It is now read-only.

Commit 2fc982d

Browse files
committed
fix: update clipboard text on going back to tab
1 parent 7cb7ea1 commit 2fc982d

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/use-clipboard-text.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,11 @@ export function useClipboardText(options: UseClipboardTextOptions = {}) {
7979
useDocumentEventListener("cut", read);
8080
useDocumentEventListener("copy", read);
8181

82-
// TODO: Visibility change event listener
82+
useDocumentEventListener("visibilitychange", (_, document) => {
83+
if (document.visibilityState === "visible") {
84+
read();
85+
}
86+
});
8387

8488
return {
8589
/**

tests/use-clipboard-text.test.ts

+27
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { useClipboardText } from "src";
33

44
const mockReadText = vi.fn();
55
const mockWriteText = vi.fn();
6+
const mockVisibilityState = vi.spyOn(document, "visibilityState", "get");
67

78
beforeAll(() => {
89
vi.stubGlobal("navigator", {
@@ -125,6 +126,32 @@ it("listens to copy events", async () => {
125126
expect(mockReadText).toHaveBeenCalledTimes(2);
126127
});
127128

129+
it("refreshes clipboard text when the user goes back to the tab", async () => {
130+
mockReadText.mockResolvedValueOnce("hello").mockResolvedValueOnce("world");
131+
mockVisibilityState.mockReturnValue("visible");
132+
133+
const { result } = renderHook(() => useClipboardText());
134+
await waitFor(() => expect(result.current.text).not.toEqual(""));
135+
136+
expect(result.current.text).toEqual("hello");
137+
expect(result.current.error).toEqual(null);
138+
expect(mockReadText).toHaveBeenCalledTimes(1);
139+
140+
mockVisibilityState.mockReturnValue("hidden");
141+
await act(async () => fireEvent(document, new Event("visibilitychange")));
142+
143+
expect(result.current.text).toEqual("hello");
144+
expect(result.current.error).toEqual(null);
145+
expect(mockReadText).toHaveBeenCalledTimes(1);
146+
147+
mockVisibilityState.mockReturnValue("visible");
148+
await act(async () => fireEvent(document, new Event("visibilitychange")));
149+
150+
expect(result.current.text).toEqual("world");
151+
expect(result.current.error).toEqual(null);
152+
expect(mockReadText).toHaveBeenCalledTimes(2);
153+
});
154+
128155
it("recovers from error after any successful read", async () => {
129156
mockReadText
130157
.mockRejectedValueOnce(new Error("error"))

0 commit comments

Comments
 (0)