refs #3301 Rewrite TimelineSpace/Contents/DirectMessages with composition API

This commit is contained in:
AkiraFukushima 2022-06-02 22:31:24 +09:00
parent ade7d4e25e
commit dbee470005
No known key found for this signature in database
GPG Key ID: B6E51BAC4DE1A957
6 changed files with 151 additions and 219 deletions

View File

@ -135,7 +135,6 @@ let state = (): DirectMessagesState => {
return { return {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [] timeline: []
} }
} }
@ -204,7 +203,6 @@ describe('Home', () => {
return { return {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [status1] timeline: [status1]
} }
} }

View File

@ -139,7 +139,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [status2, status1] timeline: [status2, status1]
} }
}) })
@ -154,7 +153,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [status2, rebloggedStatus] timeline: [status2, rebloggedStatus]
} }
}) })
@ -172,7 +170,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [status2, status1] timeline: [status2, status1]
} }
}) })
@ -187,7 +184,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
scrolling: false,
timeline: [rebloggedStatus, status2, status1] timeline: [rebloggedStatus, status2, status1]
} }
}) })
@ -204,7 +200,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: false, heading: false,
scrolling: false,
timeline: [status2, status1] timeline: [status2, status1]
} }
}) })
@ -219,7 +214,6 @@ describe('TimelineSpace/Contents/DirectMessages', () => {
state = { state = {
lazyLoading: false, lazyLoading: false,
heading: false, heading: false,
scrolling: false,
timeline: [rebloggedStatus, status2, status1] timeline: [rebloggedStatus, status2, status1]
} }
}) })

View File

