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

Add visibility option to heading entities #22064

Merged
merged 2 commits into from
Sep 24, 2024
Merged

Conversation

piitaya
Copy link
Member

@piitaya piitaya commented Sep 23, 2024

Proposed change

Adds visibility option to heading entity element.

CleanShot 2024-09-24 at 14 36 51

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

    • Introduced a preview property for enhanced visibility management in heading components.
    • Added a user interface for configuring visibility conditions in the heading entity editor.
    • New visibility property allows for conditional display of heading entities.
  • Documentation

    • Updated translations to include descriptions for the new visibility feature and its conditions.
  • Bug Fixes

    • Improved lifecycle management for media query listeners to ensure proper visibility updates.

@piitaya piitaya marked this pull request as draft September 23, 2024 15:55
@piitaya piitaya force-pushed the heading-entity-visiblity branch from 934148d to 14a20a3 Compare September 24, 2024 12:32
@piitaya piitaya force-pushed the heading-entity-visiblity branch from 14a20a3 to d4e7c6c Compare September 24, 2024 12:32
@piitaya piitaya marked this pull request as ready for review September 24, 2024 12:36
Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

Walkthrough

The changes introduce enhancements to the HuiHeadingEntity, HuiHeadingCard, and related components to manage visibility based on media queries and conditions. A new preview property is added to control visibility in both the heading entity and card. The HeadingEntityConfig interface is updated to include a visibility property for defining conditions. The HuiHeadingEntityEditor is modified to support configuring these visibility conditions through a user interface. Additionally, new translations for visibility are added to the English language file.

Changes

Files Change Summary
src/panels/lovelace/cards/heading/hui-heading-entity.ts Introduced preview property; implemented lifecycle methods (connectedCallback, disconnectedCallback); modified update method; added visibility management methods.
src/panels/lovelace/cards/hui-heading-card.ts Added preview property; updated rendering logic to pass preview to hui-heading-entity.
src/panels/lovelace/cards/types.ts Added visibility property to HeadingEntityConfig interface, allowing for conditional visibility.
src/panels/lovelace/editor/heading-entity/hui-heading-entity-editor.ts Added preview property; updated entityConfigStruct to include visibility; modified rendering logic and added _conditionChanged method for visibility configuration.
src/translations/en.json Added visibility and visibility_explanation properties to the entity_config object for user interface localization.

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.

@piitaya piitaya changed the title Add visibility config option to heading entity element Add visibility option to heading entities Sep 24, 2024
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: 4

Outside diff range and nitpick comments (2)
src/panels/lovelace/cards/hui-heading-card.ts (1)

99-103: LGTM: Usage of preview property in render method

The preview property is correctly passed to the hui-heading-entity component, allowing child components to react to the preview state. This implementation is consistent with the PR objectives.

Consider passing only the necessary properties from this.hass to the child component for better performance and clearer dependencies. For example:

<hui-heading-entity
  .config=${config}
  .hass=${{
    localize: this.hass.localize,
    states: this.hass.states,
    // Add other necessary properties
  }}
  .preview=${this.preview}
>
</hui-heading-entity>

This approach would make the component's dependencies more explicit and potentially improve performance by reducing the number of properties passed to child components.

src/panels/lovelace/editor/heading-entity/hui-heading-entity-editor.ts (1)

186-190: Remove redundant margin styling

The margin: 0; and margin-bottom: 8px; declarations in the .intro class conflict with each other. Since margin-bottom: 8px; overrides the bottom margin, the margin: 0; can be simplified to margin: 0 0 8px 0; for clarity.

Apply this diff to simplify the margin styling:

