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 UI for setting view background #20708

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from

Conversation

Nezz
Copy link
Contributor

@Nezz Nezz commented May 2, 2024

Proposed change

Add UI for setting view background. As it turns out most people don't know that this feature even exists because it needs to be configured by manually uploading a file somewhere then configuring the URL through YAML.

Depends on home-assistant/core#116652 to enable serving images larger than 512px.

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

No more YAML needed 🎉

Screenshot 2024-05-02 231100
Screenshot 2024-05-02 231131

Additional information

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 new "Background" tab in the view editor for configuring Lovelace view backgrounds.
    • Added a custom element for editing background configurations, including image selection and cropping options.
    • Enhanced picture upload functionality to support original image thumbnails.
  • Improvements

    • Updated the image thumbnail generation to handle original images and ensure valid URLs are generated based on the provided parameters.

@Nezz
Copy link
Contributor Author

Nezz commented May 2, 2024

I spent way too much time trying to figure out why eslint errors out in the CI but not locally. As it turns out this was just broken by
sweepline/eslint-plugin-unused-imports#77
#20703

@Nezz Nezz marked this pull request as ready for review May 2, 2024 21:47
const backgroundUrl = (ev.target as HaPictureUpload).value;
const config = {
...this._config,
background: backgroundUrl
Copy link
Member

Choose a reason for hiding this comment

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

This is an old (and deprecated?) way of setting the background, preferably it should use themes

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The limitation of themes is that they are global, whereas this setting allows people to set a background per view (i.e. show kitchen stuff for the kitchen view). This was requested here:
https://www.reddit.com/r/homeassistant/comments/1cij7oa/comment/l29nul3/?utm_source=reddit&utm_medium=web2x&context=3

Copy link
Member

Choose a reason for hiding this comment

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

Themes are not global, you can set a theme on a specific view or even a card.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It wouldn't really help with this because

  1. You'd need to create a separate theme for each view. This would result in lots of duplication because I'm not aware of templating/partial overrides existing for themes.
  2. There's no visual editor for themes, so discoverability would still remain an issue.

I think the current behaviour is perfect where a theme can define a default background, but a view can choose to deviate from it.

`/api/image/serve/${mediaId}/${size}x${size}`;
export const generateImageThumbnailUrl = (
mediaId: string,
size: number,
Copy link
Member

Choose a reason for hiding this comment

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

size should be optional now that original can be set, if original is false size should be set.

Comment on lines +17 to +26
size?: number,
original: boolean = false
) => {
if (!original && !size) {
throw new Error("Size must be provided if original is false");
}

return original
? `/api/image/serve/${mediaId}/original`
: `/api/image/serve/${mediaId}/${size}x${size}`;
Copy link
Member

Choose a reason for hiding this comment

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

or maybe don't use an original parameter, so if size is not set, provide the original

Suggested change
size?: number,
original: boolean = false
) => {
if (!original && !size) {
throw new Error("Size must be provided if original is false");
}
return original
? `/api/image/serve/${mediaId}/original`
: `/api/image/serve/${mediaId}/${size}x${size}`;
size?: number
) => {
return size && size > 0
? `/api/image/serve/${mediaId}/${size}x${size}`
: `/api/image/serve/${mediaId}/original`;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was thinking about that approach, but in ha-picture-upload we use the same structure (original defaulting to false, size defaulting to 512) and I thought it'd be cleaner to keep it unified. Alternatively the original property could be removed in ha-picture-upload and the default of size could be changed to 0, but I'm not a fan of changing the default size to an "invalid" one.

Copy link

coderabbitai bot commented May 25, 2024

Walkthrough

Walkthrough

The recent updates introduce enhancements to the image upload and view editing functionalities in the Home Assistant frontend. A significant addition is the ability to manage original images and their thumbnails, alongside a new user interface for editing view backgrounds. These changes improve the flexibility and user experience of customizing Lovelace views, providing more control over background settings and image handling.

Changes

File Path Change Summary
src/components/ha-picture-upload.ts Added original property to HaPictureUpload class and updated generateImageThumbnailUrl method to handle original parameter.
src/data/image_upload.ts Modified generateImageThumbnailUrl function to accept original parameter, throwing an error if size is not provided when original is false.
src/panels/lovelace/editor/view-editor/hui-dialog-edit-view.ts Introduced a new "tab-background" for view background editing, including necessary import statements and HTML template updates.
src/panels/lovelace/editor/view-editor/hui-view-background-editor.ts Added a new custom element hui-view-background-editor for editing Lovelace view backgrounds, with properties and event handling for background changes.
src/translations/en.json Added translation entry "tab_background": "Background" for the new background editing tab.

Tip

New Features and Improvements

Review Settings

Introduced new personality profiles for code reviews. Users can now select between "Chill" and "Assertive" review tones to tailor feedback styles according to their preferences. The "Assertive" profile posts more comments and nitpicks the code more aggressively, while the "Chill" profile is more relaxed and posts fewer comments.

AST-based Instructions

CodeRabbit offers customizing reviews based on the Abstract Syntax Tree (AST) pattern matching. Read more about AST-based instructions in the documentation.

Community-driven AST-based Rules

We are kicking off a community-driven initiative to create and share AST-based rules. Users can now contribute their AST-based rules to detect security vulnerabilities, code smells, and anti-patterns. Please see the ast-grep-essentials repository for more information.

New Static Analysis Tools

We are continually expanding our support for static analysis tools. We have added support for biome, hadolint, and ast-grep. Update the settings in your .coderabbit.yaml file or head over to the settings page to enable or disable the tools you want to use.

Tone Settings

Users can now customize CodeRabbit to review code in the style of their favorite characters or personalities. Here are some of our favorite examples:

  • Mr. T: "You must talk like Mr. T in all your code reviews. I pity the fool who doesn't!"
  • Pirate: "Arr, matey! Ye must talk like a pirate in all yer code reviews. Yarrr!"
  • Snarky: "You must be snarky in all your code reviews. Snark, snark, snark!"

Revamped Settings Page

We have redesigned the settings page for a more intuitive layout, enabling users to find and adjust settings quickly. This change was long overdue; it not only improves the user experience but also allows our development team to add more settings in the future with ease. Going forward, the changes to .coderabbit.yaml will be reflected in the settings page, and vice versa.

Miscellaneous

  • Turn off free summarization: You can switch off free summarization of PRs opened by users not on a paid plan using the enable_free_tier setting.
  • Knowledge-base scope: You can now set the scope of the knowledge base to either the repository (local) or the organization (global) level using the knowledge_base setting. In addition, you can specify Jira project keys and Linear team keys to limit the knowledge base scope for those integrations.
  • High-level summary placement: You can now customize the location of the high-level summary in the PR description using the high_level_summary_placeholder setting (default @coderabbitai summary).
  • Revamped request changes workflow: You can now configure CodeRabbit to auto-approve or request changes on PRs based on the review feedback using the request_changes_workflow setting.

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits Files that changed from the base of the PR and between a9f00de and 3e8daf1.
Files selected for processing (5)
  • src/components/ha-picture-upload.ts (2 hunks)
  • src/data/image_upload.ts (1 hunks)
  • src/panels/lovelace/editor/view-editor/hui-dialog-edit-view.ts (3 hunks)
  • src/panels/lovelace/editor/view-editor/hui-view-background-editor.ts (1 hunks)
  • src/translations/en.json (1 hunks)
Additional Context Used
Biome (32)
src/components/ha-picture-upload.ts (5)

133-133: Unexpected any. Specify a different type.


1-2: Some named imports are only used as types.


6-10: Some named imports are only used as types.


10-11: All these imports are only used as types.


107-107: Use Number.NaN instead of the equivalent global.

src/data/image_upload.ts (3)

18-18: This type annotation is trivially inferred from its initialization.


44-46: This else clause can be omitted because previous branches break early.


1-1: All these imports are only used as types.

src/panels/lovelace/editor/view-editor/hui-dialog-edit-view.ts (20)

102-102: Forbidden non-null assertion.


123-123: Forbidden non-null assertion.


126-126: Forbidden non-null assertion.


137-137: This variable implicitly has the any type.


175-175: Forbidden non-null assertion.


237-237: Forbidden non-null assertion.


251-251: Forbidden non-null assertion.


255-255: Forbidden non-null assertion.


264-264: Do not use template literals if interpolation and special-character handling are not needed.


268-268: Forbidden non-null assertion.


277-277: Do not use template literals if interpolation and special-character handling are not needed.


284-284: Forbidden non-null assertion.


287-287: Forbidden non-null assertion.


301-301: Forbidden non-null assertion.


306-306: Forbidden non-null assertion.


311-311: Forbidden non-null assertion.


316-316: Forbidden non-null assertion.


331-331: Forbidden non-null assertion.


352-352: Forbidden non-null assertion.


376-376: Forbidden non-null assertion.

src/panels/lovelace/editor/view-editor/hui-view-background-editor.ts (4)

1-2: Some named imports are only used as types.


5-6: All these imports are only used as types.


6-7: All these imports are only used as types.


9-10: All these imports are only used as types.

Additional comments not posted (1)
src/translations/en.json (1)

5435-5443: The translation entries for the new "Background" tab are correctly added.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 2

Outside diff range and nitpick comments (3)
src/data/image_upload.ts (1)

Line range hint 44-46: Consider simplifying the error handling by removing the unnecessary else clause.

  if (resp.status === 413) {
    throw new Error(`Uploaded image is too large (${file.name})`);
- } else if (resp.status !== 200) {
+ } if (resp.status !== 200) {
    throw new Error("Unknown error");
  }
src/components/ha-picture-upload.ts (1)

Line range hint 34-131: The addition of the original property and its usage in the _uploadFile method are well-implemented. Consider specifying a more accurate type than any for error handling.

- } catch (err: any) {
+ } catch (err: Error) {
    showAlertDialog(this, {
      text: err.toString(),
    });
  }
src/panels/lovelace/editor/view-editor/hui-dialog-edit-view.ts (1)

Line range hint 52-167: The integration of the new "Background" tab and the HuiViewBackgroundEditor component is well-executed. Consider using more descriptive variable names for better code readability.

- const isCompatibleViewType =
+ const isViewTypeCompatible =

Comment on lines +15 to +27
export const generateImageThumbnailUrl = (
mediaId: string,
size?: number,
original: boolean = false
) => {
if (!original && !size) {
throw new Error("Size must be provided if original is false");
}

return original
? `/api/image/serve/${mediaId}/original`
: `/api/image/serve/${mediaId}/${size}x${size}`;
};
Copy link

Choose a reason for hiding this comment

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

The updated function signature and error handling logic look good. However, consider adding explicit type annotations for clarity.

- export const generateImageThumbnailUrl = (
+ export const generateImageThumbnailUrl = (mediaId: string, size?: number, original: boolean = false): string => {

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.

Suggested change
export const generateImageThumbnailUrl = (
mediaId: string,
size?: number,
original: boolean = false
) => {
if (!original && !size) {
throw new Error("Size must be provided if original is false");
}
return original
? `/api/image/serve/${mediaId}/original`
: `/api/image/serve/${mediaId}/${size}x${size}`;
};
export const generateImageThumbnailUrl = (mediaId: string, size?: number, original: boolean = false): string => {
if (!original && !size) {
throw new Error("Size must be provided if original is false");
}
return original
? `/api/image/serve/${mediaId}/original`
: `/api/image/serve/${mediaId}/${size}x${size}`;
};

Comment on lines +1 to +81
import "@material/mwc-list/mwc-list-item";
import { CSSResultGroup, LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/user/ha-user-badge";
import { LovelaceViewConfig } from "../../../../data/lovelace/config/view";
import { HomeAssistant, ValueChangedEvent } from "../../../../types";
import "../../../../components/ha-picture-upload";
import type { HaPictureUpload } from "../../../../components/ha-picture-upload";
import { CropOptions } from "../../../../dialogs/image-cropper-dialog/show-image-cropper-dialog";

const cropOptions: CropOptions = {
round: false,
type: "image/jpeg",
quality: 0.75,
aspectRatio: 1.78,
};

@customElement("hui-view-background-editor")
export class HuiViewBackgroundEditor extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;

@state() private _config!: LovelaceViewConfig;

set config(config: LovelaceViewConfig) {
this._config = config;
}

protected render() {
if (!this.hass) {
return nothing;
}

const backgroundUrlRegex = /url\(['"]?([^'"]+)['"]?\)/;
const backgroundUrlMatch = backgroundUrlRegex.exec(
this._config?.background || ""
);
const backgroundUrl = backgroundUrlMatch ? backgroundUrlMatch[1] : null;

return html`
<p>
${this.hass.localize(
"ui.panel.lovelace.editor.edit_view.background.title"
)}
</p>
<ha-picture-upload
.hass=${this.hass}
.value=${backgroundUrl}
crop
.cropOptions=${cropOptions}
original
@change=${this._backgroundChanged}
></ha-picture-upload>
`;
}

private _backgroundChanged(ev: ValueChangedEvent<string | null>) {
const backgroundUrl = (ev.target as HaPictureUpload).value;
const config = {
...this._config,
background: backgroundUrl
? `center / cover no-repeat url('${backgroundUrl}')`
: undefined,
};
fireEvent(this, "view-config-changed", { config });
}

static get styles(): CSSResultGroup {
return css`
:host {
display: block;
}
`;
}
}

declare global {
interface HTMLElementTagNameMap {
"hui-view-background-editor": HuiViewBackgroundEditor;
}
}
Copy link

Choose a reason for hiding this comment

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

The new HuiViewBackgroundEditor component is well-implemented. Consider using type-only imports to clarify that certain imports are only used for type information.

- import { HomeAssistant, ValueChangedEvent } from "../../../../types";
+ import type { HomeAssistant, ValueChangedEvent } from "../../../../types";

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.

Suggested change
import "@material/mwc-list/mwc-list-item";
import { CSSResultGroup, LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/user/ha-user-badge";
import { LovelaceViewConfig } from "../../../../data/lovelace/config/view";
import { HomeAssistant, ValueChangedEvent } from "../../../../types";
import "../../../../components/ha-picture-upload";
import type { HaPictureUpload } from "../../../../components/ha-picture-upload";
import { CropOptions } from "../../../../dialogs/image-cropper-dialog/show-image-cropper-dialog";
const cropOptions: CropOptions = {
round: false,
type: "image/jpeg",
quality: 0.75,
aspectRatio: 1.78,
};
@customElement("hui-view-background-editor")
export class HuiViewBackgroundEditor extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _config!: LovelaceViewConfig;
set config(config: LovelaceViewConfig) {
this._config = config;
}
protected render() {
if (!this.hass) {
return nothing;
}
const backgroundUrlRegex = /url\(['"]?([^'"]+)['"]?\)/;
const backgroundUrlMatch = backgroundUrlRegex.exec(
this._config?.background || ""
);
const backgroundUrl = backgroundUrlMatch ? backgroundUrlMatch[1] : null;
return html`
<p>
${this.hass.localize(
"ui.panel.lovelace.editor.edit_view.background.title"
)}
</p>
<ha-picture-upload
.hass=${this.hass}
.value=${backgroundUrl}
crop
.cropOptions=${cropOptions}
original
@change=${this._backgroundChanged}
></ha-picture-upload>
`;
}
private _backgroundChanged(ev: ValueChangedEvent<string | null>) {
const backgroundUrl = (ev.target as HaPictureUpload).value;
const config = {
...this._config,
background: backgroundUrl
? `center / cover no-repeat url('${backgroundUrl}')`
: undefined,
};
fireEvent(this, "view-config-changed", { config });
}
static get styles(): CSSResultGroup {
return css`
:host {
display: block;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"hui-view-background-editor": HuiViewBackgroundEditor;
}
}
import "@material/mwc-list/mwc-list-item";
import { CSSResultGroup, LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/user/ha-user-badge";
import { LovelaceViewConfig } from "../../../../data/lovelace/config/view";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import "../../../../components/ha-picture-upload";
import type { HaPictureUpload } from "../../../../components/ha-picture-upload";
import { CropOptions } from "../../../../dialogs/image-cropper-dialog/show-image-cropper-dialog";
const cropOptions: CropOptions = {
round: false,
type: "image/jpeg",
quality: 0.75,
aspectRatio: 1.78,
};
@customElement("hui-view-background-editor")
export class HuiViewBackgroundEditor extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _config!: LovelaceViewConfig;
set config(config: LovelaceViewConfig) {
this._config = config;
}
protected render() {
if (!this.hass) {
return nothing;
}
const backgroundUrlRegex = /url\(['"]?([^'"]+)['"]?\)/;
const backgroundUrlMatch = backgroundUrlRegex.exec(
this._config?.background || ""
);
const backgroundUrl = backgroundUrlMatch ? backgroundUrlMatch[1] : null;
return html`
<p>
${this.hass.localize(
"ui.panel.lovelace.editor.edit_view.background.title"
)}
</p>
<ha-picture-upload
.hass=${this.hass}
.value=${backgroundUrl}
crop
.cropOptions=${cropOptions}
original
@change=${this._backgroundChanged}
></ha-picture-upload>
`;
}
private _backgroundChanged(ev: ValueChangedEvent<string | null>) {
const backgroundUrl = (ev.target as HaPictureUpload).value;
const config = {
...this._config,
background: backgroundUrl
? `center / cover no-repeat url('${backgroundUrl}')`
: undefined,
};
fireEvent(this, "view-config-changed", { config });
}
static get styles(): CSSResultGroup {
return css`
:host {
display: block;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"hui-view-background-editor": HuiViewBackgroundEditor;
}
}

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.

None yet

4 participants