-
-
Notifications
You must be signed in to change notification settings - Fork 73
Add reusable clipboard utility and copy button #458
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
Open
barry01-hash
wants to merge
3
commits into
theblockcade:main
Choose a base branch
from
barry01-hash:stellarcade
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,113 +1,164 @@ | ||
| import React, { useState, useEffect, useCallback } from 'react'; | ||
| import { copyToClipboard } from '../../utils/v1/clipboard'; | ||
| import React, { useEffect, useMemo, useRef, useState } from 'react'; | ||
| import type { AppError } from '../../types/errors'; | ||
| import { writeToClipboard } from '../../utils/v1/clipboard'; | ||
| import { ErrorNotice } from './ErrorNotice'; | ||
| import { useErrorStore } from '../../store/errorStore'; | ||
|
|
||
| export interface CopyButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { | ||
| /** The text to copy to the clipboard when clicked. */ | ||
| type CopyButtonStatus = 'idle' | 'copying' | 'copied'; | ||
|
|
||
| export interface CopyButtonProps | ||
| extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> { | ||
| text: string; | ||
| /** Custom label when the button is in default state. */ | ||
| children?: React.ReactNode; | ||
| /** Custom test ID for testing. */ | ||
| testId?: string; | ||
| /** How long to show the success state before reverting back to default (ms). Default 2000ms. */ | ||
| idleLabel?: React.ReactNode; | ||
| copyingLabel?: React.ReactNode; | ||
| copiedLabel?: React.ReactNode; | ||
| feedbackDurationMs?: number; | ||
| /** Optional callback to notify parent when text is successfully copied */ | ||
| onCopySuccess?: () => void; | ||
| /** Display format: 'icon' strictly, 'text', or 'both'. Default is 'icon' */ | ||
| variant?: 'icon' | 'text' | 'both'; | ||
| onCopy?: () => void | Promise<void>; | ||
| onCopySuccess?: () => void | Promise<void>; | ||
| onCopyError?: (error: AppError) => void | Promise<void>; | ||
| onClick?: React.MouseEventHandler<HTMLButtonElement>; | ||
| testId?: string; | ||
| } | ||
|
|
||
| /** | ||
| * CopyButton Component - v1 | ||
| * | ||
| * Reusable button to copy text to the clipboard with inline success feedback | ||
| * and global error fallback if copy fails unsupported environment. | ||
| */ | ||
| export const CopyButton: React.FC<CopyButtonProps> = ({ | ||
| export function CopyButton({ | ||
| text, | ||
| children, | ||
| testId = 'copy-button', | ||
| idleLabel, | ||
| copyingLabel, | ||
| copiedLabel, | ||
| feedbackDurationMs = 2000, | ||
| onCopySuccess, | ||
| variant = 'icon', | ||
| onCopy, | ||
| onCopySuccess, | ||
| onCopyError, | ||
| onClick, | ||
| className = '', | ||
| ...rest | ||
| }) => { | ||
| const [copied, setCopied] = useState(false); | ||
| const setError = useErrorStore((state) => state.setError); | ||
|
|
||
| const handleCopy = useCallback(async (e: React.MouseEvent<HTMLButtonElement>) => { | ||
| // Prevent event bubbling if the button is within another interactive element | ||
| e.stopPropagation(); | ||
|
|
||
| // Reset state before copy attempt | ||
| setCopied(false); | ||
|
|
||
| try { | ||
| const result = await copyToClipboard(text); | ||
| if (result.success) { | ||
| setCopied(true); | ||
| onCopySuccess?.(); | ||
| } else { | ||
| setError({ | ||
| code: 'CLIPBOARD_NOT_SUPPORTED', | ||
| domain: 'ui', | ||
| severity: 'user_actionable', | ||
| message: 'Unable to copy text to clipboard.', | ||
| action: 'Please select and copy the text manually.', | ||
| }); | ||
| disabled = false, | ||
| type = 'button', | ||
| testId = 'copy-button', | ||
| ...buttonProps | ||
| }: CopyButtonProps) { | ||
| const [status, setStatus] = useState<CopyButtonStatus>('idle'); | ||
| const [error, setError] = useState<AppError | null>(null); | ||
| const timeoutRef = useRef<number | null>(null); | ||
| const setGlobalError = useErrorStore((state) => state.setError); | ||
|
|
||
| useEffect(() => { | ||
| return () => { | ||
| if (timeoutRef.current !== null) { | ||
| window.clearTimeout(timeoutRef.current); | ||
| } | ||
| } catch (error) { | ||
| setError({ | ||
| code: 'CLIPBOARD_ERROR', | ||
| domain: 'ui', | ||
| severity: 'terminal', | ||
| message: 'An unexpected error occurred while trying to copy text.', | ||
| debug: { originalError: error } | ||
| }); | ||
| }; | ||
| }, []); | ||
|
|
||
| const isBusy = status === 'copying'; | ||
| const isDisabled = disabled || isBusy; | ||
| const showIcon = variant === 'icon' || variant === 'both'; | ||
| const showText = variant === 'text' || variant === 'both'; | ||
|
|
||
| const resolvedIdleLabel = idleLabel ?? children ?? 'Copy'; | ||
| const resolvedCopyingLabel = copyingLabel ?? 'Copying...'; | ||
| const resolvedCopiedLabel = copiedLabel ?? 'Copied!'; | ||
|
|
||
| const textLabel = useMemo(() => { | ||
| if (status === 'copying') { | ||
| return resolvedCopyingLabel; | ||
| } | ||
| }, [text, onCopySuccess, setError]); | ||
|
|
||
| // Handle automatic timeout for success feedback | ||
| useEffect(() => { | ||
| if (!copied) return; | ||
| if (status === 'copied') { | ||
| return resolvedCopiedLabel; | ||
| } | ||
|
|
||
| const timeout = setTimeout(() => { | ||
| setCopied(false); | ||
| return resolvedIdleLabel; | ||
| }, [ | ||
| resolvedCopiedLabel, | ||
| resolvedCopyingLabel, | ||
| resolvedIdleLabel, | ||
| status, | ||
| ]); | ||
|
|
||
| const statusMessage = status === 'copied' ? 'Copied to clipboard.' : ''; | ||
| const iconName = status === 'copied' ? 'check-circle' : 'copy'; | ||
|
|
||
| const scheduleReset = () => { | ||
| if (timeoutRef.current !== null) { | ||
| window.clearTimeout(timeoutRef.current); | ||
| } | ||
|
|
||
| timeoutRef.current = window.setTimeout(() => { | ||
| setStatus('idle'); | ||
| timeoutRef.current = null; | ||
| }, feedbackDurationMs); | ||
| }; | ||
|
|
||
| const handleCopy = async ( | ||
| event: React.MouseEvent<HTMLButtonElement>, | ||
| ): Promise<void> => { | ||
| onClick?.(event); | ||
|
|
||
| if (event.defaultPrevented || isDisabled) { | ||
| return; | ||
| } | ||
|
|
||
| return () => clearTimeout(timeout); | ||
| }, [copied, feedbackDurationMs]); | ||
| setError(null); | ||
| setStatus('copying'); | ||
|
|
||
| const baseClass = `copy-button copy-button--${variant} ${className}`.trim(); | ||
| const result = await writeToClipboard(text); | ||
|
|
||
| if (result.ok) { | ||
| await onCopy?.(); | ||
| await onCopySuccess?.(); | ||
| setStatus('copied'); | ||
| scheduleReset(); | ||
| return; | ||
| } | ||
|
|
||
| setStatus('idle'); | ||
| setError(result.error); | ||
| setGlobalError(result.error); | ||
| await onCopyError?.(result.error); | ||
| }; | ||
|
|
||
| return ( | ||
| <button | ||
| type="button" | ||
| className={baseClass} | ||
| onClick={handleCopy} | ||
| data-testid={testId} | ||
| aria-label={copied ? 'Copied to clipboard' : 'Copy to clipboard'} | ||
| aria-live="polite" | ||
| {...rest} | ||
| > | ||
| <span className="copy-button__content"> | ||
| {(variant === 'icon' || variant === 'both') && ( | ||
| <span | ||
| className={`icon icon--${copied ? 'check-circle' : 'copy'}`} | ||
| aria-hidden="true" | ||
| <div className={className} data-testid={`${testId}-container`}> | ||
| <button | ||
| {...buttonProps} | ||
| type={type} | ||
| disabled={isDisabled} | ||
| onClick={handleCopy} | ||
| aria-busy={isBusy} | ||
| aria-disabled={isDisabled} | ||
| aria-label={status === 'copied' ? 'Copied to clipboard' : 'Copy to clipboard'} | ||
| data-testid={testId} | ||
| > | ||
| {showIcon ? ( | ||
| <span | ||
| className={`icon icon--${iconName}`} | ||
| aria-hidden="true" | ||
| data-testid={`${testId}-icon`} | ||
| /> | ||
| )} | ||
|
|
||
| {(variant === 'text' || variant === 'both') && ( | ||
| <span className="copy-button__text" data-testid={`${testId}-text`}> | ||
| {copied ? 'Copied!' : (children || 'Copy')} | ||
| </span> | ||
| )} | ||
| ) : null} | ||
|
|
||
| {showText ? ( | ||
| <span data-testid={`${testId}-text`}>{textLabel}</span> | ||
| ) : null} | ||
| </button> | ||
|
|
||
| <span role="status" aria-live="polite" data-testid={`${testId}-status`}> | ||
| {statusMessage} | ||
| </span> | ||
| </button> | ||
|
|
||
| {error ? ( | ||
| <ErrorNotice | ||
| error={error} | ||
| onDismiss={() => setError(null)} | ||
| testId={`${testId}-error`} | ||
| /> | ||
| ) : null} | ||
| </div> | ||
| ); | ||
| }; | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| export default CopyButton; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.