@ -15,7 +15,6 @@
@focusPrev="focusPrev" @focusPrev="focusPrev"
@focusRight="focusSidebar" @focusRight="focusSidebar"
@selectToot="focusToot(item)" @selectToot="focusToot(item)"
@sizeChanged="sizeChanged"
> >
</toot> </toot>
</DynamicScrollerItem> </DynamicScrollerItem>
@ -29,240 +28,174 @@
</div> </div>
</template> </template>
<script> <script lang="ts">
import { mapState, mapGetters } from 'vuex' import { defineComponent, ref, computed, onMounted, onBeforeUpdate, onBeforeUnmount, onUnmounted, watch } from 'vue'
import moment from 'moment' import { useStore } from '@/store'
import Toot from '~/src/renderer/components/organisms/Toot' import { useI18next } from 'vue3-i18next'
import { EventEmitter } from '~/src/renderer/components/event' import { useRoute } from 'vue-router'
import { ScrollPosition } from '~/src/renderer/components/utils/scroll' import { ElMessage } from 'element-plus'
import { Entity } from 'megalodon'
import useReloadable from '@/components/utils/reloadable'
import Toot from '@/components/organisms/Toot.vue'
import { EventEmitter } from '@/components/event'
import { ACTION_TYPES, MUTATION_TYPES } from '@/store/TimelineSpace/Contents/DirectMessages'
import { MUTATION_TYPES as SIDE_MENU_MUTATION } from '@/store/TimelineSpace/SideMenu'
import { MUTATION_TYPES as TIMELINE_MUTATION, ACTION_TYPES as TIMELINE_ACTION } from '@/store/TimelineSpace'
import { MUTATION_TYPES as HEADER_MUTATION } from '@/store/TimelineSpace/HeaderMenu'
import { ACTION_TYPES as CONTENTS_ACTION } from '@/store/TimelineSpace/Contents'
export default { export default defineComponent({
data() {
return {
focusedId: null,
scrollPosition: null,
observer: null,
scrollTime: null,
resizeTime: null
}
},
name: 'directmessages', name: 'directmessages',
components: { Toot }, components: { Toot },
computed: { setup() {
...mapState('TimelineSpace/Contents/DirectMessages', { const space = 'TimelineSpace/Contents/DirectMessages'
timeline: state => state.timeline, const store = useStore()
lazyLoading: state => state.lazyLoading, const route = useRoute()
heading: state => state.heading, const i18n = useI18next()
scrolling: state => state.scrolling const { reloadable } = useReloadable(store, route, i18n)
}),
...mapState({
openSideBar: state => state.TimelineSpace.Contents.SideBar.openSideBar,
backgroundColor: state => state.App.theme.background_color,
startReload: state => state.TimelineSpace.HeaderMenu.reload,
unreadNotification: state => state.TimelineSpace.timelineSetting.unreadNotification
}),
...mapGetters('TimelineSpace/Modals', ['modalOpened']),
shortcutEnabled: function () {
if (this.modalOpened) {
return false
}
if (!this.focusedId) {
return true
}
// Sometimes toots are deleted, so perhaps focused toot don't exist.
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id)
return currentIndex === -1
}
},
async mounted() {
this.$store.commit('TimelineSpace/SideMenu/changeUnreadDirectMessagesTimeline', false)
document.getElementById('scroller').addEventListener('scroll', this.onScroll)
if (!this.unreadNotification.direct) {
this.$store.commit('TimelineSpace/Contents/changeLoading', true)
await this.initialize().finally(_ => {
this.$store.commit('TimelineSpace/Contents/changeLoading', false)
})
}
EventEmitter.on('focus-timeline', () => { const focusedId = ref<string | null>(null)
// If focusedId does not change, we have to refresh focusedId because Toot component watch change events. const scroller = ref<any>()
const previousFocusedId = this.focusedId
this.focusedId = 0
this.$nextTick(function () {
this.focusedId = previousFocusedId
})
})
const el = document.getElementById('scroller')
this.scrollPosition = new ScrollPosition(el)
this.scrollPosition.prepare()
this.observer = new ResizeObserver(() => { const timeline = computed(() => store.state.TimelineSpace.Contents.DirectMessages.timeline)
if (this.scrollPosition && !this.heading && !this.lazyLoading && !this.scrolling) { const lazyLoading = computed(() => store.state.TimelineSpace.Contents.DirectMessages.lazyLoading)
this.resizeTime = moment() const heading = computed(() => store.state.TimelineSpace.Contents.DirectMessages.heading)
this.scrollPosition.restore() const openSideBar = computed(() => store.state.TimelineSpace.Contents.SideBar.openSideBar)
} const startReload = computed(() => store.state.TimelineSpace.HeaderMenu.reload)
}) const unreadNotification = computed(() => store.state.TimelineSpace.timelineSetting.unreadNotification)
const modalOpened = computed(() => store.getters[`TimelineSpace/Modals/modalOpened`])
const currentFocusedIndex = computed(() => timeline.value.findIndex(toot => focusedId.value === toot.uri + toot.id))
const scrollWrapper = el.getElementsByClassName('vue-recycle-scroller__item-wrapper')[0] onMounted(async () => {
this.observer.observe(scrollWrapper) store.commit(`TimelineSpace/SideMenu/${SIDE_MENU_MUTATION.CHANGE_UNREAD_HOME_TIMELINE}`, false)
}, document.getElementById('scroller')?.addEventListener('scroll', onScroll)
beforeUpdate() { if (!unreadNotification.value.direct) {
if (this.$store.state.TimelineSpace.SideMenu.unreadDirectMessagesTimeline && this.heading) { store.commit(`TimelineSpace/Contents/${CONTENTS_ACTION.CHANGE_LOADING}`, true)
this.$store.commit('TimelineSpace/SideMenu/changeUnreadDirectMessagesTimeline', false) await initialize().finally(() => {
} store.commit(`TimelineSpace/Contents/${CONTENTS_ACTION.CHANGE_LOADING}`, false)
if (this.scrollPosition) {
this.scrollPosition.prepare()
}
},
beforeUnmount() {
if (!this.unreadNotification.direct) {
this.$store.dispatch('TimelineSpace/stopDirectMessagesStreaming')
this.$store.dispatch('TimelineSpace/unbindDirectMessagesStreaming')
}
EventEmitter.off('focus-timeline')
this.observer.disconnect()
},
unmounted() {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeHeading', true)
this.$store.commit('TimelineSpace/Contents/DirectMessages/archiveTimeline')
if (!this.unreadNotification.direct) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/clearTimeline')
}
if (document.getElementById('scroller') !== undefined && document.getElementById('scroller') !== null) {
document.getElementById('scroller').removeEventListener('scroll', this.onScroll)
document.getElementById('scroller').scrollTop = 0
}
},
watch: {
startReload: function (newState, oldState) {
if (!oldState && newState) {
this.reload().finally(() => {
this.$store.commit('TimelineSpace/HeaderMenu/changeReload', false)
}) })
} }
}, })
focusedId: function (newState, _oldState) { onBeforeUpdate(() => {
if (newState && this.heading) { if (store.state.TimelineSpace.SideMenu.unreadDirectMessagesTimeline && heading.value) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeHeading', false) store.commit(`TimelineSpace/SideMenu/${SIDE_MENU_MUTATION.CHANGE_UNREAD_DIRECT_MESSAGES_TIMELINE}`, false)
} else if (newState === null && !this.heading) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeHeading', true)
} }
} })
}, onBeforeUnmount(() => {
methods: { if (!unreadNotification.value.direct) {
async initialize() { store.dispatch(`TimelineSpace/${TIMELINE_ACTION.STOP_DIRECT_MESSAGES_STREAMING}`)
await this.$store.dispatch('TimelineSpace/Contents/DirectMessages/fetchTimeline').catch(_ => { store.dispatch(`TimelineSpace/${TIMELINE_ACTION.UNBIND_DIRECT_MESSAGES_STREAMING}`)
this.$message({ }
message: this.$t('message.timeline_fetch_error'), })
onUnmounted(() => {
store.commit(`${space}/${MUTATION_TYPES.CHANGE_HEADING}`, true)
store.commit(`${space}/${MUTATION_TYPES.ARCHIVE_TIMELINE}`)
if (!unreadNotification.value.direct) {
store.commit(`${space}/${MUTATION_TYPES.CLEAR_TIMELINE}`)
}
})
watch(startReload, (newVal, oldVal) => {
if (!oldVal && newVal) {
reload().finally(() => {
store.commit(`TimelineSpace/HeaderMenu/${HEADER_MUTATION.CHANGE_RELOAD}`, false)
})
}
})
const initialize = async () => {
await store.dispatch(`${space}/${ACTION_TYPES.FETCH_TIMELINE}`).catch(_ => {
ElMessage({
message: i18n.t('message.timeline_fetch_error'),
type: 'error' type: 'error'
}) })
}) })
await this.$store.dispatch('TimelineSpace/bindDirectMessagesStreaming') await store.dispatch(`TimelineSpace/${TIMELINE_ACTION.BIND_DIRECT_MESSAGES_STREAMING}`)
this.$store.dispatch('TimelineSpace/startDirectMessagesStreaming') store.dispatch(`TimelineSpace/${TIMELINE_ACTION.START_DIRECT_MESSAGES_STREAMING}`)
}, }
onScroll(event) { const onScroll = (event: Event) => {
if (moment().diff(this.resizeTime) < 500) {
return
}
this.scrollTime = moment()
if (!this.scrolling) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', true)
}
// for lazyLoading // for lazyLoading
if ( if (
event.target.clientHeight + event.target.scrollTop >= document.getElementById('scroller').scrollHeight - 10 && (event.target as HTMLElement)!.clientHeight + (event.target as HTMLElement)!.scrollTop >=
!this.lazyloading document.getElementById('scroller')!.scrollHeight - 10 &&
!lazyLoading.value
) { ) {
this.$store store
.dispatch('TimelineSpace/Contents/DirectMessages/lazyFetchTimeline', this.timeline[this.timeline.length - 1]) .dispatch(`${space}/${ACTION_TYPES.LAZY_FETCH_TIMELINE}`, timeline.value[timeline.value.length - 1])
.then(statuses => { .then(statuses => {
if (statuses === null) { if (statuses === null) {
return return
} }
if (statuses.length > 0) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', true)
setTimeout(() => {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', false)
}, 500)
}
}) })
.catch(() => { .catch(() => {
this.$message({ ElMessage({
message: this.$t('message.timeline_fetch_error'), message: i18n.t('message.timeline_fetch_error'),
type: 'error' type: 'error'
}) })
}) })
} }
if (event.target.scrollTop > 10 && this.heading) { if ((event.target as HTMLElement)!.scrollTop > 10 && heading.value) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeHeading', false) store.commit(`${space}/${MUTATION_TYPES.CHANGE_HEADING}`, false)
} else if (event.target.scrollTop <= 10 && !this.heading) { } else if ((event.target as HTMLElement)!.scrollTop <= 10 && !heading.value) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeHeading', true) store.commit(`${space}/${MUTATION_TYPES.CHANGE_HEADING}`, true)
} }
}
setTimeout(() => { const updateToot = (message: Entity.Status) => {
const now = moment() store.commit(`${space}/${MUTATION_TYPES.UPDATE_TOOT}`, message)
if (now.diff(this.scrollTime) >= 150) { }
this.scrollTime = null const deleteToot = (message: Entity.Status) => {
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', false) store.commit(`${space}/${MUTATION_TYPES.DELETE_TOOT}`, message.id)
} }
}, 150) const reload = async () => {
}, store.commit(`TimelineSpace/${TIMELINE_MUTATION.CHANGE_LOADING}`, true)
updateToot(message) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/updateToot', message)
},
deleteToot(message) {
this.$store.commit('TimelineSpace/Contents/DirectMessages/deleteToot', message.id)
},
async reload() {
this.$store.commit('TimelineSpace/changeLoading', true)
try { try {
reloadable()
} finally { } finally {
this.$store.commit('TimelineSpace/changeLoading', false) store.commit(`TimelineSpace/${TIMELINE_MUTATION.CHANGE_LOADING}`, false)
} }
}, }
upper() { const upper = () => {
this.$refs.scroller.scrollToItem(0) scroller.value.scrollToItem(0)
this.focusedId = null focusedId.value = null
}, }
focusNext() { const focusNext = () => {
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id) if (currentFocusedIndex.value === -1) {
if (currentIndex === -1) { focusedId.value = timeline.value[0].uri + timeline.value[0].id
this.focusedId = this.timeline[0].uri + this.timeline[0].id } else if (currentFocusedIndex.value < timeline.value.length) {
} else if (currentIndex < this.timeline.length) { focusedId.value = timeline.value[currentFocusedIndex.value + 1].uri + timeline.value[currentFocusedIndex.value + 1].id
this.focusedId = this.timeline[currentIndex + 1].uri + this.timeline[currentIndex + 1].id
} }
}, }
focusPrev() { const focusPrev = () => {
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id) if (currentFocusedIndex.value === 0) {
if (currentIndex === 0) { focusedId.value = null
this.focusedId = null } else if (currentFocusedIndex.value > 0) {
} else if (currentIndex > 0) { focusedId.value = timeline.value[currentFocusedIndex.value - 1].uri + timeline.value[currentFocusedIndex.value - 1].id
this.focusedId = this.timeline[currentIndex - 1].uri + this.timeline[currentIndex - 1].id
} }
}, }
focusToot(message) { const focusToot = (message: Entity.Status) => {
this.focusedId = message.uri + message.id focusedId.value = message.uri + message.id
}, }
focusSidebar() { const focusSidebar = () => {
EventEmitter.emit('focus-sidebar') EventEmitter.emit('focus-sidebar')
}, }
handleKey(event) {
switch (event.srcKey) { return {
case 'next': timeline,
this.focusedId = this.timeline[0].uri + this.timeline[0].id scroller,
break focusedId,
} modalOpened,
}, updateToot,
sizeChanged() { deleteToot,
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', true) focusNext,
setTimeout(() => { focusPrev,
this.$store.commit('TimelineSpace/Contents/DirectMessages/changeScrolling', false) focusSidebar,
}, 500) focusToot,
openSideBar,
heading,
upper
} }
} }
} })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -252,6 +252,7 @@ export default defineComponent({
return { return {
mentions, mentions,
scroller,
loadingMore, loadingMore,
fetchMentionsSince, fetchMentionsSince,
focusedId, focusedId,

View File

@ -50,8 +50,12 @@ const mutations: MutationTree<ContentsState> = {
} }
} }
export const ACTION_TYPES = {
CHANGE_LOADING: 'changeLoading'
}
const actions: ActionTree<ContentsState, RootState> = { const actions: ActionTree<ContentsState, RootState> = {
changeLoading: ({ commit }, loading) => { [ACTION_TYPES.CHANGE_LOADING]: ({ commit }, loading) => {
commit(MUTATION_TYPES.CHANGE_LOADING, loading) commit(MUTATION_TYPES.CHANGE_LOADING, loading)
} }
} }

View File

@ -6,14 +6,12 @@ export type DirectMessagesState = {
lazyLoading: boolean lazyLoading: boolean
heading: boolean heading: boolean
timeline: Array<Entity.Status> timeline: Array<Entity.Status>
scrolling: boolean
} }
const state = (): DirectMessagesState => ({ const state = (): DirectMessagesState => ({
lazyLoading: false, lazyLoading: false,
heading: true, heading: true,
timeline: [], timeline: []
scrolling: false
}) })
export const MUTATION_TYPES = { export const MUTATION_TYPES = {
@ -25,8 +23,7 @@ export const MUTATION_TYPES = {
ARCHIVE_TIMELINE: 'archiveTimeline', ARCHIVE_TIMELINE: 'archiveTimeline',
CLEAR_TIMELINE: 'clearTimeline', CLEAR_TIMELINE: 'clearTimeline',
UPDATE_TOOT: 'updateToot', UPDATE_TOOT: 'updateToot',
DELETE_TOOT: 'deleteToot', DELETE_TOOT: 'deleteToot'
CHANGE_SCROLLING: 'changeScrolling'
} }
const mutations: MutationTree<DirectMessagesState> = { const mutations: MutationTree<DirectMessagesState> = {
@ -79,14 +76,16 @@ const mutations: MutationTree<DirectMessagesState> = {
return toot.id !== id return toot.id !== id
} }
}) })
},
[MUTATION_TYPES.CHANGE_SCROLLING]: (state, value: boolean) => {
state.scrolling = value
} }
} }
export const ACTION_TYPES = {
FETCH_TIMELINE: 'fetchTimeline',
LAZY_FETCH_TIMELINE: 'lazyFetchTimeline'
}
const actions: ActionTree<DirectMessagesState, RootState> = { const actions: ActionTree<DirectMessagesState, RootState> = {
fetchTimeline: async ({ dispatch, commit, rootState }): Promise<Array<Entity.Status>> => { [ACTION_TYPES.FETCH_TIMELINE]: async ({ dispatch, commit, rootState }): Promise<Array<Entity.Status>> => {
const client = generator( const client = generator(
rootState.TimelineSpace.sns, rootState.TimelineSpace.sns,
rootState.TimelineSpace.account.baseURL, rootState.TimelineSpace.account.baseURL,
@ -104,7 +103,10 @@ const actions: ActionTree<DirectMessagesState, RootState> = {
return [] return []
} }
}, },
lazyFetchTimeline: ({ state, commit, rootState }, lastStatus: Entity.Status): Promise<Array<Entity.Status> | null> => { [ACTION_TYPES.LAZY_FETCH_TIMELINE]: async (
{ state, commit, rootState },
lastStatus: Entity.Status
): Promise<Array<Entity.Status> | null> => {
if (state.lazyLoading) { if (state.lazyLoading) {
return Promise.resolve(null) return Promise.resolve(null)
} }