Skip to content

refactor(site): clean up clipboard functionality and define tests #12296

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

Merged
merged 19 commits into from
Feb 28, 2024
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
refactor: redesign useClipboard to be easier to test
  • Loading branch information
Parkreiner committed Feb 27, 2024
commit 5cfbc8eff107ff809e26ff49754f9809393dac77
16 changes: 8 additions & 8 deletions site/src/hooks/useClipboard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { displayError as dispatchError } from "components/GlobalSnackbar/utils";
import { displayError } from "components/GlobalSnackbar/utils";

const CLIPBOARD_TIMEOUT_MS = 1_000;
const COPY_FAILED_MESSAGE = "Failed to copy text to clipboard";
Expand All @@ -8,10 +8,10 @@ export type UseClipboardInput = Readonly<{
textToCopy: string;

/**
* Indicates whether the user should be notified of an error if the copy
* operation fails for whatever reason. Defaults to true.
* Callback to call when an error happens. By default, this will use the
* codebase's global displayError function.
*/
displayErrors?: boolean;
errorCallback?: (errorMessage: string) => void;
}>;

export type UseClipboardResult = Readonly<{
Expand Down Expand Up @@ -39,7 +39,7 @@ export type UseClipboardResult = Readonly<{
}>;

export const useClipboard = (input: UseClipboardInput): UseClipboardResult => {
const { textToCopy, displayErrors = true } = input;
const { textToCopy, errorCallback } = input;
const [showCopiedSuccess, setShowCopiedSuccess] = useState(false);
const timeoutIdRef = useRef<number | undefined>();

Expand Down Expand Up @@ -73,9 +73,9 @@ export const useClipboard = (input: UseClipboardInput): UseClipboardResult => {
}

console.error(wrappedErr);
if (displayErrors) {
dispatchError(COPY_FAILED_MESSAGE);
}

const dispatchError = errorCallback ?? displayError;
dispatchError(COPY_FAILED_MESSAGE);
}
};

Expand Down