Skip to content

Conversation

@GoldGroove06
Copy link
Contributor

@GoldGroove06 GoldGroove06 commented Mar 5, 2025

closes #919

Summary by CodeRabbit

  • Refactor

    • Improved the handling and merging of customizable attributes on button elements for a more streamlined and consistent experience using a hook-based approach.
  • Tests

    • Updated tests to ensure buttons consistently display the correct behavior with various configurations, now utilizing the new hook-based methods for attribute generation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Walkthrough

The changes update how data attributes are managed in the Button component. The previous implementation utilized createDataAttribute and composeAttributes, which have been replaced with the hook-based functions useCreateDataAttribute and useComposeAttributes. This shift maintains similar logic for handling attributes while adapting to a new method of invocation. Corresponding updates were made to the tests to reflect these changes in both the Button component and the data attribute utilities.

Changes

File(s) Change Summary
src/components/ui/Button/Button.tsx Updated the Button component to use useCreateDataAttribute and useComposeAttributes for data attribute management.
src/core/hooks/createDataAttribute/(index.ts, createDataAttribute.test.tsx) Renamed and updated utility functions to handle data attributes with new parameters and logic, along with corresponding test updates to reflect these changes.

Possibly related PRs

  • Release/0.0.29 #791: The changes in this PR relate to enhancements made to the Button component, which introduced color support and are connected to the updates in data attribute management.

Suggested labels

automerge

Suggested reviewers

  • kotAPI

Poem

I'm a hopping rabbit, coding through the night,
With new functions that set our code just right.
Data attributes now flow, neat and clear,
Merging like magic, making bugs disappear.
Happy bytes and carrots—let's cheer the light!
🥕🐇 Happy coding!


📜 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 a605799 and 0fb16ae.

📒 Files selected for processing (7)
  • src/components/ui/Button/Button.tsx (2 hunks)
  • src/components/ui/Button/Button.tsx (2 hunks)
  • src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (1 hunks)
  • src/core/hooks/createDataAttribute/index.ts (1 hunks)
  • src/components/ui/Button/Button.tsx (2 hunks)
  • src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (3 hunks)
  • src/core/hooks/createDataAttribute/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/core/hooks/createDataAttribute/createDataAttribute.test.tsx
  • src/core/hooks/createDataAttribute/index.ts
  • src/components/ui/Button/Button.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (9)
src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (3)

1-1: Good update to import hooks instead of utility functions

The test file has been properly updated to import the new hook-based implementations of the data attribute utilities.


13-18: Properly updated test to use hooks

The test case has been correctly updated to use the new hook-based implementations useCreateDataAttribute and useComposeAttributes while maintaining the same testing logic.


33-38: Properly updated second test case to use hooks

Similarly, the second test case has been correctly updated to use the hook versions of the data attribute utilities, ensuring consistent usage throughout the test file.

src/components/ui/Button/Button.tsx (2)

22-24: ⚠️ Potential issue

Function name mismatch with hooks implementation

The function names used here don't match the hook implementations. These should be updated to use the hooks.

-const dataAttributes = createDataAttributes("button", { variant, size });
-const accentAttributes = createDataAttributes("accent", { color });
-const mergedAttributes = mergeAttributes(dataAttributes, accentAttributes);
+const dataAttributes = useCreateDataAttribute("button", { variant, size });
+const accentAttributes = useCreateDataAttribute("accent", { color });
+const mergedAttributes = useComposeAttributes(dataAttributes, accentAttributes);

Likely an incorrect or invalid review comment.


6-6: ⚠️ Potential issue

Naming inconsistency in imported functions

There's a naming inconsistency between this file and the hooks implementation. The Button component imports createDataAttributes and mergeAttributes from "~/core/createDataAttributes", but the hooks file defines useCreateDataAttribute and useComposeAttributes.

Either:

  1. This import path points to a different implementation, or
  2. The import should be updated to use the hook versions

Since the test file has been updated to use the hooks, this Button component should also use the same hooks.

-import  { createDataAttributes, mergeAttributes }  from "~/core/createDataAttributes"
+import  { useCreateDataAttribute, useComposeAttributes }  from "~/core/hooks/createDataAttribute"

Likely an incorrect or invalid review comment.

src/core/hooks/createDataAttribute/index.ts (4)

1-3: Good improvement for handling null attributes

The hook now properly handles null attributes by returning an empty object. This improves robustness and prevents potential runtime errors.


5-7: Improved filtering and mapping logic

The code looks good and maintains the same functionality while being more robust against null/undefined values.


11-12: Enhanced compose attributes function to handle null values

Good update to filter out null objects before merging. This makes the function more robust and prevents errors when composing attributes.


1-13: Confirm if these are true React hooks

While you've renamed the functions to follow React's hook naming convention (prefixing with "use"), these don't appear to use any React hooks internally (like useState, useEffect, etc.).

If these are intended to be true React hooks:

  1. Consider if you need to use any React hooks internally
  2. Ensure they follow React's rules of hooks (called at the top level, only called from React functions)

If they're just utility functions:

  1. The naming is fine if it helps clarify their usage pattern
  2. Verify that they're being used correctly in components
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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: 0

🧹 Nitpick comments (6)
src/components/ui/Button/Button.tsx (2)

6-6: Fix import formatting for consistency.

There are extra spaces in the import statement that should be removed for consistency with other imports in the file.

-import  { createDataAttributes, mergeAttributes }  from "~/core/createDataAttributes"
+import { createDataAttributes, mergeAttributes } from "~/core/createDataAttributes";

20-24: Update comments to reflect the new implementation.

The existing comments (lines 20-21) don't fully reflect the new implementation. The comments mention only applying accent color if present, but now both button and accent attributes are handled by the utility functions which filter out empty values.

-    // apply data attribute for accent color
-    // apply attribute only if color is present
+    // Create data attributes for button properties and accent color
+    // Empty or undefined values will be automatically filtered out
     const dataAttributes = createDataAttributes("button", { variant, size });
     const accentAttributes = createDataAttributes("accent", { color });
     const mergedAttributes = mergeAttributes(dataAttributes, accentAttributes);
src/core/createDataAttributes/index.ts (4)

1-7: Add JSDoc documentation to improve function discoverability.

Adding JSDoc comments would help other developers understand the purpose and usage of this utility function.

+/**
+ * Creates data attributes with a specified prefix.
+ * Filters out undefined and empty string values from the attributes object.
+ * @param prefix - The prefix to add to each data attribute key
+ * @param attributes - Object containing attribute key-value pairs
+ * @returns Object with transformed data attribute keys
+ */
 export const createDataAttributes = (prefix: string, attributes: Record<string, any>) => {
     return Object.fromEntries(
         Object.entries(attributes)
             .filter(([_, value]) => value !== undefined && value !== '')
             .map(([key, value]) => [`data-${prefix}-${key}`, value])
     );
 };

9-11: Add JSDoc and consider a more specific return type.

Adding documentation and specifying the return type would improve usability and type safety.

+/**
+ * Merges multiple attribute objects into a single object.
+ * Later objects will override properties from earlier objects if keys collide.
+ * @param attributeObjects - Array of attribute objects to merge
+ * @returns A merged attribute object
+ */
-export const mergeAttributes = (...attributeObjects: Record<string, any>[]) => {
+export const mergeAttributes = (...attributeObjects: Record<string, any>[]): Record<string, any> => {
     return Object.assign({}, ...attributeObjects);
 };

1-11: Consider using more specific types for improved type safety.

The current implementation uses Record<string, any> which is quite permissive. Consider using more specific types to restrict what values can be passed.

You could define interfaces for your attribute objects and use generic types to improve type safety:

interface AttributeValue {
  [key: string]: string | number | boolean;
}

/**
 * Creates data attributes with a specified prefix.
 * Filters out undefined and empty string values from the attributes object.
 * @param prefix - The prefix to add to each data attribute key
 * @param attributes - Object containing attribute key-value pairs
 * @returns Object with transformed data attribute keys
 */
export const createDataAttributes = <T extends Record<string, any>>(
  prefix: string, 
  attributes: T
): Record<string, string | number | boolean> => {
  return Object.fromEntries(
    Object.entries(attributes)
      .filter(([_, value]) => value !== undefined && value !== '')
      .map(([key, value]) => [`data-${prefix}-${key}`, value])
  );
};

/**
 * Merges multiple attribute objects into a single object.
 * Later objects will override properties from earlier objects if keys collide.
 * @param attributeObjects - Array of attribute objects to merge
 * @returns A merged attribute object
 */
export const mergeAttributes = (
  ...attributeObjects: Record<string, string | number | boolean>[]
): Record<string, string | number | boolean> => {
  return Object.assign({}, ...attributeObjects);
};

4-4: Consider handling additional falsy values in the filter.

The current filter excludes undefined and empty strings, but you might want to consider other falsy values like null or false depending on your use case.

-            .filter(([_, value]) => value !== undefined && value !== '')
+            .filter(([_, value]) => value !== undefined && value !== '' && value !== 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 07ced7f and 312b5db.

📒 Files selected for processing (2)
  • src/components/ui/Button/Button.tsx (2 hunks)
  • src/core/createDataAttributes/index.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (2)
src/components/ui/Button/Button.tsx (1)

22-24: Good refactoring of data attributes handling!

This is a good improvement over manually constructing data attributes. The code is now more maintainable and follows a consistent pattern for data attribute creation.

src/core/createDataAttributes/index.ts (1)

9-11:

❓ Verification inconclusive

Add unit tests for these utility functions.

These utility functions are crucial for component behavior and should have unit tests to ensure they work as expected in various scenarios.

Consider creating tests for both functions to verify:

  1. That createDataAttributes correctly filters out undefined/empty values
  2. That the data attribute keys are correctly formatted
  3. That mergeAttributes correctly merges multiple objects
  4. That property collisions are resolved correctly

🏁 Script executed:

#!/bin/bash
# Check if there are any tests for these utility functions

echo "Searching for existing tests for createDataAttributes..."
fd "createDataAttributes" --type file --extension spec.ts --extension test.ts
fd "createDataAttributes" --type file --extension spec.tsx --extension test.tsx

# Or use grep if fd is not available
echo "Alternative search using grep..."
find . -name "*.spec.ts" -o -name "*.test.ts" -o -name "*.spec.tsx" -o -name "*.test.tsx" | xargs grep -l "createDataAttributes" 2>/dev/null

Length of output: 484


Action: Add Unit Tests for Utility Functions

It appears that there are currently no unit tests for the utility functions in this file. To ensure that the createDataAttributes and mergeAttributes functions behave correctly in all intended scenarios, please add unit tests that cover the following areas:

  • Verify that createDataAttributes filters out undefined or empty values.
  • Check that data attribute keys are correctly formatted.
  • Ensure that mergeAttributes correctly merges multiple objects.
  • Confirm that property collisions are resolved as expected.

Please create the appropriate test files (e.g., within a matching .spec.ts or .test.ts file) to cover these cases. After adding the tests, manually verify that the functions behave as intended under various conditions.

);
};

