1
0
mirror of https://github.com/home-assistant/frontend.git synced 2025-12-19 18:28:42 +00:00

Migrate ha-icon-picker to generic picker (#27677)

This commit is contained in:
Aidan Timson
2025-12-16 15:14:44 +00:00
committed by GitHub
parent b125cd5f3e
commit 88faedba65
4 changed files with 171 additions and 115 deletions

View File

@@ -34,10 +34,12 @@ export class HaGenericPicker extends LitElement {
@property({ type: Boolean, attribute: "allow-custom-value" }) @property({ type: Boolean, attribute: "allow-custom-value" })
public allowCustomValue; public allowCustomValue;
@property() public label?: string;
@property() public value?: string; @property() public value?: string;
@property() public icon?: string;
@property() public label?: string;
@property() public helper?: string; @property() public helper?: string;
@property() public placeholder?: string; @property() public placeholder?: string;
@@ -140,6 +142,10 @@ export class HaGenericPicker extends LitElement {
// helper to set new value after closing picker, to avoid flicker // helper to set new value after closing picker, to avoid flicker
private _newValue?: string; private _newValue?: string;
@property({ attribute: "error-message" }) public errorMessage?: string;
@property({ type: Boolean, reflect: true }) public invalid = false;
private _unsubscribeTinyKeys?: () => void; private _unsubscribeTinyKeys?: () => void;
protected render() { protected render() {
@@ -172,13 +178,15 @@ export class HaGenericPicker extends LitElement {
aria-label=${ifDefined(this.label)} aria-label=${ifDefined(this.label)}
@click=${this.open} @click=${this.open}
@clear=${this._clear} @clear=${this._clear}
.placeholder=${this.placeholder} .icon=${this.icon}
.showLabel=${this.showLabel} .showLabel=${this.showLabel}
.placeholder=${this.placeholder}
.value=${this.value} .value=${this.value}
.valueRenderer=${this.valueRenderer}
.required=${this.required} .required=${this.required}
.disabled=${this.disabled} .disabled=${this.disabled}
.invalid=${this.invalid}
.hideClearIcon=${this.hideClearIcon} .hideClearIcon=${this.hideClearIcon}
.valueRenderer=${this.valueRenderer}
> >
</ha-picker-field>`} </ha-picker-field>`}
</slot> </slot>
@@ -261,11 +269,16 @@ export class HaGenericPicker extends LitElement {
); );
private _renderHelper() { private _renderHelper() {
return this.helper const showError = this.invalid && this.errorMessage;
? html`<ha-input-helper-text .disabled=${this.disabled} const showHelper = !showError && this.helper;
>${this.helper}</ha-input-helper-text
>` if (!showError && !showHelper) {
: nothing; return nothing;
}
return html`<ha-input-helper-text .disabled=${this.disabled}>
${showError ? this.errorMessage : this.helper}
</ha-input-helper-text>`;
} }
private _dialogOpened = () => { private _dialogOpened = () => {
@@ -364,6 +377,9 @@ export class HaGenericPicker extends LitElement {
display: block; display: block;
margin: var(--ha-space-2) 0 0; margin: var(--ha-space-2) 0 0;
} }
:host([invalid]) ha-input-helper-text {
color: var(--mdc-theme-error, var(--error-color, #b00020));
}
wa-popover { wa-popover {
--wa-space-l: var(--ha-space-0); --wa-space-l: var(--ha-space-0);
@@ -386,12 +402,6 @@ export class HaGenericPicker extends LitElement {
} }
} }
@media (max-height: 1000px) {
wa-popover::part(body) {
max-height: 400px;
}
}
ha-bottom-sheet { ha-bottom-sheet {
--ha-bottom-sheet-height: 90vh; --ha-bottom-sheet-height: 90vh;
--ha-bottom-sheet-height: calc(100dvh - var(--ha-space-12)); --ha-bottom-sheet-height: calc(100dvh - var(--ha-space-12));

View File

@@ -1,8 +1,4 @@
import type { ComboBoxLitRenderer } from "@vaadin/combo-box/lit"; import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import type {
ComboBoxDataProviderCallback,
ComboBoxDataProviderParams,
} from "@vaadin/combo-box/vaadin-combo-box-light";
import type { TemplateResult } from "lit"; import type { TemplateResult } from "lit";
import { LitElement, css, html } from "lit"; import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators"; import { customElement, property } from "lit/decorators";
@@ -10,35 +6,54 @@ import memoizeOne from "memoize-one";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { customIcons } from "../data/custom_icons"; import { customIcons } from "../data/custom_icons";
import type { HomeAssistant, ValueChangedEvent } from "../types"; import type { HomeAssistant, ValueChangedEvent } from "../types";
import "./ha-combo-box";
import "./ha-icon";
import "./ha-combo-box-item"; import "./ha-combo-box-item";
import "./ha-generic-picker";
interface IconItem { import "./ha-icon";
icon: string; import type { PickerComboBoxItem } from "./ha-picker-combo-box";
parts: Set<string>;
keywords: string[];
}
interface RankedIcon { interface RankedIcon {
icon: string; item: PickerComboBoxItem;
rank: number; rank: number;
} }
let ICONS: IconItem[] = []; let ICONS: PickerComboBoxItem[] = [];
let ICONS_LOADED = false; let ICONS_LOADED = false;
interface IconData {
name: string;
keywords?: string[];
}
const createIconItem = (icon: IconData, prefix: string): PickerComboBoxItem => {
const iconId = `${prefix}:${icon.name}`;
const iconName = icon.name;
const parts = iconName.split("-");
const keywords = icon.keywords ?? [];
const searchLabels: Record<string, string> = {
iconName,
};
parts.forEach((part, index) => {
searchLabels[`part${index}`] = part;
});
keywords.forEach((keyword, index) => {
searchLabels[`keyword${index}`] = keyword;
});
return {
id: iconId,
primary: iconId,
icon: iconId,
search_labels: searchLabels,
sorting_label: iconId,
};
};
const loadIcons = async () => { const loadIcons = async () => {
ICONS_LOADED = true; ICONS_LOADED = true;
const iconList = await import("../../build/mdi/iconList.json"); const iconList = await import("../../build/mdi/iconList.json");
ICONS = iconList.default.map((icon) => ({ ICONS = iconList.default.map((icon) => createIconItem(icon, "mdi"));
icon: `mdi:${icon.name}`,
parts: new Set(icon.name.split("-")),
keywords: icon.keywords,
}));
const customIconLoads: Promise<IconItem[]>[] = []; const customIconLoads: Promise<PickerComboBoxItem[]>[] = [];
Object.keys(customIcons).forEach((iconSet) => { Object.keys(customIcons).forEach((iconSet) => {
customIconLoads.push(loadCustomIconItems(iconSet)); customIconLoads.push(loadCustomIconItems(iconSet));
}); });
@@ -47,19 +62,16 @@ const loadIcons = async () => {
}); });
}; };
const loadCustomIconItems = async (iconsetPrefix: string) => { const loadCustomIconItems = async (
iconsetPrefix: string
): Promise<PickerComboBoxItem[]> => {
try { try {
const getIconList = customIcons[iconsetPrefix].getIconList; const getIconList = customIcons[iconsetPrefix].getIconList;
if (typeof getIconList !== "function") { if (typeof getIconList !== "function") {
return []; return [];
} }
const iconList = await getIconList(); const iconList = await getIconList();
const customIconItems = iconList.map((icon) => ({ return iconList.map((icon) => createIconItem(icon, iconsetPrefix));
icon: `${iconsetPrefix}:${icon.name}`,
parts: new Set(icon.name.split("-")),
keywords: icon.keywords ?? [],
}));
return customIconItems;
} catch (_err) { } catch (_err) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.warn(`Unable to load icon list for ${iconsetPrefix} iconset`); console.warn(`Unable to load icon list for ${iconsetPrefix} iconset`);
@@ -67,10 +79,10 @@ const loadCustomIconItems = async (iconsetPrefix: string) => {
} }
}; };
const rowRenderer: ComboBoxLitRenderer<IconItem | RankedIcon> = (item) => html` const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
<ha-combo-box-item type="button"> <ha-combo-box-item type="button">
<ha-icon .icon=${item.icon} slot="start"></ha-icon> <ha-icon .icon=${item.id} slot="start"></ha-icon>
${item.icon} ${item.id}
</ha-combo-box-item> </ha-combo-box-item>
`; `;
@@ -94,85 +106,99 @@ export class HaIconPicker extends LitElement {
@property({ type: Boolean }) public invalid = false; @property({ type: Boolean }) public invalid = false;
private _getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
protected render(): TemplateResult { protected render(): TemplateResult {
return html` return html`
<ha-combo-box <ha-generic-picker
.hass=${this.hass} .hass=${this.hass}
item-value-path="icon"
item-label-path="icon"
.value=${this._value}
allow-custom-value allow-custom-value
.dataProvider=${ICONS_LOADED ? this._iconProvider : undefined} show-label
.label=${this.label} .getItems=${this._getIconPickerItems}
.helper=${this.helper} .helper=${this.helper}
.disabled=${this.disabled} .disabled=${this.disabled}
.required=${this.required} .required=${this.required}
.placeholder=${this.placeholder}
.errorMessage=${this.errorMessage} .errorMessage=${this.errorMessage}
.invalid=${this.invalid} .invalid=${this.invalid}
.renderer=${rowRenderer} .rowRenderer=${rowRenderer}
icon .icon=${this._icon}
@opened-changed=${this._openedChanged} .placeholder=${this.label}
.value=${this._value}
.searchFn=${this._filterIcons}
.notFoundLabel=${this.hass?.localize(
"ui.components.icon-picker.no_match"
)}
popover-placement="bottom-start"
@value-changed=${this._valueChanged} @value-changed=${this._valueChanged}
> >
${this._value || this.placeholder </ha-generic-picker>
? html`
<ha-icon .icon=${this._value || this.placeholder} slot="icon">
</ha-icon>
`
: html`<slot slot="icon" name="fallback"></slot>`}
</ha-combo-box>
`; `;
} }
// Filter can take a significant chunk of frame (up to 3-5 ms) // Filter can take a significant chunk of frame (up to 3-5 ms)
private _filterIcons = memoizeOne( private _filterIcons = memoizeOne(
(filter: string, iconItems: IconItem[] = ICONS) => { (
if (!filter) { filter: string,
filteredItems: PickerComboBoxItem[],
allItems: PickerComboBoxItem[]
): PickerComboBoxItem[] => {
const normalizedFilter = filter.toLowerCase().replace(/\s+/g, "-");
const iconItems = allItems?.length ? allItems : filteredItems;
if (!normalizedFilter.length) {
return iconItems; return iconItems;
} }
const filteredItems: RankedIcon[] = []; const rankedItems: RankedIcon[] = [];
const addIcon = (icon: string, rank: number) =>
filteredItems.push({ icon, rank });
// Filter and rank such that exact matches rank higher, and prefer icon name matches over keywords // Filter and rank such that exact matches rank higher, and prefer icon name matches over keywords
for (const item of iconItems) { for (const item of iconItems) {
if (item.parts.has(filter)) { const iconName = (item.id.split(":")[1] || item.id).toLowerCase();
addIcon(item.icon, 1); const parts = iconName.split("-");
} else if (item.keywords.includes(filter)) { const keywords = item.search_labels
addIcon(item.icon, 2); ? Object.values(item.search_labels)
} else if (item.icon.includes(filter)) { .filter((v): v is string => v !== null)
addIcon(item.icon, 3); .map((v) => v.toLowerCase())
} else if (item.keywords.some((word) => word.includes(filter))) { : [];
addIcon(item.icon, 4); const id = item.id.toLowerCase();
if (parts.includes(normalizedFilter)) {
rankedItems.push({ item, rank: 1 });
} else if (keywords.includes(normalizedFilter)) {
rankedItems.push({ item, rank: 2 });
} else if (id.includes(normalizedFilter)) {
rankedItems.push({ item, rank: 3 });
} else if (keywords.some((word) => word.includes(normalizedFilter))) {
rankedItems.push({ item, rank: 4 });
} }
} }
// Allow preview for custom icon not in list // Allow preview for custom icon not in list
if (filteredItems.length === 0) { if (rankedItems.length === 0) {
addIcon(filter, 0); rankedItems.push({
item: {
id: filter,
primary: filter,
icon: filter,
search_labels: { keyword: filter },
sorting_label: filter,
},
rank: 0,
});
} }
return filteredItems.sort((itemA, itemB) => itemA.rank - itemB.rank); return rankedItems
.sort((itemA, itemB) => itemA.rank - itemB.rank)
.map((item) => item.item);
} }
); );
private _iconProvider = ( protected firstUpdated() {
params: ComboBoxDataProviderParams, if (!ICONS_LOADED) {
callback: ComboBoxDataProviderCallback<IconItem | RankedIcon> loadIcons().then(() => {
) => { this._getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
const filteredItems = this._filterIcons(params.filter.toLowerCase(), ICONS); this.requestUpdate();
const iStart = params.page * params.pageSize; });
const iEnd = iStart + params.pageSize;
callback(filteredItems.slice(iStart, iEnd), filteredItems.length);
};
private async _openedChanged(ev: ValueChangedEvent<boolean>) {
const opened = ev.detail.value;
if (opened && !ICONS_LOADED) {
await loadIcons();
this.requestUpdate();
} }
} }
@@ -194,20 +220,18 @@ export class HaIconPicker extends LitElement {
); );
} }
private get _icon() {
return this.value?.length ? this.value : this.placeholder;
}
private get _value() { private get _value() {
return this.value || ""; return this.value || "";
} }
static styles = css` static styles = css`
*[slot="icon"] { ha-generic-picker {
color: var(--primary-text-color); width: 100%;
position: relative; display: block;
bottom: 2px;
}
*[slot="prefix"] {
margin-right: 8px;
margin-inline-end: 8px;
margin-inline-start: initial;
} }
`; `;
} }

View File

@@ -15,6 +15,7 @@ import type { HomeAssistant } from "../types";
import "./ha-combo-box-item"; import "./ha-combo-box-item";
import type { HaComboBoxItem } from "./ha-combo-box-item"; import type { HaComboBoxItem } from "./ha-combo-box-item";
import "./ha-icon-button"; import "./ha-icon-button";
import "./ha-icon";
declare global { declare global {
interface HASSDomEvents { interface HASSDomEvents {
@@ -32,6 +33,8 @@ export class HaPickerField extends LitElement {
@property() public value?: string; @property() public value?: string;
@property() public icon?: string;
@property() public helper?: string; @property() public helper?: string;
@property() public placeholder?: string; @property() public placeholder?: string;
@@ -49,6 +52,8 @@ export class HaPickerField extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public valueRenderer?: PickerValueRenderer; public valueRenderer?: PickerValueRenderer;
@property({ type: Boolean, reflect: true }) public invalid = false;
@query("ha-combo-box-item", true) public item!: HaComboBoxItem; @query("ha-combo-box-item", true) public item!: HaComboBoxItem;
@state() @state()
@@ -61,23 +66,32 @@ export class HaPickerField extends LitElement {
} }
protected render() { protected render() {
const hasValue = !!this.value?.length;
const showClearIcon = const showClearIcon =
!!this.value && !this.required && !this.disabled && !this.hideClearIcon; !!this.value && !this.required && !this.disabled && !this.hideClearIcon;
const placeholder = this.showLabel
? html`<span slot="overline">${this.placeholder}</span>` const overlineLabel =
: nothing; this.showLabel && hasValue && this.placeholder
? html`<span slot="overline">${this.placeholder}</span>`
: nothing;
const headlineContent = hasValue
? this.valueRenderer
? this.valueRenderer(this.value ?? "")
: html`<span slot="headline">${this.value}</span>`
: this.placeholder
? html`<span slot="headline" class="placeholder">
${this.placeholder}
</span>`
: nothing;
return html` return html`
<ha-combo-box-item .disabled=${this.disabled} type="button" compact> <ha-combo-box-item .disabled=${this.disabled} type="button" compact>
${this.value ${this.icon
? this.valueRenderer ? html`<ha-icon slot="start" .icon=${this.icon}></ha-icon>`
? html`${placeholder}${this.valueRenderer(this.value)}` : nothing}
: html`${placeholder}<span slot="headline">${this.value}</span>` ${overlineLabel}${headlineContent}
: html`
<span slot="headline" class="placeholder">
${this.placeholder}
</span>
`}
${this.unknown ${this.unknown
? html`<div slot="supporting-text" class="unknown"> ? html`<div slot="supporting-text" class="unknown">
${this.unknownItemText || ${this.unknownItemText ||
@@ -169,6 +183,11 @@ export class HaPickerField extends LitElement {
background-color: var(--ha-color-fill-warning-quiet-resting); background-color: var(--ha-color-fill-warning-quiet-resting);
} }
:host([invalid]) ha-combo-box-item:after {
height: 2px;
background-color: var(--mdc-theme-error, var(--error-color, #b00020));
}
.clear { .clear {
margin: 0 -8px; margin: 0 -8px;
--mdc-icon-button-size: 32px; --mdc-icon-button-size: 32px;

View File

@@ -769,6 +769,9 @@
"no_match": "No languages found for {term}", "no_match": "No languages found for {term}",
"no_languages": "No languages available" "no_languages": "No languages available"
}, },
"icon-picker": {
"no_match": "No matching icons found"
},
"tts-picker": { "tts-picker": {
"tts": "Text-to-speech", "tts": "Text-to-speech",
"none": "None" "none": "None"