Skip to content

Conversation

@ib-inu
Copy link
Contributor

@ib-inu ib-inu commented Dec 5, 2024

This pull request implements the copy-code functionality in the project. Users can now easily copy code snippets by clicking on the copy icon next to the code block. The icon changes to a checkmark once the code is successfully copied, providing clear feedback to the user.

Changes made:

  • Added a button with a clipboard icon to copy the code inside code blocks.
  • Used Radix UI's clipboard SVG for the copy icon.
  • Implemented state handling to toggle the icon between a clipboard and checkmark after copying.
  • Added appropriate styling to position the copy button and ensure accessibility.

Summary by CodeRabbit

  • New Features

    • Added a copy-to-clipboard functionality in the Code component, allowing users to easily copy code snippets.
    • Introduced visual feedback with a button that changes icon based on copy status.
  • Chores

    • Updated package dependencies to include @radix-ui/react-icons.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The pull request introduces updates to the @radui/ui package by adding a new dependency on @radix-ui/react-icons version ^1.3.2. Additionally, significant changes are made to the Code component in src/components/ui/Code/Code.tsx, which now includes functionality for copying code to the clipboard. A button is added to trigger this functionality, enhancing the user interface by allowing users to easily copy code snippets.

Changes

File Change Summary
package.json Added dependency: "@radix-ui/react-icons": "^1.3.2"
src/components/ui/Code/Code.tsx Implemented clipboard copy functionality with a button.

Possibly related issues

Possibly related PRs

  • Added Copy component #499: This PR introduces a Copy component for copying text to the clipboard, which relates to the new copy functionality in the Code component of this PR.

Suggested reviewers

  • kotAPI

Poem

🐰 In the garden where code does play,
A button now shines, brightening the day.
With a click, the code leaps to the clipboard,
Hopping along, like a joyful little chord!
New icons join in, a radiant sight,
Copying code has never felt so right! 🌼


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

🧹 Outside diff range and nitpick comments (2)
src/components/ui/Code/Code.tsx (2)

26-40: Enhance accessibility support

While the basic accessibility is present with the title attribute, consider these improvements:

 <div className="rui-code-root">
     <div className='pt-1'>
         <button 
             onClick={handleCopy} 
             className="copy-button" 
             title="Copy code"
+            aria-label={isCopied ? "Code copied" : "Copy code"}
+            aria-pressed={isCopied}
+            data-state={isCopied ? "copied" : "idle"}
         >
             {isCopied
                 ? (
-                    <CheckCircledIcon width={16} height={16} className='inline-block' />
+                    <CheckCircledIcon width={16} height={16} className='inline-block' aria-hidden="true" />
                 )
                 : (
-                    <ClipboardIcon width={16} height={16} />
+                    <ClipboardIcon width={16} height={16} aria-hidden="true" />
                 )}
         </button>
     </div>
-    <code>{children}</code>
+    <code className="block relative">{children}</code>
 </div>

1-41: Consider component architecture improvements

The component structure is good, but consider these architectural improvements:

  1. Extract the copy functionality into a custom hook for reusability:
const useCopyToClipboard = (duration = 2000) => {
  const [isCopied, setIsCopied] = useState(false);
  
  const copy = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), duration);
      return true;
    } catch (error) {
      console.error('Failed to copy text: ', error);
      return false;
    }
  };
  
  return { isCopied, copy };
};
  1. Consider adding a loading state for better UX during the copy operation
  2. Add prop types for customization (e.g., copy duration, custom icons, position of copy button)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7539a7f and ea34120.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/components/ui/Code/Code.tsx (1 hunks)
🔇 Additional comments (2)
src/components/ui/Code/Code.tsx (1)

2-3: LGTM: Imports are appropriate for the copy functionality

The imports are correctly structured and include the necessary icons and React hooks for the implementation.

package.json (1)

132-132: Verify dependency version and security implications

