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

fix(IndexBar): allow active bottom anchor #10404

Merged
merged 3 commits into from
Mar 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 28 additions & 4 deletions packages/vant/src/index-bar/IndexBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export default defineComponent({
const touch = useTouch();
const scrollParent = useScrollParent(root);
const { children, linkChildren } = useChildren(INDEX_BAR_KEY);
let selectActiveIndex: string;

linkChildren({ props });

Expand Down Expand Up @@ -116,6 +117,9 @@ export default defineComponent({
return -1;
};

const getMatchAnchor = (index: string) =>
children.find((item) => String(item.index) === index);

const onScroll = () => {
if (isHidden(root)) {
return;
Expand All @@ -129,7 +133,16 @@ export default defineComponent({
item.getRect(scrollParent.value, scrollParentRect)
);

const active = getActiveAnchor(scrollTop, rects);
let active = -1;
if (selectActiveIndex) {
const match = getMatchAnchor(selectActiveIndex);
if (match) {
const rect = match.getRect(scrollParent.value, scrollParentRect);
active = getActiveAnchor(rect.top, rects);
}
} else {
active = getActiveAnchor(scrollTop, rects);
}

activeAnchor.value = indexList[active];

Expand All @@ -150,7 +163,7 @@ export default defineComponent({
state.top =
Math.max(props.stickyOffsetTop, rects[index].top - scrollTop) +
scrollParentRect.top;
} else if (index === active - 1) {
} else if (index === active - 1 && selectActiveIndex === '') {
const activeItemTop = rects[active].top - scrollTop;
state.active = activeItemTop > 0;
state.top =
Expand All @@ -160,6 +173,8 @@ export default defineComponent({
}
});
}

selectActiveIndex = '';
};

const init = () => {
Expand Down Expand Up @@ -193,10 +208,19 @@ export default defineComponent({
});

const scrollTo = (index: string | number) => {
index = String(index);
const match = children.find((item) => String(item.index) === index);
selectActiveIndex = String(index);
const match = getMatchAnchor(selectActiveIndex);

if (match) {
const scrollTop = getScrollTop(scrollParent.value!);
const scrollParentRect = useRect(scrollParent);
const { offsetHeight } = document.documentElement;

if (scrollTop === offsetHeight - scrollParentRect.height) {
onScroll();
return;
}

match.$el.scrollIntoView();

if (props.sticky && props.stickyOffsetTop) {
Expand Down