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

multi select component #1554

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

multi select component #1554

wants to merge 3 commits into from

Conversation

adred
Copy link
Contributor

@adred adred commented Dec 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a MultiSelect component allowing users to select multiple options.
    • Added styles for the MultiSelect component and its options.
    • Created Storybook stories for visual testing of the MultiSelect component with different selection states.
  • Accessibility Improvements

    • Implemented keyboard accessibility for selecting options.

Copy link

coderabbitai bot commented Dec 18, 2024

Walkthrough

A new multi-select component has been developed for the frontend application, introducing a flexible and accessible way to select multiple options. The implementation includes a React component in multiselect.tsx, accompanying SCSS styles in multiselect.scss, and Storybook stories in multiselect.stories.tsx. The component allows users to select multiple items with keyboard and mouse interactions, featuring visual selection indicators and a responsive design.

Changes

File Change Summary
frontend/app/element/multiselect.scss Added styles for .multi-select and .option classes with rounded corners, hover effects, and selection states
frontend/app/element/multiselect.stories.tsx Created Storybook stories showcasing MultiSelect component with preselected and no-selection scenarios
frontend/app/element/multiselect.tsx Implemented MultiSelect React component with state management, keyboard accessibility, and option selection logic

Sequence Diagram

sequenceDiagram
    participant User
    participant MultiSelect
    participant OnChangeHandler

    User->>MultiSelect: Click/Select Option
    MultiSelect->>MultiSelect: Update Selected Values
    MultiSelect->>OnChangeHandler: Trigger onChange
    OnChangeHandler-->>MultiSelect: Process Selection
Loading

Poem

🐰 Hop, hop, select with glee!
Options dancing, wild and free
Checkboxes bounce, values take flight
A multi-select rabbit's delight!
Click and choose, no need to fear 🐾


📜 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 d9b5f4f and 1852a38.

📒 Files selected for processing (1)
  • frontend/app/element/multiselect.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/app/element/multiselect.tsx

🪧 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. (Beta)
  • @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

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

🧹 Nitpick comments (2)
frontend/app/element/multiselect.tsx (2)

7-16: Consider enhancing type safety and validation.

While the types are well-defined, consider these improvements:

  1. Add non-empty array validation for options
  2. Make value and label properties more specific if possible
  3. Add runtime validation for empty options array

Consider this enhancement:

 type Option = {
-    label: string;
-    value: string;
+    label: string;  // Consider readonly if immutable
+    value: string;  // Consider union type if values are known
 };

 type MultiSelectProps = {
-    options: Option[];
+    options: readonly Option[] & { length: number };  // Ensures non-empty array
     selectedValues?: string[];
     onChange: (values: string[]) => void;
 };

21-38: Enhance event handlers with error handling and performance optimizations.

The handlers work well but could be more robust:

  1. Add error handling for onChange callback
  2. Consider debouncing for rapid changes
  3. Add error boundary for component safety

Consider these improvements:

+const handleChange = useCallback((newSelected: string[]) => {
+    try {
+        onChange(newSelected);
+    } catch (error) {
+        console.error('Error in onChange callback:', error);
+    }
+}, [onChange]);
+
+const debouncedHandleChange = useMemo(
+    () => debounce(handleChange, 100),
+    [handleChange]
+);
+
 const handleToggle = (value: string) => {
     setSelected((prevSelected) => {
         const newSelected = prevSelected.includes(value)
             ? prevSelected.filter((v) => v !== value)
             : [...prevSelected, value];
-        onChange(newSelected);
+        debouncedHandleChange(newSelected);
         return newSelected;
     });
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69bb1d4 and d9b5f4f.

📒 Files selected for processing (3)
  • frontend/app/element/multiselect.scss (1 hunks)
  • frontend/app/element/multiselect.stories.tsx (1 hunks)
  • frontend/app/element/multiselect.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/app/element/multiselect.scss
  • frontend/app/element/multiselect.stories.tsx
🔇 Additional comments (2)
frontend/app/element/multiselect.tsx (2)

1-6: LGTM! Proper imports and licensing.

The file header includes appropriate licensing and the imports are correctly structured.


63-63: LGTM! Clear and explicit export.

The named export is appropriate for this component.

Comment on lines +39 to +61
return (
<div className="multi-select" role="listbox" aria-multiselectable="true" aria-label="Multi-select list">
{options.map((option) => {
const isSelected = selected.includes(option.value);

return (
<div
key={option.value}
role="option"
aria-selected={isSelected}
className={`option ${isSelected ? "selected" : ""}`}
tabIndex={0}
onClick={() => handleToggle(option.value)}
onKeyDown={(e) => handleKeyDown(e, option.value)}
>
{option.label}
{isSelected && <i className="fa fa-solid fa-check" aria-hidden="true" />}
</div>
);
})}
</div>
);
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility and performance for large lists.

The component is accessible but could be improved:

  1. Add loading state
  2. Consider virtualization for large lists
  3. Enhance ARIA labels

Consider these improvements:

 return (
     <div className="multi-select" role="listbox" aria-multiselectable="true" aria-label="Multi-select list">
+        {options.length === 0 && (
+            <div className="empty-state" role="alert">
+                No options available
+            </div>
+        )}
         {options.map((option) => {
             const isSelected = selected.includes(option.value);
             return (
                 <div
                     key={option.value}
                     role="option"
                     aria-selected={isSelected}
+                    aria-label={`${option.label}${isSelected ? ' selected' : ''}`}
                     className={`option ${isSelected ? "selected" : ""}`}
                     tabIndex={0}
                     onClick={() => handleToggle(option.value)}
                     onKeyDown={(e) => handleKeyDown(e, option.value)}
                 >
                     {option.label}
                     {isSelected && <i className="fa fa-solid fa-check" aria-hidden="true" />}
                 </div>
             );
         })}
     </div>
 );

For large lists, consider using a virtualization library:

import { FixedSizeList } from 'react-window';

Comment on lines 18 to 20
const MultiSelect: React.FC<MultiSelectProps> = ({ options, selectedValues = [], onChange }) => {
const [selected, setSelected] = useState<string[]>(selectedValues);

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add synchronization with prop changes and validation.

The component should sync its internal state when selectedValues prop changes and validate for duplicate values.

Add this code after the useState declaration:

 const [selected, setSelected] = useState<string[]>(selectedValues);
+
+// Sync with prop changes
+useEffect(() => {
+    setSelected(selectedValues);
+}, [selectedValues]);
+
+// Validate props
+useEffect(() => {
+    const uniqueValues = new Set(selectedValues);
+    if (uniqueValues.size !== selectedValues.length) {
+        console.warn('MultiSelect: selectedValues contains duplicate values');
+    }
+}, [selectedValues]);
📝 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 MultiSelect: React.FC<MultiSelectProps> = ({ options, selectedValues = [], onChange }) => {
const [selected, setSelected] = useState<string[]>(selectedValues);
const MultiSelect: React.FC<MultiSelectProps> = ({ options, selectedValues = [], onChange }) => {
const [selected, setSelected] = useState<string[]>(selectedValues);
// Sync with prop changes
useEffect(() => {
setSelected(selectedValues);
}, [selectedValues]);
// Validate props
useEffect(() => {
const uniqueValues = new Set(selectedValues);
if (uniqueValues.size !== selectedValues.length) {
console.warn('MultiSelect: selectedValues contains duplicate values');
}
}, [selectedValues]);

Comment on lines 1 to 63
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0

import React, { useState } from "react";
import "./multiselect.scss";

type Option = {
label: string;
value: string;
};

type MultiSelectProps = {
options: Option[];
selectedValues?: string[];
onChange: (values: string[]) => void;
};

const MultiSelect: React.FC<MultiSelectProps> = ({ options, selectedValues = [], onChange }) => {
const [selected, setSelected] = useState<string[]>(selectedValues);

const handleToggle = (value: string) => {
setSelected((prevSelected) => {
const newSelected = prevSelected.includes(value)
? prevSelected.filter((v) => v !== value) // Remove if already selected
: [...prevSelected, value]; // Add if not selected

onChange(newSelected);
return newSelected;
});
};

const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>, value: string) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleToggle(value);
}
};

return (
<div className="multi-select" role="listbox" aria-multiselectable="true" aria-label="Multi-select list">
{options.map((option) => {
const isSelected = selected.includes(option.value);

return (
<div
key={option.value}
role="option"
aria-selected={isSelected}
className={`option ${isSelected ? "selected" : ""}`}
tabIndex={0}
onClick={() => handleToggle(option.value)}
onKeyDown={(e) => handleKeyDown(e, option.value)}
>
{option.label}
{isSelected && <i className="fa fa-solid fa-check" aria-hidden="true" />}
</div>
);
})}
</div>
);
};

export { MultiSelect };
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add unit tests for the MultiSelect component

The component has good documentation through Storybook stories that demonstrate its usage with proper prop descriptions and examples. However, it lacks unit tests to verify its functionality. Please add tests to cover:

  • Initial rendering with and without selected values
  • Option selection/deselection behavior
  • Keyboard interaction (Enter and Space key handlers)
  • Callback invocation with updated values
🔗 Analysis chain

Verify component documentation and test coverage.

Let's ensure the component is properly documented and tested.


Let me check the content of the stories file to verify the documentation quality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for component documentation and tests

# Look for story file
echo "Checking for Storybook stories..."
fd "multiselect.stories" frontend/app/element

# Look for test file
echo "Checking for test file..."
fd "multiselect.test|multiselect.spec" frontend/app/element

# Look for README or documentation
echo "Checking for documentation..."
fd "README|DOCUMENTATION" frontend/app/element

Length of output: 408


Script:

#!/bin/bash
# Check content of the stories file
cat frontend/app/element/multiselect.stories.tsx

# Let's also check if there are any tests in the codebase for this component
# that might have a different naming pattern
rg -l "describe.*MultiSelect|test.*MultiSelect" frontend/app/element

Length of output: 1600

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.

1 participant