Skip to content

Commit 6f7d6fb

Browse files
authored
fix(Picker): when the first item is a disabled item, the confirm event returns an incorrect value (#1999)
* fix(Picker): when the first item is a disabled item, the confirm event returns an incorrect value * chore: optimize findIndexOfEnabledOption func * fix: fix cr
1 parent 5db1e99 commit 6f7d6fb

2 files changed

Lines changed: 20 additions & 15 deletions

File tree

src/picker/picker.class.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ class Picker {
132132
this.height = this.holder.offsetHeight || DEFAULT_HOLDER_HEIGHT;
133133
this.indicatorOffset = this.itemGroupHeight / 2 - this.itemHeight / 2;
134134
let curIndex = findIndexOfEnabledOption(this.pickerColumns, this.options.defaultIndex || 0, this.options.keys);
135+
if (curIndex !== (this.options.defaultIndex || 0)) this.onChange(curIndex);
135136
this.itemClassName = `${classPrefix.value}-picker-item__item`;
136137
this.itemSelectedClassName = `${classPrefix.value}-picker-item__item--active`;
137138
this.startY = 0;

src/picker/utils.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,28 @@ export const limitNumberInRange = (num: number, min: number, max: number): numbe
1717

1818
export function findIndexOfEnabledOption(options: PickerColumn, startIndex: number, keys?: KeysType): number {
1919
// 确保起始索引在合法范围内
20-
const limitStartIndex = limitNumberInRange(startIndex, 0, options.length - 1);
20+
const limitStartIndex = limitNumberInRange(startIndex, 0, Math.max(options.length - 1, 0));
21+
const disabledKey = keys?.disabled ?? 'disabled';
2122

22-
// Forward Search
23-
const forwardIndex = options.findIndex(
24-
(opt, idx) => !lodashGet(opt, keys?.disabled ?? 'disabled') && idx >= limitStartIndex,
25-
);
26-
if (forwardIndex !== -1) {
27-
return forwardIndex;
23+
// 检查 limitStartIndex 是否已经是有效选项,若是直接返回
24+
if (!lodashGet(options[limitStartIndex], disabledKey)) {
25+
return limitStartIndex;
2826
}
2927

30-
// Backward Search
31-
const backwardIndex = options
32-
.slice(0, limitStartIndex)
33-
.reverse()
34-
.findIndex((opt) => !lodashGet(opt, keys?.disabled ?? 'disabled'));
35-
if (backwardIndex !== -1) {
36-
return limitStartIndex - 1 - backwardIndex;
37-
}
28+
// 双向搜索
29+
const maxOffset = Math.max(limitStartIndex, options.length - 1 - limitStartIndex);
30+
for (let i = 0; i <= maxOffset; i++) {
31+
// Forward Search
32+
const forwardIdx = limitStartIndex + i;
33+
if (forwardIdx < options.length && !lodashGet(options[forwardIdx], disabledKey)) {
34+
return forwardIdx;
35+
}
3836

37+
// Backward Search
38+
const backwardIdx = limitStartIndex - i;
39+
if (backwardIdx >= 0 && !lodashGet(options[backwardIdx], disabledKey)) {
40+
return backwardIdx;
41+
}
42+
}
3943
return 0;
4044
}

0 commit comments

Comments
 (0)