index.js 8.59 KB
Newer Older
李嘉林 committed
1 2
import { VantComponent } from '../common/component';
import { touch } from '../mixins/touch';
程默 committed
3 4 5 6 7 8 9 10
import {
  getAllRect,
  getRect,
  groupSetData,
  nextTick,
  requestAnimationFrame,
} from '../common/utils';
import { isDef } from '../common/validator';
李嘉林 committed
11
VantComponent({
程默 committed
12
  mixins: [touch],
李嘉林 committed
13
  classes: ["nav-class", "tab-class", "tab-active-class", "line-class"],
程默 committed
14
  relation: {
李嘉林 committed
15 16 17
    name: "tab",
    type: "descendant",
    current: "tabs",
程默 committed
18 19 20 21 22 23 24 25 26 27
    linked(target) {
      target.index = this.children.length - 1;
      this.updateTabs();
    },
    unlinked() {
      this.children = this.children.map((child, index) => {
        child.index = index;
        return child;
      });
      this.updateTabs();
李嘉林 committed
28
    }
程默 committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42
  },
  props: {
    sticky: Boolean,
    border: Boolean,
    swipeable: Boolean,
    titleActiveColor: String,
    titleInactiveColor: String,
    color: String,
    animated: {
      type: Boolean,
      observer() {
        this.children.forEach((child, index) =>
          child.updateRender(index === this.data.currentIndex, this)
        );
李嘉林 committed
43
      }
程默 committed
44 45 46 47
    },
    lineWidth: {
      type: [String, Number],
      value: 40,
李嘉林 committed
48 49 50 51 52 53 54 55 56
      // observer: "resize"
    },
    lineLengthType: {
      type: [String, Number],
      value: 1  // 1默认自适应 2短自适应 3 固定宽度取值lineWidth
    },
    linePosition: {
      type: [String, Number],
      value: 1  // 1默认右对齐 2居中 3铺满
程默 committed
57 58 59
    },
    lineHeight: {
      type: [String, Number],
李嘉林 committed
60
      value: -1
程默 committed
61 62 63 64 65 66 67
    },
    active: {
      type: [String, Number],
      value: 0,
      observer(name) {
        if (name !== this.getCurrentName()) {
          this.setCurrentIndexByName(name);
李嘉林 committed
68
        }
李嘉林 committed
69
      }
程默 committed
70 71 72
    },
    type: {
      type: String,
李嘉林 committed
73
      value: "line"
程默 committed
74 75 76
    },
    ellipsis: {
      type: Boolean,
李嘉林 committed
77
      value: true
程默 committed
78 79 80
    },
    duration: {
      type: Number,
李嘉林 committed
81
      value: 0.3
程默 committed
82 83 84
    },
    zIndex: {
      type: Number,
李嘉林 committed
85
      value: 1
程默 committed
86 87 88 89 90 91
    },
    swipeThreshold: {
      type: Number,
      value: 5,
      observer(value) {
        this.setData({
李嘉林 committed
92
          scrollable: this.children.length > value || !this.data.ellipsis
程默 committed
93
        });
李嘉林 committed
94
      }
程默 committed
95 96 97
    },
    offsetTop: {
      type: Number,
李嘉林 committed
98
      value: 0
程默 committed
99 100 101
    },
    lazyRender: {
      type: Boolean,
李嘉林 committed
102 103
      value: true
    }
程默 committed
104 105 106 107 108 109 110 111
  },
  data: {
    tabs: [],
    scrollLeft: 0,
    scrollable: false,
    currentIndex: 0,
    container: null,
    skipTransition: true,
李嘉林 committed
112
    lineOffsetLeft: 0
程默 committed
113 114
  },
  mounted() {
李嘉林 committed
115
    this.getElementInfo();
程默 committed
116 117
    requestAnimationFrame(() => {
      this.setData({
李嘉林 committed
118
        container: () => this.createSelectorQuery().select(".van-tabs")
程默 committed
119 120 121 122 123 124
      });
      this.resize(true);
      this.scrollIntoView();
    });
  },
  methods: {
李嘉林 committed
125 126 127 128 129 130 131 132 133 134 135
    getElementInfo() {
      let that = this;
      wx
        .createSelectorQuery()
        .in(this)
        .selectAll(".van-tab")
        .boundingClientRect()
        .exec((rect = []) =>
          that.triggerEvent("getEleInfo", { rect, vanTabsThis: this })
        );
    },
程默 committed
136 137 138
    updateTabs() {
      const { children = [], data } = this;
      this.setData({
李嘉林 committed
139 140
        tabs: children.map(child => child.data),
        scrollable: this.children.length > data.swipeThreshold || !data.ellipsis
程默 committed
141 142
      });
      this.setCurrentIndexByName(data.active || this.getCurrentName());
李嘉林 committed
143
    },
程默 committed
144 145 146 147 148 149 150 151 152
    trigger(eventName, child) {
      const { currentIndex } = this.data;
      const currentChild = child || this.children[currentIndex];
      if (!isDef(currentChild)) {
        return;
      }
      this.$emit(eventName, {
        index: currentChild.index,
        name: currentChild.getComputedName(),
李嘉林 committed
153
        title: currentChild.data.title
程默 committed
154 155 156 157 158 159
      });
    },
    onTap(event) {
      const { index } = event.currentTarget.dataset;
      const child = this.children[index];
      if (child.data.disabled) {
李嘉林 committed
160
        this.trigger("disabled", child);
程默 committed
161 162 163
      } else {
        this.setCurrentIndex(index);
        nextTick(() => {
李嘉林 committed
164
          this.trigger("click");
程默 committed
165 166 167 168 169 170 171
        });
      }
    },
    // correct the index of active tab
    setCurrentIndexByName(name) {
      const { children = [] } = this;
      const matched = children.filter(
李嘉林 committed
172
        child => child.getComputedName() === name
程默 committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      );
      if (matched.length) {
        this.setCurrentIndex(matched[0].index);
      }
    },
    setCurrentIndex(currentIndex) {
      const { data, children = [] } = this;
      if (
        !isDef(currentIndex) ||
        currentIndex >= children.length ||
        currentIndex < 0
      ) {
        return;
      }
      groupSetData(this, () => {
        children.forEach((item, index) => {
          const active = index === currentIndex;
          if (active !== item.data.active || !item.inited) {
            item.updateRender(active, this);
          }
        });
      });
      if (currentIndex === data.currentIndex) {
        return;
      }
      const shouldEmitChange = data.currentIndex !== null;
      this.setData({ currentIndex });
      nextTick(() => {
        this.resize();
        this.scrollIntoView();
李嘉林 committed
203
        this.trigger("input");
程默 committed
204
        if (shouldEmitChange) {
李嘉林 committed
205
          this.trigger("change");
李嘉林 committed
206
        }
程默 committed
207 208 209 210 211 212 213
      });
    },
    getCurrentName() {
      const activeTab = this.children[this.data.currentIndex];
      if (activeTab) {
        return activeTab.getComputedName();
      }
李嘉林 committed
214
    },
程默 committed
215
    resize(skipTransition = false) {
李嘉林 committed
216 217
      console.log("resize")
      if (this.data.type !== "line") {
程默 committed
218 219 220 221
        return;
      }
      const { currentIndex, ellipsis } = this.data;
      Promise.all([
李嘉林 committed
222 223
        getAllRect(this, ".van-tab"),
        getRect(this, ".van-tabs__line")
程默 committed
224 225 226 227 228
      ]).then(([rects = [], lineRect]) => {
        const rect = rects[currentIndex];
        if (rect == null) {
          return;
        }
李嘉林 committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        let lineWidths = 0;
        let lineOffsetLeft = 0;
        if (this.data.lineLengthType == 1) {
          if (this.data.linePosition == 2) {
            lineOffsetLeft = rect.left;
          } else {
            lineOffsetLeft = rects
              .slice(0, currentIndex)
              .reduce((prev, curr) => prev + curr.width, 0);
            lineOffsetLeft += 8;
          }
          lineWidths = rect.width;
        } else if (this.data.lineLengthType == 2) {
          // 宽度*80%
          if (this.data.linePosition == 2) {
            lineOffsetLeft = rect.left+rect.width*0.2;
          } else {
            lineOffsetLeft = rects
              .slice(0, currentIndex)
              .reduce((prev, curr) => prev + curr.width, 0);
            lineOffsetLeft += rect.width * 0.2;
            lineOffsetLeft += 8;
          }
          lineWidths = rect.width * 0.6;
        } else {
          // 有问题暂不支持固定宽度
          // lineOffsetLeft = rects
          //   .slice(0, currentIndex)
          //   .reduce((prev, curr) => prev + curr.width, 0);
          // lineOffsetLeft += this.data.lineWidth / 2;
          // lineWidths = this.data.lineWidth;
        }
程默 committed
261
        this.setData({
李嘉林 committed
262
          lineWidth: lineWidths,
程默 committed
263
          lineOffsetLeft,
李嘉林 committed
264
          skipTransition
程默 committed
265 266
        });
      });
李嘉林 committed
267
    },
程默 committed
268 269 270 271 272 273 274
    // scroll active tab into view
    scrollIntoView() {
      const { currentIndex, scrollable } = this.data;
      if (!scrollable) {
        return;
      }
      Promise.all([
李嘉林 committed
275 276
        getAllRect(this, ".van-tab"),
        getRect(this, ".van-tabs__nav")
程默 committed
277 278 279 280 281 282
      ]).then(([tabRects, navRect]) => {
        const tabRect = tabRects[currentIndex];
        const offsetLeft = tabRects
          .slice(0, currentIndex)
          .reduce((prev, curr) => prev + curr.width, 0);
        this.setData({
李嘉林 committed
283
          scrollLeft: offsetLeft - (navRect.width - tabRect.width) / 2
李嘉林 committed
284
        });
程默 committed
285 286 287
      });
    },
    onTouchScroll(event) {
李嘉林 committed
288
      this.$emit("scroll", event.detail);
程默 committed
289 290 291 292 293 294 295 296
    },
    onTouchStart(event) {
      if (!this.data.swipeable) return;
      this.touchStart(event);
    },
    onTouchMove(event) {
      if (!this.data.swipeable) return;
      this.touchMove(event);
李嘉林 committed
297
    },
程默 committed
298 299 300 301 302
    // watch swipe touch end
    onTouchEnd() {
      if (!this.data.swipeable) return;
      const { direction, deltaX, offsetX } = this;
      const minSwipeDistance = 50;
李嘉林 committed
303
      if (direction === "horizontal" && offsetX >= minSwipeDistance) {
程默 committed
304 305 306
        const index = this.getAvaiableTab(deltaX);
        if (index !== -1) {
          this.setCurrentIndex(index);
李嘉林 committed
307
        }
程默 committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
      }
    },
    getAvaiableTab(direction) {
      const { tabs, currentIndex } = this.data;
      const step = direction > 0 ? -1 : 1;
      for (
        let i = step;
        currentIndex + i < tabs.length && currentIndex + i >= 0;
        i += step
      ) {
        const index = currentIndex + i;
        if (
          index >= 0 &&
          index < tabs.length &&
          tabs[index] &&
          !tabs[index].disabled
        ) {
          return index;
        }
      }
      return -1;
李嘉林 committed
329 330
    }
  }
李嘉林 committed
331
});