Skip to content

Commit

Permalink
Merge pull request #633 from Tencent/feat/tab/auto-scroll
Browse files Browse the repository at this point in the history
feat(tabs): automatically scrolls active item to the center
  • Loading branch information
LeeJim authored Jul 19, 2022
2 parents 24f736a + fcb4d74 commit 91e86c9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/tabs/tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export default class Tabs extends SuperComponent {
isScrollY: false,
direction: 'X',
animate: { duration: 0 },
offset: 0,
};

created() {
Expand All @@ -94,6 +95,9 @@ export default class Tabs extends SuperComponent {
isScrollY,
direction: isScrollX ? 'X' : 'Y',
});
this.gettingBoundingClientRect(`.${name}`, true).then((res: any) => {
this.containerWidth = res[0].width;
});
}

updateTabs() {
Expand Down Expand Up @@ -136,6 +140,20 @@ export default class Tabs extends SuperComponent {
}
}

calcScrollOffset(
containerWidth: number,
totalWidth: number,
targetLeft: number,
targetWidth: number,
offset: number,
) {
if (offset + targetLeft > containerWidth / 2) {
const maxOffset = totalWidth - containerWidth;
return Math.min(Math.abs(containerWidth / 2 - targetLeft - offset - targetWidth / 2), maxOffset);
}
return 0;
}

setTrack(color = '#0052d9') {
if (!this.properties.showBottomLine) return;
const { children } = this;
Expand All @@ -156,6 +174,19 @@ export default class Tabs extends SuperComponent {
}
}

if (this.containerWidth) {
const offset = this.calcScrollOffset(
this.containerWidth,
rect.width * res.length,
rect.left,
rect.width,
this.data.offset,
);
this.setData({
offset,
});
}

if (isScrollX) {
distance += (rect.width - trackLineWidth) / 2;
}
Expand Down
9 changes: 8 additions & 1 deletion src/tabs/tabs.wxml
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
<wxs src="./tabs.wxs" module="filters" />
<view class="{{prefix}}-class {{classPrefix}} {{classPrefix}}--{{placement}}">
<scroll-view class="{{classPrefix}}__scroll" enable-flex scroll-x="{{isScrollX}}" scroll-y="{{isScrollY}}">
<scroll-view
class="{{classPrefix}}__scroll"
enable-flex
scroll-left="{{offset}}"
scroll-x="{{isScrollX}}"
scroll-y="{{isScrollY}}"
scroll-with-animation
>
<view class="{{classPrefix}}__nav">
<view
wx:for="{{tabs}}"
Expand Down

0 comments on commit 91e86c9

Please sign in to comment.