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

Filter selected entities in entities picker using includeEntities property #22059

Merged
merged 2 commits into from
Sep 23, 2024

Conversation

piitaya
Copy link
Member

@piitaya piitaya commented Sep 23, 2024

Proposed change

This logic existed when using entityFilter. I added to includeEntities too because the entityFilter is ignored when using includeEntities property.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue or discussion:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Improved entity selection logic in the HaEntitiesPicker component for better performance and clarity.
    • Streamlined filtering logic for include and exclude entities in the HaEntityPicker component.
  • Bug Fixes

    • Enhanced handling of undefined values in entity inclusion, ensuring more reliable behavior during rendering.

Copy link
Contributor

coderabbitai bot commented Sep 23, 2024

Walkthrough

Walkthrough

The changes involve refactoring the HaEntitiesPickerLight and HaEntityPicker classes to streamline entity filtering logic. The _getEntityFilter method has been removed and replaced with new methods _excludeEntities and _includeEntities for managing entity inclusion and exclusion. The HaEntityPicker class has also been updated to use parameters directly for filtering instead of relying on class properties. These modifications enhance the clarity and efficiency of the entity filtering process.

Changes

Files Change Summary
src/components/entity/ha-entities-picker.ts Removed _getEntityFilter method; added _excludeEntities and _includeEntities methods for filtering logic. Updated rendering logic to utilize entityFilter directly.
src/components/entity/ha-entity-picker.ts Simplified filtering logic by using function parameters for includeEntities and excludeEntities instead of class properties. Removed mapping and sorting of entityIds.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant HaEntitiesPickerLight
    participant _includeEntities
    participant _excludeEntities

    User->>HaEntitiesPickerLight: Request to render entities
    HaEntitiesPickerLight->>_excludeEntities: Call _excludeEntities(value, excludeEntities)
    _excludeEntities-->>HaEntitiesPickerLight: Return excluded entities
    HaEntitiesPickerLight->>_includeEntities: Call _includeEntities(value, includeEntities)
    _includeEntities-->>HaEntitiesPickerLight: Return included entities
    HaEntitiesPickerLight-->>User: Render entities based on filtered results
Loading

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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range and nitpick comments (1)
src/components/entity/ha-entities-picker.ts (1)

142-154: Well-implemented _includeEntities method with optimization

The new _includeEntities method is well-implemented and addresses the issue described in the PR objectives. The use of memoizeOne is a good choice for optimization, especially if this method is called frequently during rendering.

The filtering logic correctly removes entities from includeEntities that are already present in value, which prevents duplicate selections and improves the user experience.

Consider adding a brief comment explaining the purpose of this method for improved readability. For example:

  // Filter out entities from includeEntities that are already selected (present in value)
  private _includeEntities = memoizeOne(
    (
      value: string[] | undefined,
      includeEntities: string[] | undefined
    ): string[] | undefined => {
      // ... rest of the method
    }
  );
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d25f725 and 5c86f9d.

Files selected for processing (1)
  • src/components/entity/ha-entities-picker.ts (3 hunks)
Additional comments not posted (3)
src/components/entity/ha-entities-picker.ts (3)

97-100: Improved handling of includeEntities

The change to use _includeEntities method is a good improvement. It allows for dynamic filtering of the includeEntities based on the current value, which can prevent duplicate entity selections and provide a more accurate list of available entities to pick from.


123-126: Consistent application of _includeEntities

The use of _includeEntities here maintains consistency with the earlier implementation. This ensures that the new filtering logic is applied uniformly across the component, which is a good practice for maintainability and predictable behavior.


Line range hint 1-254: Summary of changes and their impact

The changes in this file successfully address the issue of entityFilter being ignored when using the includeEntities property. The new _includeEntities method provides a clean and optimized way to filter entities, ensuring that already selected entities are not included in the list of available entities to pick from.

The implementation is consistent throughout the component, and the use of memoizeOne helps with performance optimization. These changes improve the functionality of the entity picker without introducing breaking changes.

Overall, this is a well-implemented bugfix that enhances the usability of the ha-entities-picker component.

To ensure that these changes don't have any unintended side effects, it would be beneficial to run the following verification:

This will help identify any other places in the codebase that might be affected by these changes and ensure that relevant tests are updated if necessary.

bramkragten
bramkragten previously approved these changes Sep 23, 2024
@bramkragten
Copy link
Member

Shouldnt we use exclude entities instead? 🤔

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 and nitpick comments (2)
src/components/entity/ha-entities-picker.ts (1)

135-144: LGTM: New _excludeEntities method implemented correctly.

The new _excludeEntities method is well-implemented:

  1. Uses memoizeOne for performance optimization.
  2. Correctly handles undefined value.
  3. Uses spread operator for immutability.
  4. Aligns with the PR objective of combining current value with excludeEntities.

Consider adding a type annotation for the return value of the memoized function for better clarity:

private _excludeEntities = memoizeOne(
  (
    value: string[] | undefined,
    excludeEntities: string[] | undefined
  ): string[] | undefined => {
    // ... (rest of the implementation)
  }
);
src/components/entity/ha-entity-picker.ts (1)

Line range hint 1-461: Suggestions for improvement

While the changes look good, here are a few suggestions to enhance the implementation:

  1. Local Testing: The PR checklist indicates that the code change has not been tested locally. It's recommended to perform local testing to ensure the changes work as expected in various scenarios.

  2. Performance Consideration: For large sets of entities, the filtering operations might impact performance. Consider adding a comment about potential optimization if performance issues are observed with extensive entity lists.

  3. Error Handling: Consider adding explicit checks for undefined values of includeEntities and excludeEntities to prevent potential runtime errors.

