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 a picture uploader to picture-card-editor #18695

Merged
merged 9 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 39 additions & 33 deletions src/components/ha-picture-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { mdiImagePlus } from "@mdi/js";
import { LitElement, TemplateResult, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../common/dom/fire_event";
import { haStyle } from "../resources/styles";
import { createImage, generateImageThumbnailUrl } from "../data/image_upload";
import { showAlertDialog } from "../dialogs/generic/show-dialog-box";
import {
Expand Down Expand Up @@ -62,13 +63,15 @@ export class HaPictureUpload extends LitElement {
alt=${this.currentImageAltText ||
this.hass.localize("ui.components.picture-upload.current_image_alt")}
/>
<ha-button
@click=${this._handleChangeClick}
.label=${this.hass.localize(
"ui.components.picture-upload.change_picture"
)}
>
</ha-button>
<div>
<ha-button
@click=${this._handleChangeClick}
.label=${this.hass.localize(
"ui.components.picture-upload.change_picture"
)}
>
</ha-button>
</div>
</div>
</div>`;
}
Expand Down Expand Up @@ -140,32 +143,35 @@ export class HaPictureUpload extends LitElement {
}

static get styles() {
return css`
:host {
display: block;
height: 240px;
}
ha-file-upload {
height: 100%;
}
.center-vertical {
display: flex;
align-items: center;
height: 100%;
}
.value {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
img {
max-width: 100%;
max-height: 200px;
margin-bottom: 4px;
border-radius: var(--file-upload-image-border-radius);
}
`;
return [
haStyle,
css`
:host {
display: block;
height: 240px;
}
ha-file-upload {
height: 100%;
}
.center-vertical {
display: flex;
align-items: center;
height: 100%;
}
.value {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
img {
max-width: 100%;
max-height: 200px;
margin-bottom: 4px;
border-radius: var(--file-upload-image-border-radius);
}
`,
];
}
}

Expand Down
143 changes: 143 additions & 0 deletions src/components/ha-selector/ha-selector-image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { css, CSSResultGroup, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../common/dom/fire_event";
import { ImageSelector } from "../../data/selector";
import { HomeAssistant } from "../../types";
import "../ha-icon-button";
import "../ha-textarea";
import "../ha-textfield";
import "../ha-picture-upload";
import "../ha-radio";
import type { HaPictureUpload } from "../ha-picture-upload";
import { URL_PREFIX } from "../../data/image_upload";

@customElement("ha-selector-image")
export class HaImageSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;

@property() public value?: any;

@property() public name?: string;

@property() public label?: string;

@property() public placeholder?: string;

@property() public helper?: string;

@property({ attribute: false }) public selector!: ImageSelector;

@property({ type: Boolean }) public disabled = false;

@property({ type: Boolean }) public required = true;

@state() private showUpload = false;

protected firstUpdated(changedProps): void {
super.firstUpdated(changedProps);

if (!this.value || this.value.startsWith(URL_PREFIX)) {
this.showUpload = true;
}
}

protected render() {
return html`
<div>
<label>
${this.hass.localize("ui.components.selectors.image.select_image")}
<ha-formfield
.label=${this.hass.localize("ui.components.selectors.image.upload")}
>
<ha-radio
name="mode"
value="upload"
.checked=${this.showUpload}
@change=${this._radioGroupPicked}
></ha-radio>
</ha-formfield>
<ha-formfield
.label=${this.hass.localize("ui.components.selectors.image.url")}
>
<ha-radio
name="mode"
value="url"
.checked=${!this.showUpload}
@change=${this._radioGroupPicked}
></ha-radio>
</ha-formfield>
</label>
${!this.showUpload
? html`
<ha-textfield
.name=${this.name}
.value=${this.value || ""}
.placeholder=${this.placeholder || ""}
.helper=${this.helper}
helperPersistent
.disabled=${this.disabled}
@input=${this._handleChange}
.label=${this.label || ""}
.required=${this.required}
></ha-textfield>
`
: html`
<ha-picture-upload
.hass=${this.hass}
.value=${this.value?.startsWith(URL_PREFIX) ? this.value : null}
@change=${this._pictureChanged}
></ha-picture-upload>
`}
</div>
`;
}

private _radioGroupPicked(ev): void {
this.showUpload = ev.target.value === "upload";
}

private _pictureChanged(ev) {
const value = (ev.target as HaPictureUpload).value;

fireEvent(this, "value-changed", { value: value ?? undefined });
}

private _handleChange(ev) {
let value = ev.target.value;
if (this.value === value) {
return;
}
if (value === "" && !this.required) {
value = undefined;
}

fireEvent(this, "value-changed", { value });
}

static get styles(): CSSResultGroup {
return css`
:host {
display: block;
position: relative;
}
div {
display: flex;
flex-direction: column;
}
label {
display: flex;
flex-direction: column;
}
ha-textarea,
ha-textfield {
width: 100%;
}
`;
}
}

declare global {
interface HTMLElementTagNameMap {
"ha-selector-image": HaImageSelector;
}
}
Comment on lines +14 to +143
Copy link
Contributor

Choose a reason for hiding this comment

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

The new HaImageSelector component is well-implemented, providing a flexible UI component for image selection. It supports both upload and URL modes, which aligns with the PR's objectives. Consider specifying a more precise type than any for the value property to enhance type safety.

- @property() public value?: any;
+ @property() public value?: string | null; // Adjust as appropriate based on expected 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
@customElement("ha-selector-image")
export class HaImageSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property() public value?: any;
@property() public name?: string;
@property() public label?: string;
@property() public placeholder?: string;
@property() public helper?: string;
@property({ attribute: false }) public selector!: ImageSelector;
@property({ type: Boolean }) public disabled = false;
@property({ type: Boolean }) public required = true;
@state() private showUpload = false;
protected firstUpdated(changedProps): void {
super.firstUpdated(changedProps);
if (!this.value || this.value.startsWith(URL_PREFIX)) {
this.showUpload = true;
}
}
protected render() {
return html`
<div>
<label>
${this.hass.localize("ui.components.selectors.image.select_image")}
<ha-formfield
.label=${this.hass.localize("ui.components.selectors.image.upload")}
>
<ha-radio
name="mode"
value="upload"
.checked=${this.showUpload}
@change=${this._radioGroupPicked}
></ha-radio>
</ha-formfield>
<ha-formfield
.label=${this.hass.localize("ui.components.selectors.image.url")}
>
<ha-radio
name="mode"
value="url"
.checked=${!this.showUpload}
@change=${this._radioGroupPicked}
></ha-radio>
</ha-formfield>
</label>
${!this.showUpload
? html`
<ha-textfield
.name=${this.name}
.value=${this.value || ""}
.placeholder=${this.placeholder || ""}
.helper=${this.helper}
helperPersistent
.disabled=${this.disabled}
@input=${this._handleChange}
.label=${this.label || ""}
.required=${this.required}
></ha-textfield>
`
: html`
<ha-picture-upload
.hass=${this.hass}
.value=${this.value?.startsWith(URL_PREFIX) ? this.value : null}
@change=${this._pictureChanged}
></ha-picture-upload>
`}
</div>
`;
}
private _radioGroupPicked(ev): void {
this.showUpload = ev.target.value === "upload";
}
private _pictureChanged(ev) {
const value = (ev.target as HaPictureUpload).value;
fireEvent(this, "value-changed", { value: value ?? undefined });
}
private _handleChange(ev) {
let value = ev.target.value;
if (this.value === value) {
return;
}
if (value === "" && !this.required) {
value = undefined;
}
fireEvent(this, "value-changed", { value });
}
static get styles(): CSSResultGroup {
return css`
:host {
display: block;
position: relative;
}
div {
display: flex;
flex-direction: column;
}
label {
display: flex;
flex-direction: column;
}
ha-textarea,
ha-textfield {
width: 100%;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-selector-image": HaImageSelector;
}
}
@property() public value?: string | null;

1 change: 1 addition & 0 deletions src/components/ha-selector/ha-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const LOAD_ELEMENTS = {
file: () => import("./ha-selector-file"),
floor: () => import("./ha-selector-floor"),
label: () => import("./ha-selector-label"),
image: () => import("./ha-selector-image"),
language: () => import("./ha-selector-language"),
navigation: () => import("./ha-selector-navigation"),
number: () => import("./ha-selector-number"),
Expand Down
16 changes: 15 additions & 1 deletion src/data/image_upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,24 @@ interface Image {
id: string;
}

export const URL_PREFIX = "/api/image/serve/";

export interface ImageMutableParams {
name: string;
}

export const getIdFromUrl = (url: string): string | undefined => {
let id;
if (url.startsWith(URL_PREFIX)) {
id = url.substring(URL_PREFIX.length);
const idx = id.indexOf("/");
if (idx >= 0) {
id = id.substring(0, idx);
}
}
return id;
Comment on lines +17 to +26
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding explicit type annotations to enhance code clarity and maintainability. For instance, id should be explicitly typed as string | undefined.

- let id;
+ let id: string | undefined;

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 getIdFromUrl = (url: string): string | undefined => {
let id;
if (url.startsWith(URL_PREFIX)) {
id = url.substring(URL_PREFIX.length);
const idx = id.indexOf("/");
if (idx >= 0) {
id = id.substring(0, idx);
}
}
return id;
export const getIdFromUrl = (url: string): string | undefined => {
let id: string | undefined;
if (url.startsWith(URL_PREFIX)) {
id = url.substring(URL_PREFIX.length);
const idx = id.indexOf("/");
if (idx >= 0) {
id = id.substring(0, idx);
}
}
return id;

};

export const generateImageThumbnailUrl = (
mediaId: string,
size?: number,
Expand Down Expand Up @@ -61,5 +75,5 @@ export const updateImage = (
export const deleteImage = (hass: HomeAssistant, id: string) =>
hass.callWS({
type: "image/delete",
media_id: id,
image_id: id,
});
6 changes: 6 additions & 0 deletions src/data/selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type Selector =
| FileSelector
| IconSelector
| LabelSelector
| ImageSelector
| LanguageSelector
| LocationSelector
| MediaSelector
Expand Down Expand Up @@ -256,6 +257,11 @@ export interface IconSelector {
} | null;
}

export interface ImageSelector {
// eslint-disable-next-line @typescript-eslint/ban-types
image: {} | null;
}
Comment on lines +260 to +263
Copy link
Contributor

Choose a reason for hiding this comment

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

Define a more specific type for ImageSelector.

- export interface ImageSelector {
-   image: {} | null;
- }
+ export interface ImageSelector {
+   image: {
+     url?: string;
+     altText?: string;
+   } | null;
+ }

Using {} as a type is generally discouraged as it is too broad and does not provide useful type checking. Defining a more specific type will enhance maintainability and clarity of the code.


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 interface ImageSelector {
// eslint-disable-next-line @typescript-eslint/ban-types
image: {} | null;
}
export interface ImageSelector {
image: {
url?: string;
altText?: string;
} | null;
}


export interface LabelSelector {
label: {
multiple?: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const cardConfigStruct = assign(
);

const SCHEMA = [
{ name: "image", selector: { text: {} } },
{ name: "image", selector: { image: {} } },
{ name: "image_entity", selector: { entity: { domain: "image" } } },
{ name: "alt_text", selector: { text: {} } },
{ name: "theme", selector: { theme: {} } },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const cardConfigStruct = assign(
const SCHEMA = [
{ name: "entity", required: true, selector: { entity: {} } },
{ name: "name", selector: { text: {} } },
{ name: "image", selector: { text: {} } },
{ name: "image", selector: { image: {} } },
{ name: "camera_image", selector: { entity: { domain: "camera" } } },
{
name: "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const cardConfigStruct = assign(

const SCHEMA = [
{ name: "title", selector: { text: {} } },
{ name: "image", selector: { text: {} } },
{ name: "image", selector: { image: {} } },
{ name: "image_entity", selector: { entity: { domain: "image" } } },
{ name: "camera_image", selector: { entity: { domain: "camera" } } },
{
Expand Down
1 change: 1 addition & 0 deletions src/resources/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export const haStyle = css`
color: var(--error-color);
}

ha-button.warning,
mwc-button.warning {
--mdc-theme-primary: var(--error-color);
}
Expand Down
10 changes: 10 additions & 0 deletions src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,11 @@
"upload_failed": "Upload failed",
"unknown_file": "Unknown file"
},
"image": {
"select_image": "Select image",
"upload": "Upload picture",
"url": "Local path or web URL"
},
"location": {
"latitude": "[%key:ui::panel::config::zone::detail::latitude%]",
"longitude": "[%key:ui::panel::config::zone::detail::longitude%]",
Expand Down Expand Up @@ -412,6 +417,11 @@
"manual": "Manual Entry"
}
},
"image": {
"select_image": "Select image",
"upload": "Upload picture",
"url": "Local path or web URL"
},
Comment on lines +420 to +424
Copy link
Contributor

Choose a reason for hiding this comment

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

This section appears to be a duplicate of the earlier translation keys for image handling. Please verify and consider removing if it's unintentional.

"text": {
"show_password": "Show password",
"hide_password": "Hide password"
Expand Down
Loading