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

Feature toggle primitive #553

Merged
merged 26 commits into from
Nov 22, 2024
Merged

Conversation

jindaljyoti
Copy link
Contributor

@jindaljyoti jindaljyoti commented Nov 11, 2024

image

I have added toggle primitive, context and stories file but their is no usage of toggle primitive in the toggle component, can you please suggest how to change the toggle component based on toggle primitive?

Summary by CodeRabbit

  • New Features

    • Introduced a new Toggle component with an optional defaultPressed property for initial state configuration.
    • Added a context for managing toggle states, enhancing component interaction.
    • Created the TogglePrimitiveRoot component to encapsulate toggle logic and state management.
  • Improvements

    • Enhanced accessibility with updated aria-pressed attributes.
    • Improved selection logic for toggle items, supporting both single and multiple selections.
  • Documentation

    • Added a new story for the TogglePrimitive component in Storybook for easier visualization and testing.

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes introduce enhancements to the Toggle component and its associated items in a React application. A new optional property, defaultPressed, is added to the ToggleProps type, allowing for an initial pressed state. The ToggleItem component is updated to manage toggle selection logic for both single and multiple selections. A new context for managing toggle state is created, along with a TogglePrimitiveRoot component to encapsulate toggle logic. Additionally, a Storybook story for the TogglePrimitive component is added for visualization and testing.

Changes

File Path Change Summary
src/components/ui/Toggle/Toggle.tsx Added defaultPressed to ToggleProps, adjusted internal state management for isPressed.
src/components/ui/ToggleGroup/fragments/ToggleItem.tsx Introduced isActive variable and updated handleToggleSelect for single/multiple toggle logic.
src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx Created context TogglePrimitiveContext with properties for managing toggle state.
src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx Added TogglePrimitiveRoot component to manage toggle state and provide context to children.
src/core/primitives/Toggle/index.tsx Introduced index.tsx to export TogglePrimitive containing TogglePrimitiveRoot.
src/core/primitives/Toggle/stories/TogglePrimitive.stories.tsx Added Storybook story for TogglePrimitive component for interactive visualization.

Possibly related PRs

Suggested reviewers

  • kotAPI

Poem

In the meadow where toggles play,
A new default joins the fray.
With states that dance and buttons bright,
Our UI hops with pure delight! 🐇✨
Let the toggles switch and sway,
A joyful code, hip-hip-hooray!

Warning

Rate limit exceeded

@jindaljyoti has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 48 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1c3cfdc and 3f49aaf.

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.

src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx

Oops! Something went wrong! :(

ESLint: 8.56.0

Error: Failed to load parser '@babel/eslint-parser' declared in '.eslintrc.cjs': Cannot find module '@babel/core/package.json'
Require stack:

  • /node_modules/@babel/eslint-parser/lib/parse.cjs
  • /node_modules/@babel/eslint-parser/lib/index.cjs
  • /node_modules/@eslint/eslintrc/dist/eslintrc.cjs
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object. (/node_modules/@babel/eslint-parser/lib/parse.cjs:14:19)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)
    at Module._load (node:internal/modules/cjs/loader:1127:12)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1c3cfdc and 3f49aaf.

📒 Files selected for processing (1)
  • src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx

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

🧹 Outside diff range and nitpick comments (12)
src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx (1)

1-9: Consider these architectural patterns for toggle component integration

As you proceed with integrating this context into the toggle component, consider the following architectural patterns:

  1. Keep the primitive focused on core toggle logic (state, accessibility) while the component handles presentation
  2. Consider implementing a compound component pattern:
    <Toggle.Root>
      <Toggle.Thumb />
      <Toggle.Label />
    </Toggle.Root>
  3. Ensure the primitive handles ARIA attributes (aria-pressed, role="switch")
  4. Consider adding event callbacks for state changes to support controlled and uncontrolled modes

Would you like me to provide a detailed implementation example for any of these patterns?

src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1)

1-36: Consider extracting toggle logic into a custom hook

To improve reusability and testing, consider extracting the toggle logic into a custom hook (e.g., useTogglePrimitive). This would:

  1. Separate concerns between state management and rendering
  2. Make the logic reusable across different components
  3. Make it easier to test the logic in isolation

Example implementation:

