Skip to content

Conversation

@kotAPI
Copy link
Collaborator

@kotAPI kotAPI commented Dec 9, 2024

Fixes broken tests in CI by specifying how ref is passed - #622

Summary by CodeRabbit

  • New Features

    • Enhanced type safety and specificity for the Primitive component's props.
    • Improved handling of the asChild prop for better ref typing.
  • Bug Fixes

    • Corrected prop typing for cloned elements to ensure compatibility with HTML attributes.
  • Documentation

    • Updated interface and function signatures for clarity on public entities.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The changes in the Primitive component located in src/core/primitives/Primitive/index.tsx focus on enhancing type safety and specificity for props and forwarded refs. The PrimitiveProps interface is refined to extend React.HTMLAttributes<HTMLElement>, improving prop typing. Modifications to the createPrimitiveComponent function ensure that when the asChild prop is true, props are correctly typed when cloning elements. Additionally, the mapping of supported HTML elements to PrimitiveComponent is updated to maintain type structure and adherence to React's typing conventions.

Changes

File Path Change Summary
src/core/primitives/Primitive/index.tsx Updated PrimitiveProps interface to extend React.HTMLAttributes<HTMLElement>. Improved type handling in createPrimitiveComponent for asChild prop. Updated type definition for Primitive to ensure compliance with PrimitiveProps and React.RefAttributes<HTMLElement>.

Poem

In the land of code where rabbits play,
Types are safe, come what may!
With props refined and refs in tow,
The Primitive shines, watch it grow!
Hop along, let changes unfold,
A tale of types, in code retold! 🐇✨


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.

@codecov
Copy link

codecov bot commented Dec 9, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.75%. Comparing base (db8664c) to head (52b8605).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #623      +/-   ##
==========================================
+ Coverage   96.64%   96.75%   +0.10%     
==========================================
  Files          15       15              
  Lines         149      154       +5     
  Branches       28       29       +1     
==========================================
+ Hits          144      149       +5     
  Misses          5        5              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@kotAPI kotAPI merged commit cf5e8c1 into main Dec 9, 2024
7 checks passed
@kotAPI kotAPI deleted the pranay/fix-tests branch December 9, 2024 12:43
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

🧹 Outside diff range and nitpick comments (1)
src/core/primitives/Primitive/index.tsx (1)

19-22: Consider improving type safety without type assertions

The current implementation uses a type assertion (as React.HTMLAttributes<HTMLElement>), which bypasses TypeScript's type checking. Consider using a more type-safe approach.

Consider this alternative approach:

type ElementProps<T> = Omit<React.HTMLAttributes<T>, keyof PrimitiveProps>;

function cloneElementWithRef<T extends HTMLElement>(
  element: React.ReactElement,
  props: ElementProps<T>,
  ref: React.Ref<T>
) {
  return React.cloneElement(element, {
    ...props,
    ref
  });
}

This would provide better type inference and catch potential type mismatches at compile time rather than runtime.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7dcdcec and 52b8605.

📒 Files selected for processing (1)
  • src/core/primitives/Primitive/index.tsx (1 hunks)
🔇 Additional comments (2)
src/core/primitives/Primitive/index.tsx (2)

19-22: 🛠️ Refactor suggestion

Consider improving ref handling for component composition

The current implementation might have issues when the child component already has a ref. Consider using a ref merging utility to handle both refs properly.

Here's a suggested improvement:

- return React.cloneElement(children, { 
-     ...elementProps, 
-     ref
- } as React.HTMLAttributes<HTMLElement>);
+ // Add this utility function at the top of the file
+ const mergeRefs = <T extends any>(
+   refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | null | undefined>
+ ): React.RefCallback<T> => {
+   return (value) => {
+     refs.forEach((ref) => {
+       if (typeof ref === 'function') {
+         ref(value);
+       } else if (ref != null) {
+         (ref as React.MutableRefObject<T | null>).current = value;
+       }
+     });
+   };
+ };
+
+ // In the component:
+ const childrenRef = (children as any).ref;
+ return React.cloneElement(children, {
+   ...elementProps,
+   ref: childrenRef ? mergeRefs([childrenRef, ref]) : ref
+ } as React.HTMLAttributes<HTMLElement>);

This change will:

  1. Properly handle cases where both the primitive and child component have refs
  2. Maintain ref functionality for both components
  3. Preserve type safety while being more flexible

Let's verify if there are any existing ref merging utilities in the codebase:


19-22: Verify ref handling in test cases

Since this PR aims to fix broken tests, let's ensure all ref-related test cases are covered.

Let's check for existing test cases and potential issues:

✅ Verification successful

Ref handling implementation is correct and consistent

The verification shows that:

  1. The Primitive component is the only one using React.cloneElement with ref forwarding, which is the correct pattern for polymorphic components
  2. The implementation follows React's ref forwarding best practices using React.forwardRef
  3. Other components in the codebase handle refs directly through the ref prop without cloning, which is the expected pattern
  4. The test file for the Primitive component covers basic rendering scenarios, though it could benefit from additional ref-specific test cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test files related to Primitive component
fd -e test.tsx -e spec.tsx -e test.ts -e spec.ts

# Search for ref-related test cases
rg -A 5 "ref.*=.*{" --type=typescript

# Look for similar patterns in other components
ast-grep --pattern 'React.cloneElement($_, { ref: $_ })'

Length of output: 591


Script:

#!/bin/bash
# Search for test files specifically related to Primitive component
cat src/core/primitives/Primitive/tests/Primitive.test.tsx

# Search for ref-related test cases with fixed regex
rg "ref\s*=\s*\{" --type=typescript -A 5

# Look for similar patterns with more specific ast-grep pattern
ast-grep --pattern 'React.cloneElement($_, { $$$, ref: $_ })'

Length of output: 1289


Script:

#!/bin/bash
# Search for ref-related test cases with correct file types
rg "ref\s*=\s*\{" -t tsx -t ts -A 5

# Look for ref forwarding patterns in the codebase
ast-grep --pattern 'React.forwardRef<$_, $_>($_)'

# Search for other components using cloneElement
rg "React\.cloneElement" -t tsx -t ts -A 5

Length of output: 1191


Script:

#!/bin/bash
# Search for ref-related test cases with extension
rg "ref\s*=\s*\{" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' -t tsx -t ts -A 5

# Search for cloneElement usage with extension
rg "React\.cloneElement" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' -t tsx -t ts -A 5

# Check if there are any ref-related tests in other components
fd -e test.tsx -e test.ts -x grep -l "ref" {}

Length of output: 7612

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