@@ -3,7 +3,8 @@ import { useState, useRef, useCallback } from 'react';
33export enum CopyStatus {
44 None ,
55 Copying ,
6- Copied
6+ Copied ,
7+ Disabled
78}
89
910export type UseCopyProps = {
@@ -29,6 +30,14 @@ export type UseCopyReturn = {
2930 * the `useCopy()` hook.
3031 */
3132 copyLabel : string ;
33+ /**
34+ * Boolean flag that indicates whether the copy functionality is disabled or not.
35+ * This helps to disable the copy action button. The value is based on the presence
36+ * of `navigator.clipboard`. If `navigator.clipboard` is unavailable, the copy
37+ * functionality is considered disabled, and the `copyStatus` will be set to
38+ * either `CopyStatus.None` or `CopyStatus.Disabled`.
39+ */
40+ isCopyDisabled : boolean ;
3241 /**
3342 * Function that takes a string and copies it to the clipboard.
3443 */
@@ -38,15 +47,19 @@ export type UseCopyReturn = {
3847const DEFAULT_LABELS_BY_COPY_STATUS : Record < CopyStatus , string > = {
3948 [ CopyStatus . None ] : 'Copy to clipboard' ,
4049 [ CopyStatus . Copying ] : 'Copying…' ,
41- [ CopyStatus . Copied ] : 'Copied!'
50+ [ CopyStatus . Copied ] : 'Copied!' ,
51+ [ CopyStatus . Disabled ] : 'Copy to clipboard disabled in insecure context'
4252} ;
4353
4454/**
4555 * Hook that provides a function to copy a string to a clipboard and manages
4656 * related UI state. Should be used by any button that intends to copy text.
4757 */
4858export function useCopy ( props ?: UseCopyProps ) : UseCopyReturn {
49- const [ copyStatus , setCopyStatus ] = useState < CopyStatus > ( CopyStatus . None ) ;
59+ const isCopyDisabled = navigator . clipboard === undefined ;
60+ const [ copyStatus , setCopyStatus ] = useState < CopyStatus > (
61+ isCopyDisabled ? CopyStatus . Disabled : CopyStatus . None
62+ ) ;
5063 const timeoutId = useRef < number | null > ( null ) ;
5164
5265 const copy = useCallback (
@@ -84,6 +97,7 @@ export function useCopy(props?: UseCopyProps): UseCopyReturn {
8497 return {
8598 copyStatus,
8699 copyLabel,
100+ isCopyDisabled,
87101 copy
88102 } ;
89103}
0 commit comments