function useTogglePrimitive({
  pressed,
  defaultPressed,
  onChange
}: Pick<TogglePrimitiveRootProps, 'pressed' | 'defaultPressed' | 'onChange'>) {
  const [uncontrolledPressed, setUncontrolledPressed] = useState(defaultPressed ?? false);
  const isPressed = pressed ?? uncontrolledPressed;

  const handlePressed = useCallback((event: React.MouseEvent | React.KeyboardEvent) => {
    if (event.type === 'keydown' && (event as React.KeyboardEvent).key !== 'Enter' && (event as React.KeyboardEvent).key !== ' ') {
      return;
    }
    const updatedPressed = !isPressed;
    setUncontrolledPressed(updatedPressed);
    onChange(updatedPressed);
  }, [isPressed, onChange]);

  return {
    isPressed,
    handlePressed
  };
}
src/components/ui/Toggle/Toggle.tsx (4)

Line range hint 8-17: Simplify the defaultPressed type definition

The type union boolean | false is redundant since boolean already includes false. Consider simplifying it to just boolean.

-    defaultPressed? : boolean | false ;
+    defaultPressed? : boolean;

Line range hint 33-33: Fix incorrect state initialization logic

The current initialization pressed || defaultPressed has a logical flaw. When pressed is false and defaultPressed is true, it will use defaultPressed, which contradicts the expected behavior where pressed should always take precedence over defaultPressed.

-    const [isPressed, setIsPressed] = useState(pressed || defaultPressed);
+    const [isPressed, setIsPressed] = useState(pressed ?? defaultPressed ?? false);

Line range hint 33-39: Implement proper controlled/uncontrolled component pattern

The component currently mixes controlled and uncontrolled patterns, which can lead to state synchronization issues. The internal state might get out of sync with the external pressed prop.

Consider implementing either:

  1. Fully controlled component (recommended):
-    const [isPressed, setIsPressed] = useState(pressed || defaultPressed);
-
     const handlePressed = () => {
-        const updatedPressed = !isPressed;
-        setIsPressed(updatedPressed);
-        onChange(updatedPressed);
+        onChange(!pressed);
     };
  1. Or proper uncontrolled component with key prop:
+    const [isPressed, setIsPressed] = useState(defaultPressed ?? false);
+
+    // Sync with external updates
+    useEffect(() => {
+        if (pressed !== undefined) {
+            setIsPressed(pressed);
+        }
+    }, [pressed]);
+
     const handlePressed = () => {
         const updatedPressed = !isPressed;
         setIsPressed(updatedPressed);
         onChange(updatedPressed);
     };

Line range hint 1-55: Consider refactoring to use the new TogglePrimitive

Based on the PR objectives, this component should be refactored to utilize the newly created toggle primitive instead of maintaining its own state management logic. This would ensure consistency and reduce code duplication.

Consider:

  1. Importing and using the TogglePrimitive component
  2. Delegating state management to the primitive
  3. Focusing this component on styling and specific UI requirements

Example approach:

import { TogglePrimitive } from '~/core/primitives/Toggle';

const Toggle: React.FC<ToggleProps> = (props) => {
  return (
    <TogglePrimitive.Root
      defaultPressed={props.defaultPressed}
      pressed={props.pressed}
      onPressedChange={props.onChange}
    >
      <ButtonPrimitive className={props.className} {...props}>
        {props.children}
      </ButtonPrimitive>
    </TogglePrimitive.Root>
  );
};
src/components/ui/ToggleGroup/fragments/ToggleItem.tsx (6)

Line range hint 6-6: Define proper TypeScript interface for component props

Using :any type annotation reduces type safety and makes the component harder to maintain. Consider defining a proper interface for the props.

+interface ToggleItemProps {
+  children: React.ReactNode;
+  value?: string | number | null;
+  [key: string]: any; // for remaining props if needed
+}

