-
Notifications
You must be signed in to change notification settings - Fork 489
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
Create reusable CopyButton
component
#9498
base: develop
Are you sure you want to change the base?
Create reusable CopyButton
component
#9498
Conversation
WalkthroughThis pull request introduces a new Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (4)
src/Utils/utils.ts (1)
567-570
: Consider enhancing the error message with context.While the null check is a good addition, the error message could be more specific about what content was empty.
- Notification.Error({ msg: "Nothing to copy here!" }); + Notification.Error({ msg: "Cannot copy empty content" });src/components/Licenses/SBOMViewer.tsx (1)
Line range hint
7-7
: Consider creating a custom hook for copy operations.Multiple components share similar copy status management logic. Consider extracting this into a reusable hook:
// src/hooks/useCopyToClipboard.ts export const useCopyToClipboard = () => { const [isCopied, setIsCopied] = useState(false); useEffect(() => { let timeoutId: NodeJS.Timeout; if (isCopied) { timeoutId = setTimeout(() => setIsCopied(false), 2500); } return () => clearTimeout(timeoutId); }, [isCopied]); const copy = async (content: string) => { await copyToClipboard(content); setIsCopied(true); }; return { isCopied, copy }; };This would simplify the components and ensure consistent behavior across the application.
Also applies to: 11-11
src/components/Shifting/ShiftDetails.tsx (2)
45-55
: Consider cleanup and constant extraction improvementsThe button implementation looks good, but there are two suggestions for improvement:
- Clear the timeout when the component unmounts to prevent memory leaks
- Extract the timeout duration as a named constant
Consider applying these changes:
+ const COPY_FEEDBACK_TIMEOUT = 2500; + const showCopyToclipBoard = (data: any) => { + const timeoutRef = useRef<NodeJS.Timeout>(); + + useEffect(() => { + return () => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }; + }, []); + return ( <button className="tooltip tooltip-top" onClick={() => { copyToClipboard(copyContent(data)); setIsCopied(true); - setTimeout(() => setIsCopied(false), 2500); + timeoutRef.current = setTimeout(() => setIsCopied(false), COPY_FEEDBACK_TIMEOUT); }} >
Line range hint
58-82
: Add type safety to copyContent functionThe
copyContent
function usesany
type for its parameter. Consider adding proper typing for better type safety and maintainability.Consider applying these changes:
- const copyContent = (data: any) => { + interface ShiftDetailsData { + patient_object?: { + name?: string; + phone_number?: string; + address?: string; + }; + origin_facility_object?: { + name?: string; + }; + reason?: string; + assigned_facility_type?: string; + } + + const copyContent = (data: ShiftDetailsData) => {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/Utils/utils.ts
(1 hunks)src/components/Assets/AssetWarrantyCard.tsx
(2 hunks)src/components/Licenses/SBOMViewer.tsx
(3 hunks)src/components/Shifting/ShiftDetails.tsx
(2 hunks)
🔇 Additional comments (1)
src/components/Shifting/ShiftDetails.tsx (1)
28-28
: LGTM: Import statement is correctly placed
The copyToClipboard
utility import is properly organized with other utility imports.
Co-authored-by: Rithvik Nishad <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/components/Common/CopyButton.tsx (1)
9-20
: Add JSDoc documentation and improve type constraints.While the interface is well-structured, consider these improvements for better maintainability and type safety:
+/** + * Props for the CopyButton component + * @property {string} content - The text content to be copied + * @property {string} [tooltipContent] - Custom tooltip text + * @property {string} [btnContent] - Custom button text + * @property {number} [resetDuration] - Duration in ms to show copied state + * @property {string} [iconClassName] - CSS class for the icon + * @property {string} [btnClassName] - CSS class for the button + * @property {Object} [icons] - Custom icons for copy states + */ interface CopyButtonProps { content: string; tooltipContent?: string; btnContent?: string; - resetDuration?: number; + resetDuration?: number & { __brand: 'PositiveNumber' }; // Type constraint for positive numbers iconClassName?: string; btnClassName?: string; icons?: { - copied: IconName; - copy: IconName; + copied: Extract<IconName, 'l-check'>; // More specific type + copy: Extract<IconName, 'l-copy'>; }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Common/CopyButton.tsx
(1 hunks)
🔇 Additional comments (1)
src/components/Common/CopyButton.tsx (1)
1-7
: LGTM! Imports are well-organized and appropriate.
The imports are logically grouped and all are necessary for the component's functionality.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/components/Assets/AssetWarrantyCard.tsx
(2 hunks)src/components/Common/CopyButton.tsx
(1 hunks)src/components/Licenses/SBOMViewer.tsx
(3 hunks)src/components/Shifting/ShiftDetails.tsx
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/components/Shifting/ShiftDetails.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Licenses/SBOMViewer.tsx
[error] 183-183: Avoid passing children using a prop
The canonical way to pass children in React is to use JSX elements
(lint/correctness/noChildrenProp)
🔇 Additional comments (5)
src/components/Common/CopyButton.tsx (4)
12-18
: LGTM! Well-structured props interface.
The props interface extends button HTML attributes and variant props, providing good flexibility and type safety.
25-37
:
Fix potential memory leak in setTimeout.
The current implementation doesn't clean up the timeout when the component unmounts or when isCopied
changes.
Apply this diff to fix the memory leak:
const CopyButton = ({ ... }: CopyButtonProps) => {
const [isCopied, setIsCopied] = useState(false);
+
+ React.useEffect(() => {
+ let timeoutId: NodeJS.Timeout;
+ if (isCopied) {
+ timeoutId = setTimeout(() => setIsCopied(false), 2500);
+ }
+ return () => clearTimeout(timeoutId);
+ }, [isCopied]);
return (
<TooltipProvider>
<TooltipComponent content={isCopied ? "Copied!" : tooltipContent}>
<Button
variant="link"
size={size}
onClick={() => {
copyToClipboard(content);
setIsCopied(true);
- setTimeout(() => setIsCopied(false), 2500);
}}
>
Likely invalid or redundant comment.
30-38
:
Add error handling for copyToClipboard operation.
The current implementation doesn't handle potential errors from the copyToClipboard utility.
Apply this diff to add error handling:
<Button
variant="link"
size={size}
onClick={() => {
- copyToClipboard(content);
- setIsCopied(true);
+ try {
+ copyToClipboard(content);
+ setIsCopied(true);
+ } catch (error) {
+ console.error('Failed to copy:', error);
+ // Consider showing error state in tooltip
+ }
}}
>
Likely invalid or redundant comment.
30-38
: 🛠️ Refactor suggestion
Enhance button accessibility.
The button lacks proper accessibility attributes.
Apply this diff to improve accessibility:
<Button
variant="link"
size={size}
+ type="button"
+ disabled={isCopied}
+ aria-label={`Copy ${content} to clipboard`}
onClick={() => {
copyToClipboard(content);
setIsCopied(true);
}}
>
Likely invalid or redundant comment.
src/components/Assets/AssetWarrantyCard.tsx (1)
33-39
: LGTM! Clean implementation of CopyButton.
The component correctly uses CopyButton for the serial number copy functionality. The implementation is clean and maintains good type safety by checking for the existence of the serial number before rendering the CopyButton.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/components/Licenses/SBOMViewer.tsx (1)
185-185
: Use double quotes for consistency.Replace single quotes with double quotes to match the project's style.
- return ''; + return "";🧰 Tools
🪛 GitHub Check: lint
[failure] 185-185:
Replace''
with""
🪛 eslint
[error] 185-185: Replace
''
with""
(prettier/prettier)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Licenses/SBOMViewer.tsx
(3 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
src/components/Licenses/SBOMViewer.tsx
[failure] 185-185:
Replace ''
with ""
🪛 eslint
src/components/Licenses/SBOMViewer.tsx
[error] 185-185: Replace ''
with ""
(prettier/prettier)
🔇 Additional comments (1)
src/components/Licenses/SBOMViewer.tsx (1)
7-7
: LGTM!
The import statement follows the project's conventions and is correctly placed with other component imports.
Co-authored-by: Rithvik Nishad <[email protected]>
Co-authored-by: Rithvik Nishad <[email protected]>
Co-authored-by: Rithvik Nishad <[email protected]>
@rithviknishad, can we pass the success/error messages to this utility via this component? |
i don't understand what error would come up when copying, the only notification that needs to be there is "Copied to clipboard" right? |
that's a point. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/components/Common/CopyButton.tsx (1)
30-30
: Consider adding development-time validation.While returning null for undefined content is valid, consider adding a development-time validation to catch potential issues earlier.
- if (content === undefined) return null; + if (content === undefined) { + if (process.env.NODE_ENV === 'development') { + console.warn('CopyButton: content prop is required but was undefined'); + } + return null; + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
public/locale/en.json
(1 hunks)src/components/Common/CopyButton.tsx
(1 hunks)src/components/Licenses/SBOMViewer.tsx
(3 hunks)src/components/Shifting/ShiftDetails.tsx
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/components/Shifting/ShiftDetails.tsx
- src/components/Licenses/SBOMViewer.tsx
🔇 Additional comments (3)
src/components/Common/CopyButton.tsx (3)
1-19
: LGTM! Clean props interface with good type safety.
The props interface is well-structured with appropriate TypeScript types and extends the correct base interfaces.
21-28
: LGTM! Clean component setup with proper hooks usage.
The component is well-structured with appropriate state management and internationalization setup.
32-56
:
Add cleanup, error handling, and accessibility improvements.
The component needs several improvements for production readiness:
- Memory leak prevention
- Error handling
- Accessibility enhancements
Apply these improvements:
const CopyButton = ({
content,
tooltipContent = "copy_to_clipboard",
children,
size,
+ className,
...props
}: CopyButtonProps) => {
const [isCopied, setIsCopied] = useState(false);
+ const [error, setError] = useState(false);
const { t } = useTranslation();
+ useEffect(() => {
+ let timeoutId: NodeJS.Timeout;
+ if (isCopied || error) {
+ timeoutId = setTimeout(() => {
+ setIsCopied(false);
+ setError(false);
+ }, 2500);
+ }
+ return () => clearTimeout(timeoutId);
+ }, [isCopied, error]);
if (content === undefined) return null;
return (
<TooltipProvider>
<TooltipComponent
- content={isCopied ? t("copied_to_clipboard") : t(tooltipContent)}
+ content={error ? t("copy_failed") : (isCopied ? t("copied_to_clipboard") : t(tooltipContent))}
>
<Button
variant="link"
size={size}
+ disabled={isCopied}
+ aria-label={t("copy_to_clipboard_aria_label", { content })}
+ className={cn(className, isCopied && "opacity-50 cursor-not-allowed")}
+ {...props}
onClick={() => {
- copyToClipboard(content);
- setIsCopied(true);
- setTimeout(() => setIsCopied(false), 2500);
+ try {
+ copyToClipboard(content);
+ setIsCopied(true);
+ setError(false);
+ } catch (err) {
+ console.error('Failed to copy:', err);
+ setError(true);
+ }
}}
>
{children || (
<CareIcon
- icon={isCopied ? "l-check" : "l-copy"}
+ icon={error ? "l-times" : (isCopied ? "l-check" : "l-copy")}
className="text-lg"
/>
)}
</Button>
</TooltipComponent>
</TooltipProvider>
);
};
Likely invalid or redundant comment.
Co-authored-by: Rithvik Nishad <[email protected]>
Co-authored-by: Rithvik Nishad <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/components/Common/CopyButton.tsx (1)
40-44
:⚠️ Potential issueAdd proper cleanup and error handling.
The current implementation has potential issues:
- The timeout should be cleaned up to prevent memory leaks
- Clipboard operations should include error handling
🧹 Nitpick comments (1)
src/components/Common/CopyButton.tsx (1)
30-30
: Remove unnecessary guard clause.If we make the
content
prop required as suggested above, this guard clause becomes unnecessary.- if (content === undefined) return null;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Common/CopyButton.tsx
(1 hunks)
🧰 Additional context used
🪛 eslint
src/components/Common/CopyButton.tsx
[error] 35-35: Replace isCopied·?·t("copied_to_clipboard")·:·tooltipContent·??·t("copy_to_clipboard")
with ⏎··········isCopied⏎············?·t("copied_to_clipboard")⏎············:·(tooltipContent·??·t("copy_to_clipboard"))⏎········
(prettier/prettier)
🪛 GitHub Check: lint
src/components/Common/CopyButton.tsx
[failure] 35-35:
Replace isCopied·?·t("copied_to_clipboard")·:·tooltipContent·??·t("copy_to_clipboard")
with ⏎··········isCopied⏎············?·t("copied_to_clipboard")⏎············:·(tooltipContent·??·t("copy_to_clipboard"))⏎········
🔇 Additional comments (1)
src/components/Common/CopyButton.tsx (1)
1-58
: Verify integration in all components.
Let's ensure all components are properly updated to use the new CopyButton component.
✅ Verification successful
Integration verified across components
The verification shows that:
- No legacy
CopyToClipboard
implementations remain in the codebase - The new
CopyButton
component is properly imported and used in all mentioned components:src/components/Assets/AssetWarrantyCard.tsx
src/components/Licenses/SBOMViewer.tsx
src/components/Shifting/ShiftDetails.tsx
src/components/Facility/DoctorVideoSlideover.tsx
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for any remaining CopyToClipboard usages that should be migrated
echo "Searching for old CopyToClipboard implementations:"
rg "CopyToClipboard"
# Search for direct copyToClipboard utility usage that should use CopyButton
echo -e "\nSearching for direct copyToClipboard utility usage:"
rg "copyToClipboard\(" --type ts --type tsx | grep -v "CopyButton.tsx"
# Verify CopyButton usage in mentioned components
echo -e "\nVerifying CopyButton usage in mentioned components:"
rg "CopyButton" src/components/Assets/AssetWarrantyCard.tsx src/components/Licenses/SBOMViewer.tsx src/components/Shifting/ShiftDetails.tsx src/components/Facility/DoctorVideoSlideover.tsx
Length of output: 1487
🧰 Tools
🪛 eslint
[error] 35-35: Replace isCopied·?·t("copied_to_clipboard")·:·tooltipContent·??·t("copy_to_clipboard")
with ⏎··········isCopied⏎············?·t("copied_to_clipboard")⏎············:·(tooltipContent·??·t("copy_to_clipboard"))⏎········
(prettier/prettier)
🪛 GitHub Check: lint
[failure] 35-35:
Replace isCopied·?·t("copied_to_clipboard")·:·tooltipContent·??·t("copy_to_clipboard")
with ⏎··········isCopied⏎············?·t("copied_to_clipboard")⏎············:·(tooltipContent·??·t("copy_to_clipboard"))⏎········
@rajku-dev please complete the Merge Checklist |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/components/Common/CopyButton.tsx (1)
41-56
: Enhance accessibility and visual feedback.Consider the following improvements:
- Add
aria-label
for screen readers- Add visual feedback during copied state
- Use design tokens for icon sizing instead of hardcoded values
<Button variant="link" size={size} + aria-label={`Copy ${content} to clipboard`} onClick={() => { copyToClipboard(content); setIsCopied(true); setTimeout(() => setIsCopied(false), 2500); }} + className={isCopied ? 'opacity-50' : ''} > {children || ( <CareIcon icon={isCopied ? "l-check" : "l-copy"} - className="text-lg" + className={cn("text-icon-md", isCopied && "text-success")} /> )} </Button>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Common/CopyButton.tsx
(1 hunks)
🔇 Additional comments (4)
src/components/Common/CopyButton.tsx (4)
1-11
: LGTM! Well-organized imports.
The imports are properly organized with clear separation between external and internal dependencies.
13-19
: Enhance type safety and accessibility in props interface.
Previous suggestions about improving the interface remain valid:
- Make
content
required by removingundefined
type - Add
disabled
prop - Add
type
prop with default "button"
44-48
: Add cleanup for setTimeout to prevent memory leaks.
The timeout should be cleaned up using useEffect to prevent potential memory leaks.
21-31
: 🛠️ Refactor suggestion
Add missing button attributes and improve props consistency.
The component implementation could be improved:
- Add
type="button"
attribute for accessibility - Implement the
disabled
state handling - Consider removing the guard clause and make
content
required in the interface instead
const CopyButton = ({
content,
tooltipContent,
children,
size,
+ disabled,
+ type = "button",
...props
}: CopyButtonProps) => {
const [isCopied, setIsCopied] = useState(false);
const { t } = useTranslation();
- if (content === undefined) return null;
Likely invalid or redundant comment.
@bodhish Sir, I have formatted the code using Prettier to resolve the linting errors. I will ensure to take care of this in future commits as well. @rithviknishad, please let me know if any further changes are required. Thank you! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm clicking on the clipboard in DoctorVideoSlideOver also opens up (the dialog for/or) Whatsapp. Right now, we just have that trigger if user clicks anywhere in the card. I would suggest removing that.
And Clipboard isn't disabled on null (check AssetWarrantyCard as an example).
… Double action on clicking CopyButton on Doctor Connect Card
…u-dev/care_fe into issue/9494/revamp-clipboard
@Jacobjeevan i have made the changes as requested
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Implement the suggestion Rithvik mentioned above, otherwise lgtm.
Co-authored-by: Rithvik Nishad <[email protected]>
made the required changes |
Proposed Changes
copyToClipboard
util to handle null copy operationsAssetWarrantyCard
,SBOMViewer
,ShiftDetails
to usecopyToClipboard
utility@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
New Features
CopyButton
component for improved clipboard functionality across various components.Bug Fixes