export const mergeAttributes = (...attributeObjects: Record<string, any>[]) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

call this composeAttributes

if (color) {
data_attributes['data-accent-color'] = color;
}
const dataAttributes = createDataAttributes("button", { variant, size });
Copy link
Collaborator

Choose a reason for hiding this comment

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

looking good :D

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 (7)
src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (3)

6-7: Remove unnecessary blank line.

There's an extra blank line after the describe block opening. This violates the linting rule against padded blocks.

describe("createDataAttribute", () => {
-    
  test("attributes are created and applied", () => {
🧰 Tools
🪛 ESLint

[error] 6-8: Block must not be padded by blank lines.

(padded-blocks)


8-26: Test is well structured but could benefit from more descriptive naming.

The test correctly validates that attributes are properly created and applied to the Button component. However, consider using a more descriptive test name that indicates what functionality is being verified.

-  test("attributes are created and applied", () => {
+  test("should create and apply multiple data attributes when valid values are provided", () => {

1-47: Consider adding tests for additional edge cases.

While the current tests cover the basic functionality and handling of undefined/empty values, consider adding tests for these additional scenarios:

  1. Testing with null values
  2. Testing with boolean values (true/false)
  3. Testing with numeric values (0, negative numbers)
  4. Testing the composition of multiple attribute objects with overlapping keys

Would you like me to provide examples of these additional test cases?

🧰 Tools
🪛 ESLint

[error] 6-8: Block must not be padded by blank lines.

(padded-blocks)

src/core/hooks/createDataAttribute/index.ts (3)

1-7: Add stronger type safety for the createDataAttribute function.

The current implementation uses any for attribute values, which loses type safety. Consider using a more specific type or generic parameter to maintain better type safety while still allowing flexibility.

-export const createDataAttribute = (prefix: string, attributes: Record<string, any>) => {
+export const createDataAttribute = <T extends Record<string, string | number | boolean | undefined>>(prefix: string, attributes: T) => {
    return Object.fromEntries(
        Object.entries(attributes)
            .filter(([_, value]) => value !== undefined && value !== '')
            .map(([key, value]) => [`data-${prefix}-${key}`, value])
    );
};

9-11: Add stronger type safety for the composeAttributes function.

Similar to the previous comment, consider improving the type safety of this function by using a more specific type or generic parameter.

-export const composeAttributes = (...attributeObjects: Record<string, any>[]) => {
+export const composeAttributes = <T extends Record<string, string | number | boolean>>(...attributeObjects: T[]) => {
    return Object.assign({}, ...attributeObjects);
};

1-11: Add JSDoc comments for better documentation.

Adding JSDoc comments would improve the documentation of these utility functions, making it easier for other developers to understand their purpose and usage.

+/**
+ * Creates data attributes with the specified prefix.
+ * @param prefix The prefix to add to each data attribute name.
+ * @param attributes Record of attribute key-value pairs.
+ * @returns Record of data attributes with keys formatted as `data-${prefix}-${key}`.
+ */
export const createDataAttribute = (prefix: string, attributes: Record<string, any>) => {
    return Object.fromEntries(
        Object.entries(attributes)
            .filter(([_, value]) => value !== undefined && value !== '')
            .map(([key, value]) => [`data-${prefix}-${key}`, value])
    );
};

+/**
+ * Composes multiple attribute objects into a single object.
+ * @param attributeObjects Array of attribute objects to compose.
+ * @returns Single object containing all attributes from the input objects.
+ */
export const composeAttributes = (...attributeObjects: Record<string, any>[]) => {
    return Object.assign({}, ...attributeObjects);
};
src/components/ui/Button/Button.tsx (1)

22-30: Consider moving data attribute creation to a custom hook.

Since these data attribute utilities are in a hooks directory, consider creating a custom hook that encapsulates this logic for better reusability across components.

For example:

// In a new file: src/core/hooks/createDataAttribute/useComponentAttributes.ts
import { createDataAttribute, composeAttributes } from './index';

export const useButtonAttributes = (variant?: string, size?: string, color?: string) => {
  const dataAttributes = createDataAttribute("button", { variant, size });
  const accentAttributes = createDataAttribute("accent", { color });
  return composeAttributes(dataAttributes, accentAttributes);
};

Then in Button.tsx:

-import  { createDataAttribute, composeAttributes }  from "~/core/hooks/createDataAttribute"
+import { useButtonAttributes } from "~/core/hooks/createDataAttribute/useComponentAttributes"

// ...

const Button = ({ children, type = 'button', customRootClass = '', className = '', variant = '', size = '', color = '', ...props }: ButtonProps) => {
    const rootClass = customClassSwitcher(customRootClass, COMPONENT_NAME);
-    const dataAttributes = createDataAttribute("button", { variant, size });
-    const accentAttributes = createDataAttribute("accent", { color });
-    const composedAttributes = composeAttributes(dataAttributes, accentAttributes);
+    const composedAttributes = useButtonAttributes(variant, size, color);

    // ...
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 312b5db and a605799.

📒 Files selected for processing (3)
  • src/components/ui/Button/Button.tsx (2 hunks)
  • src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (1 hunks)
  • src/core/hooks/createDataAttribute/index.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
src/core/hooks/createDataAttribute/createDataAttribute.test.tsx

[error] 6-8: Block must not be padded by blank lines.

(padded-blocks)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
src/core/hooks/createDataAttribute/createDataAttribute.test.tsx (2)

1-4: Imports are well organized.

The imports section is clean and properly imports all necessary dependencies: the custom hooks being tested, React, testing utilities, and the Button component.


28-46: Effective testing of edge cases.

This test effectively verifies that undefined or empty values are properly filtered out when creating data attributes. The assertions correctly check that the corresponding attributes are not present in the rendered button.

src/components/ui/Button/Button.tsx (3)

6-6: Well-structured import of the new utility functions.

The import is correctly formatted and placed appropriately with other imports.


22-24: Good implementation of the new data attribute utilities.

The code effectively uses the new utility functions to replace the manual construction of data attributes. This approach is more maintainable and reduces the risk of errors.


30-31: Ensure proper attribute spreading order.

The order of spreading attributes is important. The current implementation correctly places composedAttributes before props, which allows any data attributes directly passed in props to override those created by the utility functions if necessary.

render(<Component />);

expect(screen.getByText("Click me")).toBeInTheDocument();
expect(screen.getByText("Click me")).toHaveAttribute("data-button-variant","primary");
Copy link
Collaborator

Choose a reason for hiding this comment

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

nice one

@@ -0,0 +1,11 @@
export const createDataAttribute = (prefix: string, attributes: Record<string, any>) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

can we convert these to react hooks?

@rad-ui rad-ui deleted a comment from GoldGroove06 Mar 8, 2025
@kotAPI
Copy link
Collaborator

kotAPI commented Mar 19, 2025

Closing this in favor of #934

@kotAPI kotAPI closed this Mar 19, 2025
kotAPI pushed a commit that referenced this pull request Mar 19, 2025
@kotAPI kotAPI deleted the Utility-Data-Attributes branch March 19, 2025 17:46
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.

[New Feature] Utility Function for Data Attributes

3 participants