Make it possible to clear an optional select (#18047)

This commit is contained in:
Bram Kragten 2023-10-09 14:24:18 +02:00 committed by GitHub
parent 352e721d0c
commit 5b7ef941e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 2 deletions

View File

@ -68,6 +68,9 @@ export class HaSelect extends SelectBase {
.mdc-select__anchor .mdc-floating-label--float-above {
transform-origin: var(--float-start);
}
.mdc-select__selected-text-container {
padding-inline-end: var(--select-selected-text-padding-end, 0px);
}
`,
];
}

View File

@ -1,6 +1,6 @@
import "@material/mwc-list/mwc-list-item";
import { mdiClose } from "@mdi/js";
import { css, html, LitElement } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators";
import { fireEvent } from "../../common/dom/fire_event";
import { stopPropagation } from "../../common/dom/stop_propagation";
@ -209,6 +209,14 @@ export class HaSelectSelector extends LitElement {
`
)}
</ha-select>
${!this.required && !this.disabled && this.value
? html`<ha-icon-button
toggles
.label=${this.hass.localize("ui.common.clear")}
@click=${this._clearValue}
.path=${mdiClose}
></ha-icon-button>`
: nothing}
`;
}
@ -225,10 +233,19 @@ export class HaSelectSelector extends LitElement {
);
}
private _clearValue(): void {
if (this.disabled || !this.value) {
return;
}
fireEvent(this, "value-changed", {
value: undefined,
});
}
private _valueChanged(ev) {
ev.stopPropagation();
const value = ev.detail?.value || ev.target.value;
if (this.disabled || value === undefined || value === this.value) {
if (this.disabled || value === undefined || value === (this.value ?? "")) {
return;
}
fireEvent(this, "value-changed", {
@ -331,6 +348,9 @@ export class HaSelectSelector extends LitElement {
}
static styles = css`
:host {
position: relative;
}
ha-select,
mwc-formfield,
ha-formfield {
@ -339,6 +359,20 @@ export class HaSelectSelector extends LitElement {
mwc-list-item[disabled] {
--mdc-theme-text-primary-on-background: var(--disabled-text-color);
}
ha-select {
--select-selected-text-padding-end: 12px;
}
ha-icon-button {
position: absolute;
top: 10px;
right: 28px;
--mdc-icon-button-size: 36px;
--mdc-icon-size: 20px;
color: var(--secondary-text-color);
inset-inline-start: initial;
inset-inline-end: 28px;
direction: var(--direction);
}
`;
}