The addition of @radix-ui/react-icons looks good, but let's verify:

✅ Verification successful

Let me gather more information about the current React version in the project to ensure compatibility.


✅ React Icons dependency is compatible with project

The @radix-ui/react-icons@1.3.2 is compatible with the project's React version (^18.2.0) as it supports React ^16.x through ^19.x. This is the only Radix UI dependency in the project, and its peer dependencies are satisfied.

Note: While npm audit shows some vulnerabilities, they are in other dependencies (markdown-to-jsx and rollup) and not in @radix-ui/react-icons itself.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential conflicts with existing dependencies
npm info @radix-ui/react-icons@^1.3.2 peerDependencies

# Check for known vulnerabilities
npm audit @radix-ui/react-icons@^1.3.2

# Verify compatibility with React version
npm info @radix-ui/react-icons@^1.3.2 peerDependencies.react

Length of output: 1145


Script:

#!/bin/bash
# Check React version in package.json
grep -A 1 '"react":' package.json

# Check for any other Radix UI dependencies
grep "@radix-ui/" package.json

Length of output: 210

Comment on lines +10 to +23
const [isCopied, setIsCopied] = useState(false);

const handleCopy = async() => {
try {
await navigator.clipboard.writeText(children as string);
setIsCopied(true);

setTimeout(() => {
setIsCopied(false);
}, 2000);
} catch (error) {
console.error('Failed to copy text: ', error);
}
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add type checking and improve error handling

Several improvements could enhance the robustness of the copy functionality:

  1. Add type checking before casting children to string
  2. Provide user feedback for copy failures
  3. Consider extracting the timeout duration to a constant

Consider this implementation:

 const [isCopied, setIsCopied] = useState(false);
+const COPY_FEEDBACK_DURATION = 2000;
+
+const getTextContent = (children: React.ReactNode): string => {
+    if (typeof children === 'string') return children;
+    if (Array.isArray(children)) return children.map(getTextContent).join('');
+    if (React.isValidElement(children)) return getTextContent(children.props.children);
+    return '';
+};

 const handleCopy = async() => {
     try {
-        await navigator.clipboard.writeText(children as string);
+        const text = getTextContent(children);
+        await navigator.clipboard.writeText(text);
         setIsCopied(true);

         setTimeout(() => {
             setIsCopied(false);
-        }, 2000);
+        }, COPY_FEEDBACK_DURATION);
     } catch (error) {
         console.error('Failed to copy text: ', error);
+        // Consider using a toast or other UI feedback mechanism
+        alert('Failed to copy text to clipboard');
     }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [isCopied, setIsCopied] = useState(false);
const handleCopy = async() => {
try {
await navigator.clipboard.writeText(children as string);
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 2000);
} catch (error) {
console.error('Failed to copy text: ', error);
}
};
const [isCopied, setIsCopied] = useState(false);
const COPY_FEEDBACK_DURATION = 2000;
const getTextContent = (children: React.ReactNode): string => {
if (typeof children === 'string') return children;
if (Array.isArray(children)) return children.map(getTextContent).join('');
if (React.isValidElement(children)) return getTextContent(children.props.children);
return '';
};
const handleCopy = async() => {
try {
const text = getTextContent(children);
await navigator.clipboard.writeText(text);
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, COPY_FEEDBACK_DURATION);
} catch (error) {
console.error('Failed to copy text: ', error);
// Consider using a toast or other UI feedback mechanism
alert('Failed to copy text to clipboard');
}
};

@kotAPI
Copy link
Collaborator

kotAPI commented Dec 5, 2024

Please take a look at the issue, we are supposed to add the copy code functionality for the docs website - not the core library - we can ofcourse make use of this component to build it- but this isn't released in the npm package yet

@ib-inu ib-inu closed this Dec 5, 2024
@ib-inu ib-inu deleted the feature/add-copy-code branch January 3, 2025 14:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants