Skip to content
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

Open
wants to merge 36 commits into
base: develop
Choose a base branch
from

Conversation

rajku-dev
Copy link
Contributor

@rajku-dev rajku-dev commented Dec 19, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced a new CopyButton component for improved clipboard functionality across various components.
    • Enhanced user feedback with tooltips indicating copy status.
    • Added localization support for the "Copy to clipboard" message.
  • Bug Fixes

    • Streamlined the copying mechanism by removing unnecessary state management and timeout handling, improving user experience.

@rajku-dev rajku-dev requested a review from a team as a code owner December 19, 2024 12:47
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces a new CopyButton component in src/components/Common/CopyButton.tsx to standardize clipboard copying functionality across multiple components. The changes replace existing CopyToClipboard implementations in AssetWarrantyCard, SBOMViewer, ShiftDetails, and DoctorVideoSlideover components with the new CopyButton. The new component provides a consistent approach to copying text, managing tooltip states, and providing user feedback through a unified interface.

Changes

File Change Summary
src/components/Common/CopyButton.tsx New component created with state management for clipboard copying and tooltip feedback.
src/components/Assets/AssetWarrantyCard.tsx Replaced CopyToClipboard with new CopyButton.
src/components/Licenses/SBOMViewer.tsx Replaced CopyToClipboard with new CopyButton, removed copyStatus state.
src/components/Shifting/ShiftDetails.tsx Replaced CopyToClipboard with new CopyButton, simplified copy mechanism.
src/components/Facility/DoctorVideoSlideover.tsx Replaced manual copying logic with CopyButton, removed unnecessary state management.
public/locale/en.json Added new localization key for clipboard operation.

Assessment against linked issues

Objective Addressed Explanation
Enhance UI/UX Consistency [#9494]
Improve Clipboard Icon State Changes [#9494]
Efficient Success/Error Notifications [#9494]

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 A rabbit's tale of copy and paste,
Where buttons now dance with clippy's embrace.
No more complex states to trace,
Just click and copy with elegant grace,
Technology hopping at lightning pace! 📋✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 541aa66 and 9c0a815.

📒 Files selected for processing (1)
  • src/components/Common/CopyButton.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Common/CopyButton.tsx

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Dec 19, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 9c0a815
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676a2fdfc1a20c0008dd66ee
😎 Deploy Preview https://deploy-preview-9498--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 improvements

The button implementation looks good, but there are two suggestions for improvement:

  1. Clear the timeout when the component unmounts to prevent memory leaks
  2. 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 function

The copyContent function uses any 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

📥 Commits

Reviewing files that changed from the base of the PR and between bb2c1bc and e836004.

📒 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.

src/components/Assets/AssetWarrantyCard.tsx Outdated Show resolved Hide resolved
src/components/Licenses/SBOMViewer.tsx Outdated Show resolved Hide resolved
src/Utils/utils.ts Outdated Show resolved Hide resolved
src/components/Assets/AssetWarrantyCard.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between e836004 and 029b390.

📒 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.

src/components/Common/CopyButton.tsx Outdated Show resolved Hide resolved
src/components/Common/CopyButton.tsx Outdated Show resolved Hide resolved
src/components/Common/CopyButton.tsx Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between ec05b19 and 68da53b.

📒 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: ⚠️ Potential issue

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: ⚠️ Potential issue

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.

src/components/Licenses/SBOMViewer.tsx Outdated Show resolved Hide resolved
rajku-dev and others added 2 commits December 20, 2024 08:03
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 68da53b and 4f383e6.

📒 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.

src/components/Licenses/SBOMViewer.tsx Outdated Show resolved Hide resolved
src/components/Licenses/SBOMViewer.tsx Outdated Show resolved Hide resolved
src/components/Shifting/ShiftDetails.tsx Outdated Show resolved Hide resolved
src/components/Assets/AssetWarrantyCard.tsx Outdated Show resolved Hide resolved
@rajku-dev
Copy link
Contributor Author

@rithviknishad, can we pass the success/error messages to this utility via this component?
This way, we can handle custom notifications and translations as well.

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 20, 2024
@rithviknishad
Copy link
Member

rithviknishad commented Dec 20, 2024

i don't understand what error would come up when copying, the only notification that needs to be there is "Copied to clipboard" right?

@rajku-dev
Copy link
Contributor Author

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.
If any further changes need to be made please let me know

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between f84ba5b and 90eea5a.

📒 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: ⚠️ Potential issue

Add cleanup, error handling, and accessibility improvements.

The component needs several improvements for production readiness:

  1. Memory leak prevention
  2. Error handling
  3. 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.

public/locale/en.json Show resolved Hide resolved
src/components/Common/CopyButton.tsx Outdated Show resolved Hide resolved
src/components/Common/CopyButton.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 issue

Add proper cleanup and error handling.

The current implementation has potential issues:

  1. The timeout should be cleaned up to prevent memory leaks
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 90eea5a and 6ba3268.

📒 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"))⏎········

src/components/Common/CopyButton.tsx Show resolved Hide resolved
@bodhish
Copy link
Member

bodhish commented Dec 22, 2024

@rajku-dev please complete the Merge Checklist

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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:

  1. Add aria-label for screen readers
  2. Add visual feedback during copied state
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ba3268 and df97cd0.

📒 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:

  1. Make content required by removing undefined type
  2. Add disabled prop
  3. 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:

  1. Add type="button" attribute for accessibility
  2. Implement the disabled state handling
  3. 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.

src/components/Common/CopyButton.tsx Show resolved Hide resolved
@rajku-dev
Copy link
Contributor Author

@rajku-dev please complete the Merge Checklist

@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!

Copy link
Contributor

@Jacobjeevan Jacobjeevan left a 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).

@rajku-dev
Copy link
Contributor Author

rajku-dev commented Dec 23, 2024

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).

@Jacobjeevan i have made the changes as requested

  • Removed anchor tag wrapping in DoctorConnectCard.
  • Implemented conditional rendering for CopyButton in AssetWarrantyCard to display only when serial number is available Deployed Preview Link

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 23, 2024
@rithviknishad rithviknishad added needs review and removed question Further information is requested needs-triage labels Dec 23, 2024
Copy link
Contributor

@Jacobjeevan Jacobjeevan left a 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.

@rajku-dev
Copy link
Contributor Author

Implement the suggestion Rithvik mentioned above, otherwise lgtm.

made the required changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Refactor Clipboard Operations to Utilize new copyToClipboard Utility
5 participants