Blame view

apps/components/layouts/recycle-scroll-reveal.vue 9.23 KB
yyq authored
1
<template>
yyq authored
2
  <div class="recycle-scroll-reveal">
陈峰 authored
3
    <div class="recycle-scroll-reveal-main" ref="scroll">
yyq authored
4 5 6
      <div ref="eternal" class="eternal-top">
        <slot name="eternalTop"></slot>
      </div>
yyq authored
7 8
      <div class="scroll-reveal-list-block">
        <div ref="scrollList" class="scroll-reveal-list" :style="{height: listHeight + 'px'}">
yyq authored
9
          <div
yyq authored
10 11 12 13 14 15 16 17 18 19 20 21 22 23
            v-for="(items, col) in visibleItems"
            :key="col"
            class="scroll-reveal-col"
            :ref="'col'+ col"
            :style="colStyle">
            <div
              v-for="item in items"
              :key="item.index"
              class="scroll-reveal-item"
              :ref="'items' + item.index"
              :style="getItemStyle(item)">
              <div v-if="!item.placeholder">
                <slot name="item" :data="item"></slot>
              </div>
yyq authored
24 25 26
            </div>
          </div>
        </div>
yyq authored
27 28 29 30
        <div class="loading">
          <p v-if="noMore" class="load-text">没有更多了</p>
          <Loading v-else :size="20"></Loading>
        </div>
yyq authored
31 32 33 34 35 36
      </div>
    </div>
  </div>
</template>

<script>
yyq authored
37
import {throttle, slice} from 'lodash';
yyq authored
38 39 40 41 42 43 44 45 46
import {Loading} from 'cube-ui';

const EVENT_SCROLL = 'scroll';

export default {
  name: 'RecycleScrollReveal',
  data() {
    let data = {
      colPrefix: 'sr_col',
yyq authored
47
      listHeight: 0,
yyq authored
48 49 50 51
      visibleItems: [],
      colsHeight: [],
      items: [],
      itemWidth: 0,
陈峰 authored
52 53
      noMore: false,
      startIndexs: [0, 0]
yyq authored
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    };

    for (let i = 0; i < this.cols; i++) {
      data[data.colPrefix + i] = [];
      data.visibleItems[i] = data[data.colPrefix + i];
      data.colsHeight[i] = 0;
    }

    return data;
  },
  props: {
    infinite: {
      type: Boolean,
      default: false
    },
    size: {
      type: Number,
      default: 20
    },
    offset: {
      type: Number,
      default: 100
    },
    onFetch: {
      type: Function,
      required: true
    },
    thumbs: {
      type: Array,
      default() {
        return [];
      }
    },
    cols: {
      type: Number,
      default: 2
yyq authored
90 91 92 93
    },
    manualInit: {
      type: Boolean,
      default: false
yyq authored
94 95 96 97 98 99 100 101 102 103 104 105 106
    }
  },
  computed: {
    colStyle() {
      return {
        width: `${100 / this.cols}%`
      };
    }
  },
  watch: {
    items(newList, oldList) {
      let list = newList.slice(oldList.length, newList.length);
yyq authored
107
      if (list.length) {
yyq authored
108
        this.revealCalcing = true;
yyq authored
109
        this.loadItems(list, oldList.length).then(() => {
yyq authored
110
          this.revealCalcing = false;
yyq authored
111 112
          this.updateListHeight();
yyq authored
113 114
          if (oldList.length < 2) {
            this._updateList();
yyq authored
115
            this.$emit('on-inited', this._getCurrentItems());
yyq authored
116 117 118
          }
        });
      }
yyq authored
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    }
  },
  mounted() {
    this.updateList = throttle(this._updateList.bind(this), 100);
    let supportsPassive = false;

    try {
      const opts = Object.defineProperty({}, 'passive', {
        get() {
          supportsPassive = true;
          return true;
        }
      });

      window.addEventListener('test', null, opts);
    } catch (e) {} //eslint-disable-line
    this.$el.addEventListener(EVENT_SCROLL, this.onScroll, supportsPassive ? { passive: true } : false);
yyq authored
137 138 139
    if (!this.manualInit) {
      this.init();
    }
yyq authored
140 141 142 143 144 145 146 147 148
  },
  beforeDestroy() {
    this.$el.removeEventListener(EVENT_SCROLL, this.onScroll);
  },
  methods: {
    init() {
      this.colsHeight = [];
      this.itemWidth = Math.floor(this.$el.offsetWidth / this.cols);
yyq authored
149 150 151
      this.load(true);
    },
    clear() {
yyq authored
152
      this.clearTimestamp = new Date().getTime();
yyq authored
153
      this.noMore = false;
yyq authored
154
      this.listHeight = 0;
yyq authored
155
yyq authored
156
      for (let i = 0; i < this.cols; i++) {
yyq authored
157
        this.visibleItems[i].length = 0;
yyq authored
158
        this.colsHeight[i] = 0;
yyq authored
159
        this.startIndexs[i] = 0;
yyq authored
160
      }
yyq authored
161 162

      this.items = [];
yyq authored
163 164
    },
    load(reload) {
yyq authored
165
      if (reload) {
yyq authored
166
        this.clear();
yyq authored
167 168
      }
yyq authored
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
      if (!reload && (this.loading || this.noMore)) {
        return;
      }

      this.loading = true;

      this.onFetch().then(res => {
        this.loading = false;

        if (!res) {
          this.noMore = true;
        } else {
          this.items = this.items.concat(res);
        }
      });
    },
    async loadItems(list, start = 0) {
      if (!list.length) {
        return;
      }

      let lastIndex = list.length;
yyq authored
191
yyq authored
192 193 194 195 196
      if (this.cols > 1) {
        lastIndex = Math.max.apply(null, [1, list.length - Math.floor(this.cols * 2)]);
      }

      let startCol = this.getMinHeightCol();
yyq authored
197
      const timestamp = this.clearTimestamp;
yyq authored
198 199 200 201 202 203 204 205

      for (let i = 0; i < list.length; i++) {
        await this.loadItem({
          data: list[i],
          index: i + start,
          width: this.itemWidth,
          isThumb: true,
          placeholder: false
yyq authored
206
        }, i < lastIndex ? (startCol + i) % this.cols : -1, timestamp);
yyq authored
207 208
      }
yyq authored
209 210 211
      this.$nextTick(() => {
        for (let i = 0; i < this.cols; i++) {
          let loop = true;
ityuany authored
212
yyq authored
213
          let col = this[this.colPrefix + i];
ityuany authored
214
yyq authored
215
          let k = col.length - 1;
yyq authored
216
yyq authored
217 218
          while (loop) {
            let cur = col[k];
yyq authored
219
yyq authored
220 221 222 223 224 225
            if (!cur || cur.height) {
              loop = false;
              continue;
            }

            let dom = this.$refs[`items${cur.index}`];
yyq authored
226
yyq authored
227 228 229 230 231 232
            try {
              if (dom && dom[0]) {
                cur.height = dom[0].offsetHeight;
                cur.top = dom[0].offsetTop;
              }
            } catch (error) {
yyq authored
233
              const message = `cur_${typeof cur}, dom_ ${typeof dom}, column_${i}, index_ ${k}, length_ ${this.items.length}, ${error ? error.message : ''}`;
yyq authored
234
yyq authored
235
              throw new Error(message);
yyq authored
236 237
            }
yyq authored
238 239
            this.$set(this[this.colPrefix + i], k, cur);
            k--;
yyq authored
240 241
          }
        }
yyq authored
242
yyq authored
243 244
        return true;
      });
yyq authored
245
    },
yyq authored
246
    loadItem(item, index, timestamp) {
yyq authored
247
      return new Promise(r => {
yyq authored
248 249 250 251
        if (timestamp !== this.clearTimestamp) {
          return r();
        }
yyq authored
252
        if (index < 0) {
yyq authored
253 254 255 256
          index = this.getMinHeightCol();
        }

        this[this.colPrefix + index].push(item);
yyq authored
257 258 259 260
        this.$nextTick(() => {
          r();
          this.colsHeight[index] = this.$refs['col' + index][0].offsetHeight;
        });
yyq authored
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
      });
    },
    getMinHeightCol() {
      return this.colsHeight.indexOf(Math.min.apply(null, this.colsHeight));
    },
    getItemStyle(item) {
      const style = {};

      if (item.height) {
        if (!item.unlockHight) {
          style.height = `${item.height}px`;
        }
      } else if (item.willchange) {
        style.transition = 'height 300ms cubic-bezier(0.165, 0.84, 0.44, 1)';
        style['will-change'] = 'height';
        style.height = `${item.height}px`;
        style.opacity = 0;
      } else if (!item.isThumb) {
        style.position = 'absolute';
        style.top = `${-1000}px`;
        style.visibility = 'hidden';
      }
      return style;
    },
    updateCurrentItems(scrollTop) {
      let top = scrollTop - this.$refs.eternal.offsetHeight;
ityuany authored
287
yyq authored
288 289 290
      let arr = [];

      for (let i = 0; i < this.cols; i++) {
陈峰 authored
291
        arr.push(this.updateColumnCurrentItems(i, top));
yyq authored
292 293
      }
    },
陈峰 authored
294
    updateColumnCurrentItems(index, top) {
yyq authored
295
      let col = this[this.colPrefix + index];
ityuany authored
296
陈峰 authored
297
      let startIndex = this.startIndexs[index];
ityuany authored
298
陈峰 authored
299
      let hasTopItem = false;
yyq authored
300
陈峰 authored
301
      for (let i = 0; i < col.length; i++) {
yyq authored
302
        if ((i < startIndex - this.size || i > startIndex + this.size) && col[i].height) {
陈峰 authored
303 304 305
          this.$set(col[i], 'placeholder', true);
        } else {
          this.$set(col[i], 'placeholder', false);
yyq authored
306
        }
yyq authored
307
陈峰 authored
308 309 310
        if (!hasTopItem && col[i].top > top) {
          startIndex = Math.max(0, i - 1);
          hasTopItem = true;
yyq authored
311 312
        }
      }
陈峰 authored
313
      this.startIndexs[index] = startIndex;
yyq authored
314
    },
yyq authored
315 316 317 318 319
    updateListHeight() {
      if (this.$refs.scrollList) {
        this.listHeight = this.$refs.scrollList.scrollHeight || 0;
      }
    },
yyq authored
320 321
    _updateList() {
      const scrollTop = this.$el.scrollTop;
陈峰 authored
322
      const heights = this.$refs.scroll.offsetHeight;
yyq authored
323 324

      // trigger load
yyq authored
325
      if (scrollTop + this.$el.offsetHeight > heights - this.offset && !this.revealCalcing) {
yyq authored
326 327 328 329 330
        this.load();
      }

      this.updateCurrentItems(scrollTop);
    },
yyq authored
331
    _getCurrentItems(scrollTop = 0) {
yyq authored
332 333 334 335 336 337 338 339 340 341 342 343 344 345
      let currents = [];

      if (scrollTop > (this.$refs.eternal.offsetHeight - document.body.clientHeight / 2)) {
        for (let i = 0; i < this.cols; i++) {
          let col = this[this.colPrefix + i];

          if (col && col.length) {
            let start = this.startIndexs[i] || 0;

            currents = currents.concat(slice(col, start, start + Math.round(this.size / 2)));
          }
        }
      }
yyq authored
346 347 348 349 350 351 352 353
      return currents;
    },
    onScroll() {
      const scrollTop = this.$el.scrollTop;

      this.updateList();

      this.$emit('scroll', {scrollTop, items: this._getCurrentItems(scrollTop)});
yyq authored
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    },
  },
  components: {
    Loading
  }
};
</script>

<style lang="scss" scoped>
.recycle-scroll-reveal {
  position: relative;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.recycle-scroll-reveal-main {
  min-height: 100%;
}

.scroll-reveal-list {
  display: flex;
  align-items: flex-start;
yyq authored
378 379
  overflow-y: hidden;
  box-sizing: border-box;
yyq authored
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

  .scroll-reveal-col {
    flex-grow: 1;
    position: relative;
  }
}

.loading {
  padding: 20px 0;
  text-align: center;

  /deep/ .cube-loading-spinners {
    margin: auto;
  }
}

</style>