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