Skip to content

Commit b80481b

Browse files
authored
Generic picker: scroll to selected value on open (#28457)
1 parent 2ce1eaf commit b80481b

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

src/components/ha-picker-combo-box.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
133133

134134
@state() private _sectionTitle?: string;
135135

136+
@state() private _valuePinned = true;
137+
136138
private _allItems: (PickerComboBoxItem | string)[] = [];
137139

138140
private _selectedItemIndex = -1;
@@ -194,6 +196,15 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
194196
.renderItem=${this._renderItem}
195197
style="min-height: 36px;"
196198
class=${this._listScrolled ? "scrolled" : ""}
199+
.layout=${this.value && this._valuePinned
200+
? {
201+
pin: {
202+
index: this._getInitialSelectedIndex(),
203+
block: "center",
204+
},
205+
}
206+
: undefined}
207+
@unpinned=${this._handleUnpinned}
197208
@scroll=${this._onScrollList}
198209
@focus=${this._focusList}
199210
@visibilityChanged=${this._visibilityChanged}
@@ -244,6 +255,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
244255
}
245256
}
246257

258+
@eventOptions({ passive: true })
259+
private _handleUnpinned() {
260+
this._valuePinned = false;
261+
}
262+
247263
private _getAdditionalItems = (searchString?: string) =>
248264
this.getAdditionalItems?.(searchString) || [];
249265

@@ -592,6 +608,24 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
592608
private _keyFunction = (item: PickerComboBoxItem | string) =>
593609
typeof item === "string" ? item : item.id;
594610

611+
private _getInitialSelectedIndex() {
612+
if (!this._virtualizerElement || !this.value) {
613+
return 0;
614+
}
615+
616+
const index = this._virtualizerElement.items.findIndex(
617+
(item) =>
618+
typeof item !== "string" &&
619+
(item as PickerComboBoxItem).id === this.value
620+
);
621+
622+
if (index === -1) {
623+
return 0;
624+
}
625+
626+
return index;
627+
}
628+
595629
static get styles() {
596630
return [
597631
...super.styles,

0 commit comments

Comments
 (0)