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

Feat: Created shadcn MultiSelectOption comp #10042

Merged
merged 19 commits into from
Jan 22, 2025

Conversation

AdityaJ2305
Copy link
Contributor

@AdityaJ2305 AdityaJ2305 commented Jan 18, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced a new MultiSelect component for enhanced multi-option selection.
    • Improved facility feature selection with a more flexible and user-friendly interface.
    • Added a new locale entry for selecting facility features.
  • Bug Fixes

    • Updated feature selection logic to handle string-based value conversions.
  • Style

    • Modified submit button variant to "primary."
    • Enhanced selection UI with badges and icons.
  • Chores

    • Removed the deprecated MultiSelectFormField and MultiSelectMenuV2 components.

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

The pull request introduces a new MultiSelect component in the UI library and updates the FacilityForm to utilize this component. The changes focus on replacing an existing multi-select implementation with a more flexible and consistent ShadCN-compliant component. Modifications include updating the feature selection mechanism in the facility form, changing how feature values are handled, and introducing a new multi-select UI component with enhanced selection capabilities.

Changes

File Change Summary
src/components/Facility/FacilityForm.tsx - Replaced MultiSelectFormField with new MultiSelect component
- Updated handleFeatureChange to accept string array
- Modified feature selection rendering
- Changed submit button variant to "primary"
src/components/ui/multi-select.tsx - Added new MultiSelect component
- Implemented multi-selection with popover
- Supports default values, icons, and dynamic options
src/components/Form/FormFields/SelectFormField.tsx - Removed MultiSelectFormField component and its props type
src/components/Form/MultiSelectMenuV2.tsx - Removed MultiSelectMenuV2 component and its props type
public/locale/en.json - Added new key "select_facility_feature": "Select Facility Features"

Assessment against linked issues