Here's a suggestion for adding error handling:

if (includeEntities) {
  entityIds = entityIds.filter((entityId) =>
    Array.isArray(includeEntities) ? includeEntities.includes(entityId) : true
  );
}

if (excludeEntities) {
  entityIds = entityIds.filter((entityId) =>
    Array.isArray(excludeEntities) ? !excludeEntities.includes(entityId) : true
  );
}

This change ensures that filtering only occurs when includeEntities and excludeEntities are properly defined arrays, preventing potential runtime errors.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5c86f9d and b163f3b.

Files selected for processing (2)
  • src/components/entity/ha-entities-picker.ts (4 hunks)
  • src/components/entity/ha-entity-picker.ts (2 hunks)
Additional comments not posted (5)
src/components/entity/ha-entities-picker.ts (3)

6-6: LGTM: Import statement refactored.

The import statement has been updated to include both HomeAssistant and ValueChangedEvent types from the same location. This change improves code organization without affecting functionality.


Line range hint 1-214: Summary: PR objectives achieved with improved entity filtering logic.

The changes in this file successfully address the PR objective of filtering selected entities using the includeEntities property. Key improvements include:

  1. Simplified entity filtering by directly using the entityFilter property.
  2. Introduction of the _excludeEntities method to combine current value with excludeEntities.
  3. Removal of the _getEntityFilter method, streamlining the code.

These changes enhance the clarity and efficiency of the entity filtering process without introducing breaking changes. The implementation aligns well with the PR's goals and maintains the existing functionality while resolving the reported issue.


100-100: LGTM: Entity filtering logic improved.

The changes simplify the code and improve the entity filtering logic:

  1. Direct use of entityFilter property (lines 100 and 123) simplifies the code.
  2. The new _excludeEntities method (lines 117-120) combines current value with excludeEntities, addressing the PR objective.

These changes effectively implement the filtering of selected entities using the includeEntities property while maintaining existing functionality.

To ensure the changes work as expected, please run the following verification script:

Also applies to: 117-120, 123-123

Verification successful

Verified: Entity filtering logic confirmed.

The verification confirms that:

  1. entityFilter is directly used in ha-entities-picker.ts (lines 100 and 123).
  2. The _excludeEntities method is properly invoked (lines 117-120).
  3. There are no remaining references to _getEntityFilter, ensuring deprecated methods are removed.

These findings validate that the entity filtering logic has been correctly improved and aligns with the PR objectives.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the usage of _excludeEntities method and entityFilter property

# Check for direct usage of entityFilter
echo "Checking direct usage of entityFilter:"
rg --type typescript 'entityFilter=' src/components/entity/

# Check for usage of _excludeEntities method
echo "Checking usage of _excludeEntities method:"
rg --type typescript '_excludeEntities\(' src/components/entity/

# Check for any remaining usage of _getEntityFilter method (should be none)
echo "Checking for any remaining usage of _getEntityFilter method (should be none):"
rg --type typescript '_getEntityFilter' src/components/entity/

Length of output: 641


Script:

#!/bin/bash
# Verify the usage of _excludeEntities method and entityFilter property

# Check for direct usage of entityFilter in .ts and .tsx files
echo "Checking direct usage of entityFilter:"
fd --extension ts --extension tsx --type f . src/components/entity/ | xargs rg 'entityFilter='

# Check for usage of _excludeEntities method in .ts and .tsx files
echo "Checking usage of _excludeEntities method:"
fd --extension ts --extension tsx --type f . src/components/entity/ | xargs rg '_excludeEntities\('

# Check for any remaining usage of _getEntityFilter method (should be none) in .ts and .tsx files
echo "Checking for any remaining usage of _getEntityFilter method (should be none):"
fd --extension ts --extension tsx --type f . src/components/entity/ | xargs rg '_getEntityFilter'

Length of output: 919

src/components/entity/ha-entity-picker.ts (2)

223-224: Approved: Improved consistency and fixed filtering issue

These changes correctly implement the filtering logic for includeEntities and excludeEntities. By using the parameters directly instead of accessing them through this., the code becomes more consistent with the method signature and easier to understand. This modification also addresses the issue mentioned in the PR objectives where the entityFilter was ignored when using the includeEntities property.

The implementation now correctly filters entities based on both includeEntities and excludeEntities, ensuring that the entity selection process works as expected.

Also applies to: 229-230


223-224: Addressing the suggestion to use "exclude entities"

@bramkragten suggested using "exclude entities" instead of the current approach. It's worth noting that the current implementation already handles both includeEntities and excludeEntities. This approach provides more flexibility by allowing users to both include specific entities and exclude others.

The current implementation:

  1. Filters entities to include only those in includeEntities (if specified).
  2. Then filters out entities listed in excludeEntities (if specified).

This dual-filtering approach offers more control over entity selection than using exclusion alone. It allows users to:

  1. Specify a subset of entities to consider (inclusion).
  2. Remove specific entities from that subset (exclusion).

If there are specific use cases where exclusion alone would be preferable, please provide more context so we can discuss potential optimizations or alternative implementations.

Also applies to: 229-230

@piitaya piitaya enabled auto-merge (squash) September 23, 2024 15:54
@piitaya piitaya merged commit f7f37c2 into dev Sep 23, 2024
9 checks passed
@piitaya piitaya deleted the entities-picker-include-entities-fix branch September 23, 2024 15:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants