Skip to content

Commit

Permalink
fix: update clipboard text on going back to tab
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcaidev committed Nov 22, 2024
1 parent 7cb7ea1 commit 2fc982d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/use-clipboard-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ export function useClipboardText(options: UseClipboardTextOptions = {}) {
useDocumentEventListener("cut", read);
useDocumentEventListener("copy", read);

// TODO: Visibility change event listener
useDocumentEventListener("visibilitychange", (_, document) => {
if (document.visibilityState === "visible") {
read();
}
});

return {
/**
Expand Down
27 changes: 27 additions & 0 deletions tests/use-clipboard-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useClipboardText } from "src";

const mockReadText = vi.fn();
const mockWriteText = vi.fn();
const mockVisibilityState = vi.spyOn(document, "visibilityState", "get");

beforeAll(() => {
vi.stubGlobal("navigator", {
Expand Down Expand Up @@ -125,6 +126,32 @@ it("listens to copy events", async () => {
expect(mockReadText).toHaveBeenCalledTimes(2);
});

it("refreshes clipboard text when the user goes back to the tab", async () => {
mockReadText.mockResolvedValueOnce("hello").mockResolvedValueOnce("world");
mockVisibilityState.mockReturnValue("visible");

const { result } = renderHook(() => useClipboardText());
await waitFor(() => expect(result.current.text).not.toEqual(""));

expect(result.current.text).toEqual("hello");
expect(result.current.error).toEqual(null);
expect(mockReadText).toHaveBeenCalledTimes(1);

mockVisibilityState.mockReturnValue("hidden");
await act(async () => fireEvent(document, new Event("visibilitychange")));

expect(result.current.text).toEqual("hello");
expect(result.current.error).toEqual(null);
expect(mockReadText).toHaveBeenCalledTimes(1);

mockVisibilityState.mockReturnValue("visible");
await act(async () => fireEvent(document, new Event("visibilitychange")));

expect(result.current.text).toEqual("world");
expect(result.current.error).toEqual(null);
expect(mockReadText).toHaveBeenCalledTimes(2);
});

it("recovers from error after any successful read", async () => {
mockReadText
.mockRejectedValueOnce(new Error("error"))
Expand Down

0 comments on commit 2fc982d

Please sign in to comment.