refs #146 Add lazy loading to favourites

This commit is contained in:
AkiraFukushima 2018-03-27 18:09:13 +09:00
parent ef7bed8de2
commit b14f9d72a2
2 changed files with 56 additions and 2 deletions

View File

@ -3,6 +3,8 @@
<div class="fav" v-for="message in favourites" v-bind:key="message.id">
<toot :message="message" v-on:update="updateToot"></toot>
</div>
<div class="loading-card" v-loading="lazyLoading">
</div>
</div>
</template>
@ -16,7 +18,8 @@ export default {
computed: {
...mapState({
account: state => state.TimelineSpace.account,
favourites: state => state.TimelineSpace.Favourites.favourites
favourites: state => state.TimelineSpace.Favourites.favourites,
lazyLoading: state => state.TimelineSpace.Favourites.lazyLoading
})
},
created () {
@ -38,10 +41,32 @@ export default {
})
})
},
mounted () {
window.addEventListener('scroll', this.onScroll)
},
destroyed () {
window.removeEventListener('scroll', this.onScroll)
},
methods: {
updateToot (message) {
this.$store.commit('TimelineSpace/Favourites/updateToot', message)
},
onScroll (event) {
if (((document.documentElement.clientHeight + event.target.defaultView.scrollY) >= document.getElementById('favourites').clientHeight - 10) && !this.lazyloading) {
this.$store.dispatch('TimelineSpace/Favourites/lazyFetchFavourites', this.favourites[this.favourites.length - 1])
}
}
}
}
</script>
<style lang="scss" scoped>
.loading-card {
background-color: #ffffff;
height: 60px;
}
.loading-card:empty {
height: 0;
}
</style>

View File

@ -3,12 +3,16 @@ import Mastodon from 'mastodon-api'
const Favourites = {
namespaced: true,
state: {
favourites: []
favourites: [],
lazyLoading: false
},
mutations: {
updateFavourites (state, favourites) {
state.favourites = favourites
},
insertFavourites (state, favourites) {
state.favourites = state.favourites.concat(favourites)
},
updateToot (state, message) {
state.favourites = state.favourites.map((toot) => {
if (toot.id === message.id) {
@ -24,6 +28,9 @@ const Favourites = {
return toot
}
})
},
changeLazyLoading (state, value) {
state.lazyLoading = value
}
},
actions: {
@ -41,6 +48,28 @@ const Favourites = {
resolve(res)
})
})
},
lazyFetchFavourites ({ state, commit, rootState }, last) {
return new Promise((resolve, reject) => {
if (state.lazyLoading) {
return resolve()
}
commit('changeLazyLoading', true)
const client = new Mastodon(
{
access_token: rootState.TimelineSpace.account.accessToken,
api_url: rootState.TimelineSpace.account.baseURL + '/api/v1'
})
console.log(last.id)
// Note: Now this API's explanation and implementation are reversed.
// So if the bug has resolved, please use max_id instead of since_id.
// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#favourites
client.get('/favourites', { since_id: last.id, limit: 40 }, (err, data, res) => {
if (err) return reject(err)
commit('insertFavourites', data)
commit('changeLazyLoading', false)
})
})
}
}
}