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

Closed

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.
    • Simplified the structure of components by replacing manual copy implementations with the new CopyButton.

@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.
cypress/pageobject/Patient/PatientDoctorConnect.ts Updated selector for phone icon in clickCopyPhoneNumber method.

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

needs review, 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 620e74c and c7b8f77.

📒 Files selected for processing (1)
  • public/locale/en.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json

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 c7b8f77
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676e2c983331be0008674ae7
😎 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

@rithviknishad rithviknishad self-requested a review December 23, 2024 12:55
@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

@nihal467
Copy link
Member

@rajku-dev fix the cypress test related to your PR

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 25, 2024
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: 0

🧹 Nitpick comments (3)
cypress/pageobject/Patient/PatientDoctorConnect.ts (1)

25-25: Consider scoping to the parent context.
You're using .get("#copy-alt-phone-button") after selecting the parent element, which restarts the query from document. If your intention is to find the button only within the parent, you might want to use .find("#copy-alt-phone-button") to scope the search and prevent accidentally selecting elements elsewhere on the page.

-      .get("#copy-alt-phone-button") 
+      .find("#copy-alt-phone-button")
src/components/Common/CopyButton.tsx (2)

13-19: Consider making content required.
If the component is always expected to copy some non-empty string, removing | undefined from content and avoiding runtime checks might simplify the API. However, if intentionally optional, returning null early is fine.


42-51: Add an aria-label for better accessibility.
Providing an explicit aria-label describing the copy action improves accessibility for screen reader users.

 <Button
   id={id}
   variant="link"
   size={size}
+  aria-label={t("copy_to_clipboard")}
   onClick={() => {
     copyToClipboard(content);
     setIsCopied(true);
     setTimeout(() => setIsCopied(false), 2500);
   }}
 >
📜 Review details

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

📥 Commits

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

📒 Files selected for processing (3)
  • cypress/pageobject/Patient/PatientDoctorConnect.ts (1 hunks)
  • src/components/Common/CopyButton.tsx (1 hunks)
  • src/components/Facility/DoctorVideoSlideover.tsx (3 hunks)
🔇 Additional comments (4)
src/components/Common/CopyButton.tsx (1)

31-31: Returning null could cause layout shifts.
When content is undefined, the component renders nothing. Ensure that callers expect the button to be absent in that scenario.

src/components/Facility/DoctorVideoSlideover.tsx (3)

8-8: Great integration of CopyButton.
The import of CopyButton centralizes and streamlines clipboard functionality, making the code more consistent across the application.


188-192: Potential PII exposure in shared link.
Appending window.location.href to the WhatsApp message could expose sensitive information if the URL includes patient details. Consider reviewing whether this data should remain private.


300-306: Good usage of CopyButton.
Passing alt_phone_number as content nicely leverages the new component's capability to handle empty or valid content. The optional tooltip also provides a consistent user experience.

@rajku-dev
Copy link
Contributor Author

running individual cypress test (cloud api) in chrome for debugging purposes, it is failing due to a different reason compared to it failing here on github
image
[not able to find the specified patient name "Dummy Patient Eleven"]

@rajku-dev
Copy link
Contributor Author

rajku-dev commented Dec 27, 2024

@rajku-dev fix the cypress test related to your PR

@nihal467
All Cypress tests related to this PR have been fixed.
Thank you

@Jacobjeevan Jacobjeevan added needs testing and removed question Further information is requested changes required needs-triage labels Dec 28, 2024
@rithviknishad rithviknishad changed the base branch from develop to form-field-v1 December 30, 2024 15:43
@bodhish bodhish deleted the branch ohcnetwork:form-field-v1 December 31, 2024 06:36
@bodhish bodhish closed this Dec 31, 2024
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