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

Featue controlled/uncontrolled modes for accordian #1031

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

romeu-maleiane
Copy link

@romeu-maleiane romeu-maleiane commented Apr 6, 2025

I added support for props in AccordionRoot for the user to control the accordion component

Summary by CodeRabbit

  • New Features

    • Enhanced the Accordion component to support both controlled and uncontrolled state management with new options for setting values.
    • Streamlined item association by using explicit identifiers for each accordion item, improving consistency in behavior.
  • Documentation

    • Updated example usage to showcase the refined setup and integration of these new capabilities.

Copy link
Contributor

coderabbitai bot commented Apr 6, 2025

Walkthrough

The changes refine the accordion components by establishing a more explicit association between data and rendered items. In the example file, each accordion item now receives a specific id ("react", "angular", "vue"), replacing the previous index-based approach and eliminating the use of the key and index props. Meanwhile, the AccordionRoot component is updated to include new state management props (value, defaultValue, and onValueChange), which are passed to the context provider. No changes were made to the declarations of exported or public entities.

Changes

File(s) Summary
docs/.../example_1.tsx Introduces fixed id properties for accordion items ("react", "angular", "vue") and updates rendering to use these IDs instead of index-based values.
src/.../AccordionRoot.tsx Adds new props (value, defaultValue, onValueChange) to AccordionRoot and passes them to AccordionContext.Provider for state management.

Sequence Diagram(s)

sequenceDiagram
    participant AE as AccordionExample
    participant AI as Accordion.Item

    AE->>AE: Iterate over items with fixed IDs
    AE->>AI: Render each item using its `id` ("react", "angular", "vue")
Loading
sequenceDiagram
    participant AR as AccordionRoot
    participant AC as AccordionContext.Provider
    participant Child as Child Components

    AR->>AC: Pass props (value, defaultValue, onValueChange)
    AC->>Child: Provide state and update callbacks
Loading

Possibly related PRs

  • Composable API Docs #958: Modifies the AccordionExample component's structure and how items are rendered, paralleling the changes to item identification.
  • Better Accordion #363: Enhances the AccordionRoot by introducing state management props, aligning with this PR's updates.

Suggested labels

automerge

Suggested reviewers

  • kotAPI

Poem

I'm a rabbit hopping through the code,
Skipping past old keys on a winding road.
Fixed IDs now lead the dance so neat,
And fresh state flows with every beat.
With whiskers twitching in joyful cheer,
I nibble on changes, crisp and clear!
🐇🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error code E503
npm error 503 Service Unavailable - GET http://10.0.0.28:4873/yocto-queue/-/yocto-queue-0.1.0.tgz
npm error A complete log of this run can be found in: /.npm/_logs/2025-04-06T15_44_22_691Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 2

🔭 Outside diff range comments (1)
src/components/ui/Accordion/fragments/AccordionRoot.tsx (1)

30-30: 🛠️ Refactor suggestion

Type inconsistency in state management

The activeItems state uses (number | string)[] but the new props use string | string[]. This inconsistency could lead to unexpected behavior.

Consider updating the state type to match the props:

- const [activeItems, setActiveItems] = useState<(number | string)[]>([]);
+ const [activeItems, setActiveItems] = useState<string[]>([]);

This change would require updating any code that relies on numeric values in activeItems.

🧹 Nitpick comments (2)
docs/app/docs/components/accordion/docs/example_1.tsx (1)

27-36: Consider demonstrating controlled mode

The example doesn't demonstrate the new controlled mode capabilities added to the AccordionRoot component. Consider updating this example to show how to use the new value, defaultValue, and onValueChange props.

- <Accordion.Root>
+ <Accordion.Root 
+   defaultValue="react" 
+   // Or for controlled mode:
+   // value={selectedItem}
+   // onValueChange={setSelectedItem}
+ >

This would help document the new functionality and provide a usage example for other developers.

🧰 Tools
🪛 Biome (1.9.4)

[error] 29-29: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

src/components/ui/Accordion/fragments/AccordionRoot.tsx (1)

12-24: Add documentation for the new props

Consider adding JSDoc comments to explain how the new controlled mode props work.

export type AccordionRootProps = {
    children: React.ReactNode;
    customRootClass?: string;
    transitionDuration?: number;
    transitionTimingFunction?: string;
    orientation?: 'horizontal' | 'vertical';
    asChild?: boolean;
    loop?: boolean;
    openMultiple?: boolean;
+   /** 
+    * The controlled value of the accordion. Can be a single string or an array of strings.
+    * Use with onValueChange for controlled mode.
+    */
    value?: string | string[];
+   /**
+    * The default value for the accordion in uncontrolled mode.
+    * Can be a single string or an array of strings.
+    */
    defaultValue?: string | string[];
+   /**
+    * Callback fired when the value changes.
+    * Returns a single string if openMultiple is false, or an array of strings if openMultiple is true.
+    */
    onValueChange?: (value: string | string[]) => void
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 758d8e8 and c9e3526.

📒 Files selected for processing (2)
  • docs/app/docs/components/accordion/docs/example_1.tsx (2 hunks)
  • src/components/ui/Accordion/fragments/AccordionRoot.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
docs/app/docs/components/accordion/docs/example_1.tsx

[error] 29-29: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

🔇 Additional comments (4)
docs/app/docs/components/accordion/docs/example_1.tsx (2)

4-20: Good addition of explicit IDs to items

Adding unique IDs to each item is a good practice as it moves away from index-based identification. This approach provides more stable references for controlled components.


31-33: Good removal of index-based props

Removing index-based props from the trigger and content components is appropriate when using unique IDs from the data model instead.

src/components/ui/Accordion/fragments/AccordionRoot.tsx (2)

21-23: Good addition of controlled mode props

The addition of value, defaultValue, and onValueChange props enables both controlled and uncontrolled modes for the Accordion component, providing greater flexibility to users.


26-26: Function signature updated correctly

The function signature has been properly updated to include the new props.

Comment on lines +28 to +29
{items.map((item) => (
<Accordion.Item value={`${item.id}`}>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add a key prop to the iterable element

When rendering lists in React, each element should have a unique key prop to help React identify which items have changed.

- <Accordion.Item value={`${item.id}`}>
+ <Accordion.Item key={item.id} value={item.id}>

Also note that the template literal is unnecessary since item.id is already a string.

📝 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
{items.map((item) => (
<Accordion.Item value={`${item.id}`}>
{items.map((item) => (
<Accordion.Item key={item.id} value={item.id}>
🧰 Tools
🪛 Biome (1.9.4)

[error] 29-29: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

Comment on lines +41 to +44
openMultiple,
value,
defaultValue,
onValueChange
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 6, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Props passed to context, but implementation missing

While the props are correctly passed to the context, there's no implementation to handle controlled behavior. The component needs logic to:

  1. Initialize state from defaultValue
  2. Update state when value changes
  3. Call onValueChange when the state changes

Consider implementing the controlled behavior with a useEffect hook:

const AccordionRoot = ({ children, orientation = 'vertical', asChild, transitionDuration = 0, transitionTimingFunction = 'linear', customRootClass, loop = true, openMultiple = false, value, defaultValue, onValueChange }: AccordionRootProps) => {
    const accordionRef = useRef<HTMLDivElement | null>(null);
    const rootClass = customClassSwitcher(customRootClass, COMPONENT_NAME);

-   const [activeItems, setActiveItems] = useState<(number | string)[]>([]);
+   const [activeItems, setActiveItems] = useState<string[]>(() => {
+       // Initialize from defaultValue if provided
+       if (defaultValue !== undefined) {
+           return Array.isArray(defaultValue) ? defaultValue : [defaultValue];
+       }
+       return [];
+   });
+   
+   // Handle controlled mode
+   useEffect(() => {
+       if (value !== undefined) {
+           const newActiveItems = Array.isArray(value) ? value : [value];
+           setActiveItems(newActiveItems);
+       }
+   }, [value]);
+   
+   // Create wrapper for setActiveItems that calls onValueChange
+   const handleSetActiveItems = (items: string[]) => {
+       setActiveItems(items);
+       if (onValueChange) {
+           onValueChange(openMultiple ? items : items[0] || '');
+       }
+   };

Also, you'll need to update how setActiveItems is used throughout the component to use handleSetActiveItems instead.

📝 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
openMultiple,
value,
defaultValue,
onValueChange
const AccordionRoot = ({ children, orientation = 'vertical', asChild, transitionDuration = 0, transitionTimingFunction = 'linear', customRootClass, loop = true, openMultiple = false, value, defaultValue, onValueChange }: AccordionRootProps) => {
const accordionRef = useRef<HTMLDivElement | null>(null);
const rootClass = customClassSwitcher(customRootClass, COMPONENT_NAME);
const [activeItems, setActiveItems] = useState<string[]>(() => {
// Initialize from defaultValue if provided
if (defaultValue !== undefined) {
return Array.isArray(defaultValue) ? defaultValue : [defaultValue];
}
return [];
});
// Handle controlled mode
useEffect(() => {
if (value !== undefined) {
const newActiveItems = Array.isArray(value) ? value : [value];
setActiveItems(newActiveItems);
}
}, [value]);
// Create wrapper for setActiveItems that calls onValueChange
const handleSetActiveItems = (items: string[]) => {
setActiveItems(items);
if (onValueChange) {
onValueChange(openMultiple ? items : items[0] || '');
}
};
// ... rest of the component logic.
// Update usage of setActiveItems elsewhere in the component to handleSetActiveItems
};

Copy link
Collaborator

Choose a reason for hiding this comment

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

agreed, implementation missing

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find all Accordion-related files to understand the component structure
echo "Accordion-related files:"
fd "Accordion" src/components/ui

# Check the AccordionContext file to see how state is currently managed
echo "\nAccordionContext content:"
cat src/components/ui/Accordion/contexts/AccordionContext.tsx

# Look at AccordionItem implementation to see how it interacts with context
echo "\nAccordionItem content:"
fd "AccordionItem.tsx" src/components/ui --exec cat {}

Length of output: 3911


@kotAPI I'd be happy to help implement the missing functionality. Based on my analysis, we need to make the following changes:

  1. Update the AccordionContext type definition to include the new props
  2. Implement the controlled/uncontrolled behavior in AccordionRoot

Here's a complete implementation:

// First, update the AccordionContext type in src/components/ui/Accordion/contexts/AccordionContext.tsx
interface AccordionContextType {
    rootClass?: string | null;
    activeItems: (number | string)[];
    setActiveItems: (items: (number | string)[]) => void;
    accordionRef?: React.RefObject<HTMLDivElement | null>;
    transitionDuration?: number;
    transitionTimingFunction?: string;
    openMultiple?: boolean;
    // Add the new props
    value?: string | string[];
    defaultValue?: string | string[];
    onValueChange?: (value: string | string[]) => void;
}

// Then, update the AccordionRoot component implementation
import React, { useState, useRef, useEffect } from 'react';
// ... other imports

const AccordionRoot = ({ 
    children, 
    orientation = 'vertical', 
    asChild, 
    transitionDuration = 0, 
    transitionTimingFunction = 'linear', 
    customRootClass, 
    loop = true, 
    openMultiple = false, 
    value, 
    defaultValue, 
    onValueChange 
}: AccordionRootProps) => {
    const accordionRef = useRef<HTMLDivElement | null>(null);
    const rootClass = customClassSwitcher(customRootClass, COMPONENT_NAME);
    const isControlled = value !== undefined;

    // Initialize state from defaultValue if provided
    const [activeItems, setActiveItemsState] = useState<(number | string)[]>(() => {
        if (defaultValue !== undefined) {
            return Array.isArray(defaultValue) ? defaultValue : [defaultValue];
        }
        return [];
    });

    // Handle controlled mode
    useEffect(() => {
        if (isControlled) {
            const newActiveItems = Array.isArray(value) ? value : value ? [value] : [];
            setActiveItemsState(newActiveItems);
        }
    }, [value, isControlled]);

    // Create wrapper for setActiveItems that calls onValueChange
    const setActiveItems = (items: (number | string)[]) => {
        if (!isControlled) {
            setActiveItemsState(items);
        }
        
        if (onValueChange) {
            onValueChange(openMultiple ? items : items[0] || '');
        }
    };

    return (
        <AccordionContext.Provider
            value={{
                rootClass,
                activeItems,
                setActiveItems,
                accordionRef,
                transitionDuration,
                transitionTimingFunction,
                openMultiple,
                value, 
                defaultValue, 
                onValueChange
            }}>
            <RovingFocusGroup.Root orientation={orientation} loop={loop}>
                <RovingFocusGroup.Group >
                    <Primitive.div className={clsx(`${rootClass}-root`)} ref={accordionRef} asChild={asChild}>
                        {children}
                    </Primitive.div>
                </RovingFocusGroup.Group>
            </RovingFocusGroup.Root>
        </AccordionContext.Provider>
    );
};

This implementation:

  1. Handles initialization from defaultValue
  2. Updates state when value changes (controlled mode)
  3. Properly calls onValueChange when state changes
  4. Prevents state updates when in controlled mode (letting the parent component control the state)

Would you like me to also show how to update other components that might be affected by this change?


🧬 Code Definitions Used

Relevant Code Snippets

Filename: src/components/ui/Accordion/contexts/AccordionContext.tsx

export const AccordionContext = createContext<AccordionContextType>({
    rootClass: '',
    activeItems: [],
    setActiveItems: () => {},
    accordionRef: undefined,
    transitionDuration: 0,
    transitionTimingFunction: 'ease-out',
    openMultiple: false
});
  • Description: This snippet defines the AccordionContext using React's createContext. It initializes the context with default values for properties such as rootClass, activeItems, setActiveItems, accordionRef, transitionDuration, transitionTimingFunction, and openMultiple. This context is used in the AccordionRoot component to manage state and provide necessary values to its children.

Filename: src/components/ui/Progress/Progress.tsx

export const COMPONENT_NAME = 'Progress';
  • Description: This snippet defines a constant COMPONENT_NAME for the Progress component. While it is not directly related to the AccordionRoot, it follows a similar pattern of defining a component name, which may be relevant for consistency in naming conventions across components.

✏️ Learnings added
Learnt from: kotAPI
PR: rad-ui/ui#1031
File: src/components/ui/Accordion/fragments/AccordionRoot.tsx:41-44
Timestamp: 2025-04-07T04:38:34.706Z
Learning: The Accordion component in rad-ui/ui supports both controlled and uncontrolled modes through props like `value`, `defaultValue`, and `onValueChange`. When implementing controlled components, remember to: 1) Initialize state from defaultValue, 2) Update internal state when value changes (controlled mode), 3) Call onValueChange callback, and 4) Prevent internal state updates when in controlled mode.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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