-const ToggleItem = ({ children, value = null, ...props }:any) => {
+const ToggleItem = ({ children, value = null, ...props }: ToggleItemProps) => {

11-11: Remove unnecessary empty line

-

12-12: Add error handling for missing context

The optional chaining is good, but consider adding a check for required context to fail fast and provide better error messages.

+if (!toggleContext) {
+  throw new Error('ToggleItem must be used within a ToggleContext provider');
+}
+
const isActive = toggleContext?.activeToggles?.includes(value);

20-20: Remove unnecessary empty line

-

Line range hint 14-35: Simplify toggle selection logic

The current implementation can be made more concise and consistent by removing early returns and unifying the logic structure.

 const handleToggleSelect = () => {
-    let activeToggleArray = toggleContext?.activeToggles || [];
+    if (!toggleContext) return;
+    
+    const { activeToggles = [], setActiveToggles } = toggleContext;
 
-    // For Single Case
     if (type === 'single') {
-        if (isActive) {
-            
-            toggleContext?.setActiveToggles([]);
-            return;
-        } else {
-            toggleContext?.setActiveToggles([value]);
-            return;
-        }
+        setActiveToggles(isActive ? [] : [value]);
+        return;
     }
 
-    // For Multiple Case
-    if (type === 'multiple') {
-        if (isActive) {
-            activeToggleArray = activeToggleArray.filter((item: any) => item !== value);
-        } else {
-            activeToggleArray = [...activeToggleArray, value]; // Using spread operator to create a new array
-        }
-    }
-
-    toggleContext?.setActiveToggles(activeToggleArray);
+    const newToggles = isActive
+        ? activeToggles.filter((item: any) => item !== value)
+        : [...activeToggles, value];
+    
+    setActiveToggles(newToggles);
 };

Line range hint 37-52: Optimize component rendering and styling

Consider these improvements for better performance and maintainability:

  1. Memoize the event handler
  2. Use CSS classes instead of inline styles
  3. Simplify aria-pressed assignment
+import { useCallback } from 'react';
+import clsx from 'clsx';  // Add this to your dependencies if not present

 const ToggleItem = ({ children, value = null, ...props }:any) => {
     // ... existing code ...
+    const handleClick = useCallback(() => {
+        handleToggleSelect();
+    }, [handleToggleSelect]);
+
-    if (isActive) {
-        props['aria-pressed'] = 'true';
-    } else {
-        props['aria-pressed'] = 'false';
-    }
+    props['aria-pressed'] = String(!!isActive);

     return <ButtonPrimitive
-        className={`${isActive ? 'bg-blue-600' : ''}`}
-        onClick={() => {
-            handleToggleSelect();
-        }}
+        className={clsx('toggle-item', isActive && 'toggle-item--active')}
+        onClick={handleClick}
         {...props}
     >{children}</ButtonPrimitive>;
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between afc4f02 and b7f6db4.

📒 Files selected for processing (6)
  • src/components/ui/Toggle/Toggle.tsx (3 hunks)
  • src/components/ui/ToggleGroup/fragments/ToggleItem.tsx (2 hunks)
  • src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx (1 hunks)
  • src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1 hunks)
  • src/core/primitives/Toggle/index.tsx (1 hunks)
  • src/core/primitives/Toggle/stories/TogglePrimitive.stories.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/core/primitives/Toggle/index.tsx
  • src/core/primitives/Toggle/stories/TogglePrimitive.stories.tsx
🔇 Additional comments (3)
src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx (1)

1-1: LGTM!

The import statement is clean and follows React conventions.

src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1)

1-4: Verify path alias configuration

The import statement uses a path alias (~). Ensure that this alias is properly configured in your build setup (tsconfig.json/webpack config).

✅ Verification successful

Path alias ~ is correctly configured

The path alias ~ is properly configured in the tsconfig.json file, mapping to the src/* directory. The import statement ~/core/customClassSwitcher will correctly resolve to src/core/customClassSwitcher.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for path alias configuration in tsconfig and webpack files

# Check tsconfig.json for path alias
fd tsconfig.json --exec cat {} | jq -r '.compilerOptions.paths | select(. != null)'

# Check webpack config for path alias
fd 'webpack.config.*' --exec cat {} | grep -A 5 'alias'

Length of output: 205

src/components/ui/ToggleGroup/fragments/ToggleItem.tsx (1)

Line range hint 1-52: Verify integration with TogglePrimitive

The PR objectives mention implementing a toggle primitive, but this component still uses the old toggle context. Consider migrating to use the new toggle primitive for consistency.

Comment on lines 3 to 8
interface TogglePrimitiveContextType {
rootClass: string;
isPressed: boolean | undefined;
handlePressed: () => void;

}
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 documentation and improve type safety

The interface could benefit from the following improvements:

  1. Add JSDoc documentation
  2. Consider renaming rootClass to be more specific (e.g., toggleRootClass)
  3. Make properties readonly to prevent accidental mutations
  4. Consider adding parameters to handlePressed for more flexibility

Here's the suggested implementation:

+/**
+ * Context type for the Toggle Primitive
+ * @property toggleRootClass - CSS class for the root element
+ * @property isPressed - Current pressed state
+ * @property handlePressed - Callback to handle toggle state changes
+ */
 interface TogglePrimitiveContextType {
-    rootClass: string;
-    isPressed: boolean | undefined;
-    handlePressed: () => void;
+    readonly toggleRootClass: string;
+    readonly isPressed: boolean | undefined;
+    readonly handlePressed: (value?: boolean) => void;
 }
📝 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
interface TogglePrimitiveContextType {
rootClass: string;
isPressed: boolean | undefined;
handlePressed: () => void;
}
/**
* Context type for the Toggle Primitive
* @property toggleRootClass - CSS class for the root element
* @property isPressed - Current pressed state
* @property handlePressed - Callback to handle toggle state changes
*/
interface TogglePrimitiveContextType {
readonly toggleRootClass: string;
readonly isPressed: boolean | undefined;
readonly handlePressed: (value?: boolean) => void;
}

Comment on lines +43 to 47
className={`${rootClass}`} onClick ={handlePressed}
data-state={isPressed ? 'on' : 'off'}
type="button"
type='button'
data-disabled={props.disabled ? '' : undefined}
aria-pressed={pressed} {...props}>
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

Fix accessibility and simplify attribute handling

  1. The aria-pressed attribute should reflect the actual state of the toggle, not just the pressed prop.
  2. The data-disabled implementation can be simplified.
     <ButtonPrimitive
         className={`${rootClass}`} onClick={handlePressed}
         data-state={isPressed ? 'on' : 'off'}
         type='button'
-        data-disabled={props.disabled ? '' : undefined}
-        aria-pressed={pressed}
+        data-disabled={props.disabled || undefined}
+        aria-pressed={isPressed}
         {...props}>
📝 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
className={`${rootClass}`} onClick ={handlePressed}
data-state={isPressed ? 'on' : 'off'}
type="button"
type='button'
data-disabled={props.disabled ? '' : undefined}
aria-pressed={pressed} {...props}>
className={`${rootClass}`} onClick ={handlePressed}
data-state={isPressed ? 'on' : 'off'}
type='button'
data-disabled={props.disabled || undefined}
aria-pressed={isPressed} {...props}>

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

🧹 Outside diff range and nitpick comments (1)
src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1)