Objective Addressed Explanation
Create ShadCN-compliant MultiOptionSelect [#10041]
Replace old MultiOptionSelect instances [#10041] Only FacilityForm updated; other instances not shown.

Possibly related PRs

Suggested labels

good to merge

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 A rabbit's tale of selection's grace,
MultiSelect dances with style and pace.
Features hop, icons bright and clear,
In the form of choices, we hold dear.
With every click, a new path we trace,
Hopping towards a unified space! 🌼


📜 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 60b9a30 and 1e473cb.

📒 Files selected for processing (1)
  • public/locale/en.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json

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

netlify bot commented Jan 18, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 1e473cb
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678f9ae6ee9b720009f4aed5
😎 Deploy Preview https://deploy-preview-10042--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 18, 2025
@AdityaJ2305 AdityaJ2305 marked this pull request as ready for review January 18, 2025 12:08
@AdityaJ2305 AdityaJ2305 requested a review from a team as a code owner January 18, 2025 12:08
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 (3)
src/components/ui/multi-select.tsx (2)

81-89: Optimize the toggleAll function to avoid unnecessary state updates.

When selecting all items, we can avoid the intermediate array creation and reduce state updates.

 const toggleAll = () => {
   if (selectedValues.length === options.length) {
     handleClear();
   } else {
-    const allValues = options.map((option) => option.value);
-    setSelectedValues(allValues);
-    onValueChange(allValues);
+    const allValues = options.map(({ value }) => value);
+    setSelectedValues(allValues);
+    onValueChange(allValues);
   }
 };

98-161: Enhance accessibility and performance of the trigger button.

Consider these improvements:

  1. Add aria-label for screen readers
  2. Memoize click handlers to prevent unnecessary re-renders
 <PopoverTrigger asChild>
   <Button
     ref={ref}
     {...props}
+    aria-label={placeholder}
     onClick={handleTogglePopover}
     className={cn(
src/components/Facility/FacilityForm.tsx (1)

150-153: Consider type safety improvement in handleFeatureChange.

The function could benefit from stronger type safety when converting string values to numbers.

-  const handleFeatureChange = (value: string[]) => {
-    const features = value.map((val) => Number(val));
+  const handleFeatureChange = (value: string[]) => {
+    const features = value.map((val) => {
+      const num = Number(val);
+      if (isNaN(num)) {
+        console.warn(`Invalid feature value: ${val}`);
+        return 0;
+      }
+      return num;
+    });
     form.setValue("features", features);
   };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b24e645 and 823cccf.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityForm.tsx (4 hunks)
  • src/components/ui/multi-select.tsx (1 hunks)
🔇 Additional comments (4)
src/components/ui/multi-select.tsx (2)

26-39: Well-structured interface definition!

The MultiSelectProps interface is well-designed with:

  • Clear type definitions
  • Optional props for flexibility
  • Proper extension of HTML button attributes

41-62: Clean component initialization and state management!

Good practices observed:

  • Proper use of forwardRef
  • Clean state management
  • Appropriate prop defaults
src/components/Facility/FacilityForm.tsx (2)

295-315: Clean integration of the MultiSelect component!

The implementation correctly:

  • Maps facility features to the required format
  • Handles value conversion between string and number types
  • Provides appropriate placeholder text

521-521: LGTM: Button variant update.

The change to "primary" variant aligns with the design system.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/components/Form/MultiSelectMenuV2.tsx (1)

Line range hint 16-26: Fix invalid HTML nesting by replacing <p> with <span> elements.

Using <p> elements inside a <span> is invalid HTML, as block-level elements cannot be nested within inline elements. Replace the <p> elements with <span> to ensure correct HTML structure and avoid potential rendering issues.

Apply this diff to fix the issue:

 export const MultiSelectOptionChip = ({
   label,
   onRemove,
 }: MultiSelectOptionChipProps) => {
   return (
-    <span className="flex items-center gap-2 rounded-full border-secondary-300 bg-secondary-200 px-3 text-xs text-secondary-700">
-      <p className="py-1">{label}</p>
-      {onRemove && (
-        <p
+    <span className="flex items-center gap-2 rounded-full border-secondary-300 bg-secondary-200 px-3 text-xs text-secondary-700">
+      <span className="py-1">{label}</span>
+      {onRemove && (
+        <span
           className="cursor-pointer rounded-full hover:bg-white"
           onClick={(e) => {
             e.stopPropagation();
             onRemove();
           }}
         >
           <CareIcon icon="l-times" className="text-base" />
-        </p>
+        </span>
       )}
     </span>
   );
 };
🧹 Nitpick comments (1)
src/components/Form/MultiSelectMenuV2.tsx (1)

Line range hint 1-35: Consider renaming the file to reflect its current content.

Since the MultiSelectMenuV2 component has been removed and only utility components (MultiSelectOptionChip and dropdownOptionClassNames) remain, it would be clearer to rename the file to something like MultiSelectUtils.tsx or move these utilities to a shared components directory. This improves code organization and maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 823cccf and da83268.

📒 Files selected for processing (2)
  • src/components/Form/FormFields/SelectFormField.tsx (0 hunks)
  • src/components/Form/MultiSelectMenuV2.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Form/FormFields/SelectFormField.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)

@rithviknishad rithviknishad added needs testing needs review and removed Deploy-Failed Deplyment is not showing preview labels Jan 18, 2025
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: 1

🧹 Nitpick comments (2)
src/components/ui/multi-select.tsx (2)

51-51: Localize the default placeholder text using t function

The placeholder prop defaults to the hardcoded English string "Select options". To support internationalization, use the t function from react-i18next to localize this default text.

Apply this diff to fix the issue:

51c51
-          placeholder = "Select options",
+          placeholder = t("select_options") || "Select options",

Ensure that the translation key select_options is added to your i18n files.


172-172: Localize the "No results found." message

The string "No results found." is hardcoded and not localized. To support internationalization, wrap this message with the t function.

Apply this diff to fix the issue:

172c172
-                    <CommandEmpty>No results found.</CommandEmpty>
+                    <CommandEmpty>{t("no_results_found")}</CommandEmpty>

Add the key no_results_found to your i18n translation files.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between df077b5 and 1f954a4.

📒 Files selected for processing (1)
  • src/components/ui/multi-select.tsx (1 hunks)

src/components/ui/multi-select.tsx Outdated Show resolved Hide resolved
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: 1

🧹 Nitpick comments (6)
src/components/ui/multi-select.tsx (4)

51-51: Internationalize hardcoded placeholder for localization

The placeholder prop is hardcoded as "Select options", which may not support localization. To enable internationalization, consider wrapping it with the translation function t.

Apply this diff to internationalize the placeholder:

-          placeholder = "Select options",
+          placeholder = t("select_options"),

171-171: Internationalize hardcoded text for localization

The text "No results found." is hardcoded in the CommandEmpty component. To support localization, wrap it with the translation function t.

Apply this diff to internationalize the text:

-          <CommandEmpty>No results found.</CommandEmpty>
+          <CommandEmpty>{t("no_results_found")}</CommandEmpty>

127-134: Add accessible labels to interactive icons for better accessibility

The XCircle icon acts as a button to remove selected options but lacks an accessible label. This can hinder users who rely on screen readers. Consider adding an aria-label to describe the action.

Apply this diff to add an accessible label:

             <XCircle
               className="ml-2 h-4 w-4 cursor-pointer"
+              aria-label="Remove option"
               onClick={(event) => {
                 event.stopPropagation();
                 toggleOption(value);
               }}
             />

139-145: Add accessible labels to interactive icons for better accessibility

The XIcon used to clear all selections lacks an accessible label. Adding an aria-label will improve accessibility for screen reader users.

Apply this diff to add an accessible label:

           <XIcon
             className="h-4 mx-2 cursor-pointer text-black"
+            aria-label="Clear all selections"
             onClick={(event) => {
               event.stopPropagation();
               handleClear();
             }}
           />
src/components/Facility/FacilityForm.tsx (2)

298-298: Internationalize hardcoded labels for localization

The FormLabel text "Features" is hardcoded. To support localization, wrap it with the translation function t.

Apply this diff to internationalize the label:

             <FormLabel>Features</FormLabel>
+            <FormLabel>{t("features")}</FormLabel>

308-308: Internationalize hardcoded placeholder for localization

The placeholder prop is hardcoded as "Select facility features". Consider using the t function to support multiple languages.

Apply this diff to internationalize the placeholder:

                     placeholder="Select facility features"
+                    placeholder={t("select_facility_features")}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f954a4 and 736b673.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityForm.tsx (4 hunks)
  • src/components/ui/multi-select.tsx (1 hunks)
🔇 Additional comments (1)
src/components/ui/multi-select.tsx (1)

155-158: Avoid duplicate id attributes to ensure unique identifiers

As previously mentioned, the id attribute "dropdown-toggle" is duplicated. Removing the duplicate id will prevent potential conflicts.

Apply this diff to remove the duplicate id attribute:

           <ChevronDown
-            id="dropdown-toggle"
             className="h-4 mx-2 cursor-pointer text-black"
           />

src/components/ui/multi-select.tsx Show resolved Hide resolved
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

♻️ Duplicate comments (3)
src/components/ui/multi-select.tsx (3)

57-58: ⚠️ Potential issue

Ensure selectedValues is always an array to prevent runtime errors

The selectedValues state is initialized with value, which could be undefined. This could lead to runtime errors since the component expects it to be an array.

Apply this diff to fix the issue:

-    const [selectedValues, setSelectedValues] = React.useState<string[]>(value);
+    const [selectedValues, setSelectedValues] = React.useState<string[]>(value || []);

59-63: ⚠️ Potential issue

Ensure effect hook handles undefined values safely

The effect hook updates selectedValues with value without checking for undefined, which could cause runtime errors.

Apply this diff to fix the issue:

     React.useEffect(() => {
-      setSelectedValues(value);
+      setSelectedValues(value || []);
     }, [value]);

145-148: ⚠️ Potential issue

Avoid duplicate id attributes to ensure unique identifiers

The id attribute "dropdown-toggle" is used multiple times within the component. In HTML, id attributes must be unique within the DOM.

Apply this diff to fix the issue:

     <ChevronDown
-      id="dropdown-toggle"
       className="h-4 mx-2 cursor-pointer text-black"
     />

Also applies to: 154-157

🧹 Nitpick comments (2)
src/components/ui/multi-select.tsx (2)

26-39: Enhance type safety with TypeScript improvements.

Consider these TypeScript enhancements:

  • Add readonly modifiers to props to ensure immutability
  • Type the icon prop properly instead of using a string type
 interface MultiSelectProps
   extends React.ButtonHTMLAttributes<HTMLButtonElement> {
-  options: {
+  readonly options: {
     label: string;
     value: string;
-    icon?: IconName;
+    icon?: IconName | undefined;
   }[];
-  onValueChange: (value: string[]) => void;
-  value: string[];
-  placeholder: string;
+  readonly onValueChange: (value: readonly string[]) => void;
+  readonly value: readonly string[];
+  readonly placeholder: string;
   modalPopover?: boolean;
   asChild?: boolean;
   className?: string;
 }

65-90: Optimize handlers for better performance.

Consider these performance improvements:

  • Memoize the allValues array in toggleAll
  • Use Set for faster lookups in toggleOption
+    const allValues = React.useMemo(
+      () => options.map((option) => option.value),
+      [options]
+    );

     const toggleOption = (option: string) => {
+      const valueSet = new Set(selectedValues);
+      if (valueSet.has(option)) {
+        valueSet.delete(option);
+      } else {
+        valueSet.add(option);
+      }
+      const newSelectedValues = Array.from(valueSet);
-      const newSelectedValues = selectedValues.includes(option)
-        ? selectedValues.filter((value) => value !== option)
-        : [...selectedValues, option];
       setSelectedValues(newSelectedValues);
       onValueChange(newSelectedValues);
     };

     const toggleAll = () => {
       if (selectedValues.length === options.length) {
         handleClear();
       } else {
-        const allValues = options.map((option) => option.value);
         setSelectedValues(allValues);
         onValueChange(allValues);
       }
     };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 736b673 and 40750a4.

📒 Files selected for processing (3)
  • public/locale/en.json (1 hunks)
  • src/components/Facility/FacilityForm.tsx (4 hunks)
  • src/components/ui/multi-select.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Facility/FacilityForm.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (1)
public/locale/en.json (1)

1857-1857: LGTM! Translation key added correctly.

The new translation key follows the existing naming pattern and provides a clear, user-friendly message.

@nihal467
Copy link
Member

LGTM

@nihal467 nihal467 added tested reviewed reviewed by a core member and removed needs testing labels Jan 21, 2025
@Jacobjeevan Jacobjeevan merged commit 7994107 into ohcnetwork:develop Jan 22, 2025
15 checks passed
Copy link

@AdityaJ2305 Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reviewed reviewed by a core member tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Create MultiOptionSelect shadcn component
4 participants