.intro {
-  margin: 0;
   color: var(--secondary-text-color);
-  margin-bottom: 8px;
+  margin: 0 0 8px 0;
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c4a700a and d4e7c6c.

Files selected for processing (5)
  • src/panels/lovelace/cards/heading/hui-heading-entity.ts (4 hunks)
  • src/panels/lovelace/cards/hui-heading-card.ts (2 hunks)
  • src/panels/lovelace/cards/types.ts (1 hunks)
  • src/panels/lovelace/editor/heading-entity/hui-heading-entity-editor.ts (7 hunks)
  • src/translations/en.json (1 hunks)
Additional context used
Biome
src/panels/lovelace/editor/heading-entity/hui-heading-entity-editor.ts

[error] 153-153: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

Additional comments not posted (7)
src/panels/lovelace/cards/hui-heading-card.ts (2)

39-40: LGTM: Addition of preview property

The new preview property is correctly implemented as a boolean with the @property decorator. This addition aligns with the PR objectives and follows the coding conventions used in the rest of the class.


Line range hint 1-214: Summary: Successful implementation of visibility config option

The changes in this file successfully implement the visibility config option for the heading entity element as described in the PR objectives. The new preview property is correctly added and utilized in the render method, allowing child components to react to the preview state.

The implementation is consistent with the existing code structure and follows established patterns. These changes enhance the functionality of the HuiHeadingCard component by providing more control over the visibility of heading elements.

To ensure that these changes are properly integrated and don't introduce any regressions, please run the following verification script:

This script will help verify the correct implementation of the preview property and its usage in the render method, as well as check for any potential regressions in the HuiHeadingCard class.

src/panels/lovelace/cards/types.ts (1)

511-511: LGTM! Consider updating documentation.

The addition of the visibility property to the HeadingEntityConfig interface is well-implemented and aligns with the PR objective. It provides users with the ability to conditionally render heading entities based on specified conditions, enhancing the flexibility of the Lovelace UI.

To ensure comprehensive documentation of this new feature, please run the following script to check if the relevant documentation has been updated:

If the script doesn't return any results, consider updating the documentation to include information about the new visibility property for HeadingEntityConfig.

src/translations/en.json (1)

Line range hint 5998-6012: New visibility properties added to entity_config

Two new properties have been added to the entity_config object:

  1. "visibility": This property likely indicates the conditions under which an entity is displayed.
  2. "visibility_explanation": This property provides a description of how the visibility of the entity is determined.

These additions enhance the configurability of entities in the UI, allowing for more granular control over when and how entities are displayed.

src/panels/lovelace/cards/heading/hui-heading-entity.ts (2)

35-36: Addition of 'preview' property enhances visibility control

The introduction of the preview property provides better control over the component's visibility during preview states, which is a valuable enhancement.


83-91: '_updateVisibility' method correctly manages component visibility

The _updateVisibility method effectively determines the component's visibility based on the forceVisible flag, preview state, and defined visibility conditions. The logic is sound and should work as intended.

src/panels/lovelace/editor/heading-entity/hui-heading-entity-editor.ts (1)

105-125: Ensure localization keys exist for new strings

The localization keys used for the visibility panel header and explanation ("ui.panel.lovelace.editor.card.heading.entity_config.visibility" and "ui.panel.lovelace.editor.card.heading.entity_config.visibility_explanation") should be added to the localization files to support internationalization.

Run the following script to check if the localization keys exist:

Comment on lines +76 to +81
protected update(changedProps: PropertyValues<typeof this>): void {
super.update(changedProps);
if (changedProps.has("hass") || changedProps.has("preview")) {
this._updateVisibility();
}
}
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

Include 'config' changes in the visibility update condition

Currently, _updateVisibility() is called when hass or preview changes. If the config property changes, the visibility may also need to be updated to reflect the new configuration. Consider adding changedProps.has("config") to ensure visibility is updated when the configuration changes.

Apply this diff to implement the change:

 protected update(changedProps: PropertyValues<typeof this>): void {
   super.update(changedProps);
-  if (changedProps.has("hass") || changedProps.has("preview")) {
+  if (
+    changedProps.has("hass") ||
+    changedProps.has("preview") ||
+    changedProps.has("config")
+  ) {
     this._updateVisibility();
   }
 }
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
protected update(changedProps: PropertyValues<typeof this>): void {
super.update(changedProps);
if (changedProps.has("hass") || changedProps.has("preview")) {
this._updateVisibility();
}
}
protected update(changedProps: PropertyValues<typeof this>): void {
super.update(changedProps);
if (
changedProps.has("hass") ||
changedProps.has("preview") ||
changedProps.has("config")
) {
this._updateVisibility();
}
}

Comment on lines +98 to +115
private _listenMediaQueries() {
const config = this._config(this.config);
if (!config?.visibility) {
return;
}
const conditions = config.visibility;
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;

this._listeners = attachConditionMediaQueriesListeners(
config.visibility,
(matches) => {
this._updateVisibility(hasOnlyMediaQuery && matches);
}
);
}
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

Prevent duplicate media query listeners by clearing existing listeners

If connectedCallback() is called multiple times without a corresponding disconnectedCallback(), multiple media query listeners could be attached, potentially leading to unexpected behavior or memory leaks. To avoid this, consider calling _clearMediaQueries() at the beginning of the _listenMediaQueries() method to ensure that existing listeners are removed before new ones are added.

Apply this diff to implement the change:

 private _listenMediaQueries() {
+   this._clearMediaQueries();
    const config = this._config(this.config);
    if (!config?.visibility) {
      return;
    }
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
private _listenMediaQueries() {
const config = this._config(this.config);
if (!config?.visibility) {
return;
}
const conditions = config.visibility;
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
this._listeners = attachConditionMediaQueriesListeners(
config.visibility,
(matches) => {
this._updateVisibility(hasOnlyMediaQuery && matches);
}
);
}
private _listenMediaQueries() {
this._clearMediaQueries();
const config = this._config(this.config);
if (!config?.visibility) {
return;
}
const conditions = config.visibility;
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
this._listeners = attachConditionMediaQueriesListeners(
config.visibility,
(matches) => {
this._updateVisibility(hasOnlyMediaQuery && matches);
}
);
}

@@ -20,6 +31,7 @@ const entityConfigStruct = object({
content: optional(union([string(), array(string())])),
icon: optional(string()),
tap_action: optional(actionConfigStruct),
visibility: optional(array(any())),
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

Improve type safety for the visibility property

Using any() in visibility: optional(array(any())) reduces type safety and can lead to runtime errors. To enhance maintainability and catch potential issues at compile time, consider defining a specific struct for the visibility conditions.

Define a struct for the conditions, for example:

const conditionStruct = object({
  entity: string(),
  state: optional(string()),
  // Add other required properties
});

const entityConfigStruct = object({
  // existing properties
  visibility: optional(array(conditionStruct)),
});

Comment on lines +140 to +157
private _conditionChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
return;
}

const conditions = ev.detail.value as Condition[];

const newConfig: HeadingEntityConfig = {
...this._config,
visibility: conditions,
};
if (newConfig.visibility?.length === 0) {
delete newConfig.visibility;
}

fireEvent(this, "config-changed", { config: newConfig });
}
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

Avoid using the delete operator for better performance

The delete operator can negatively impact performance because it changes the object's shape in V8 JavaScript engine. Instead of deleting the visibility property, set it to undefined or omit it when creating newConfig.

Apply this diff to address the performance issue:

       const newConfig: HeadingEntityConfig = {
         ...this._config,
-        visibility: conditions,
+        visibility: conditions.length > 0 ? conditions : undefined,
       };
-      if (newConfig.visibility?.length === 0) {
-        delete newConfig.visibility;
-      }
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
private _conditionChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
return;
}
const conditions = ev.detail.value as Condition[];
const newConfig: HeadingEntityConfig = {
...this._config,
visibility: conditions,
};
if (newConfig.visibility?.length === 0) {
delete newConfig.visibility;
}
fireEvent(this, "config-changed", { config: newConfig });
}
private _conditionChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (!this._config || !this.hass) {
return;
}
const conditions = ev.detail.value as Condition[];
const newConfig: HeadingEntityConfig = {
...this._config,
visibility: conditions.length > 0 ? conditions : undefined,
};
fireEvent(this, "config-changed", { config: newConfig });
}
Tools
Biome

[error] 153-153: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

@piitaya piitaya merged commit c30e4a6 into dev Sep 24, 2024
13 checks passed
@piitaya piitaya deleted the heading-entity-visiblity branch September 24, 2024 15:12
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