1-30: Consider component composition pattern

Since this is a primitive component that will be used by the UI toggle component:

  1. Consider splitting into smaller subcomponents (Root, Thumb, Track) for better composition
  2. Implement a compound component pattern to allow flexible styling and behavior customization

Example structure:

export const TogglePrimitive = {
  Root: TogglePrimitiveRoot,
  Thumb: TogglePrimitiveThumb,
  Track: TogglePrimitiveTrack,
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b7f6db4 and 1c3cfdc.

📒 Files selected for processing (2)
  • src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx (1 hunks)
  • src/core/primitives/Toggle/fragments/TogglePrimitiveRoot.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/primitives/Toggle/contexts/TogglePrimitiveContext.tsx

Comment on lines 20 to 24
const values = {
handlePressed,
isPressed,
setIsPressed
};
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

Remove unnecessary context setup

As per reviewer feedback, context is not needed for this primitive component:

-  const values = {
-    handlePressed,
-    isPressed,
-    setIsPressed
-  };
📝 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 values = {
handlePressed,
isPressed,
setIsPressed
};

setIsPressed
};

return <span className={className}{...props}>{children}</span>
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 proper accessibility attributes

The toggle element needs proper ARIA attributes and event handlers:

-  return <span className={className}{...props}>{children}</span>
+  return (
+    <span
+      role="button"
+      tabIndex={0}
+      aria-pressed={isPressed}
+      className={className}
+      onClick={handlePressed}
+      onKeyDown={handlePressed}
+    >
+      {children}
+    </span>
+  );

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +3 to +10
export interface TogglePrimitiveRootProps {
defaultPressed? : boolean | false;
pressed: boolean;
children?: React.ReactNode;
className?: string;
onChange : (isPressed:boolean) => void;

}
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

Fix prop types and add documentation

The interface needs improvements for better type safety and documentation:

+/**
+ * Props for the Toggle Primitive component that handles basic toggle functionality
+ */
 export interface TogglePrimitiveRootProps {
-    defaultPressed? : boolean | false;
+    /** Initial pressed state for uncontrolled usage */
+    defaultPressed?: boolean;
+    /** Current pressed state for controlled usage. Takes precedence over defaultPressed */
     pressed: boolean;
+    /** Content to be rendered within the toggle */
     children?: React.ReactNode;
+    /** Additional CSS classes */
     className?: string;
+    /** Callback fired when toggle state changes */
     onChange : (isPressed:boolean) => void;
 }
📝 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
export interface TogglePrimitiveRootProps {
defaultPressed? : boolean | false;
pressed: boolean;
children?: React.ReactNode;
className?: string;
onChange : (isPressed:boolean) => void;
}
/**
* Props for the Toggle Primitive component that handles basic toggle functionality
*/
export interface TogglePrimitiveRootProps {
/** Initial pressed state for uncontrolled usage */
defaultPressed?: boolean;
/** Current pressed state for controlled usage. Takes precedence over defaultPressed */
pressed: boolean;
/** Content to be rendered within the toggle */
children?: React.ReactNode;
/** Additional CSS classes */
className?: string;
/** Callback fired when toggle state changes */
onChange : (isPressed:boolean) => void;
}

Comment on lines +11 to +12
const TogglePrimitiveRoot = ({children,className='',defaultPressed,pressed,onChange,...props}:TogglePrimitiveRootProps) => {
const [isPressed, setIsPressed] = useState(pressed || defaultPressed);
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

Fix state management pattern

The current state management mixes controlled and uncontrolled patterns incorrectly:

-const TogglePrimitiveRoot = ({children,className='',defaultPressed,pressed,onChange,...props}:TogglePrimitiveRootProps) => {
-      const [isPressed, setIsPressed] = useState(pressed || defaultPressed);
+const TogglePrimitiveRoot = ({
+  children,
+  className = '',
+  defaultPressed = false,
+  pressed,
+  onChange,
+  ...props
+}: TogglePrimitiveRootProps) => {
+  const [uncontrolledPressed, setUncontrolledPressed] = useState(defaultPressed);
+  const isPressed = pressed ?? uncontrolledPressed;
📝 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 TogglePrimitiveRoot = ({children,className='',defaultPressed,pressed,onChange,...props}:TogglePrimitiveRootProps) => {
const [isPressed, setIsPressed] = useState(pressed || defaultPressed);
const TogglePrimitiveRoot = ({
children,
className = '',
defaultPressed = false,
pressed,
onChange,
...props
}: TogglePrimitiveRootProps) => {
const [uncontrolledPressed, setUncontrolledPressed] = useState(defaultPressed);
const isPressed = pressed ?? uncontrolledPressed;

Comment on lines +14 to +18
const handlePressed = () => {
const updatedPressed = !isPressed;
setIsPressed(updatedPressed);
onChange(updatedPressed)
}
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

Improve event handling

The toggle needs proper event handling for both mouse and keyboard interactions:

-   const handlePressed = () => {
+   const handlePressed = (event: React.MouseEvent | React.KeyboardEvent) => {
+     if (
+       event.type === 'keydown' &&
+       (event as React.KeyboardEvent).key !== 'Enter' &&
+       (event as React.KeyboardEvent).key !== ' '
+     ) {
+       return;
+     }
+     event.preventDefault();
      const updatedPressed = !isPressed;
-     setIsPressed(updatedPressed);
+     if (pressed === undefined) {
+       setUncontrolledPressed(updatedPressed);
+     }
      onChange(updatedPressed);
    }
📝 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 handlePressed = () => {
const updatedPressed = !isPressed;
setIsPressed(updatedPressed);
onChange(updatedPressed)
}
const handlePressed = (event: React.MouseEvent | React.KeyboardEvent) => {
if (
event.type === 'keydown' &&
(event as React.KeyboardEvent).key !== 'Enter' &&
(event as React.KeyboardEvent).key !== ' '
) {
return;
}
event.preventDefault();
const updatedPressed = !isPressed;
if (pressed === undefined) {
setUncontrolledPressed(updatedPressed);
}
onChange(updatedPressed);
}

@kotAPI kotAPI merged commit df04754 into rad-ui:main Nov 22, 2024
3 checks passed
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