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

This commit is contained in:
AkiraFukushima 2022-06-12 21:04:48 +09:00
parent b823b4631b
commit 232ac6f2ad
No known key found for this signature in database
GPG Key ID: B6E51BAC4DE1A957
2 changed files with 191 additions and 186 deletions

View File

@ -29,241 +29,238 @@
</div> </div>
</template> </template>
<script> <script lang="ts">
import { mapState, mapGetters } from 'vuex' import { computed, defineComponent, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, ref, watch } from 'vue'
import moment from 'moment' import moment from 'moment'
import Toot from '~/src/renderer/components/organisms/Toot' import { ElMessage } from 'element-plus'
import { EventEmitter } from '~/src/renderer/components/event' import { Entity } from 'megalodon'
import { ScrollPosition } from '~/src/renderer/components/utils/scroll' import { useI18next } from 'vue3-i18next'
import { useRoute } from 'vue-router'
import { useStore } from '@/store'
import Toot from '@/components/organisms/Toot.vue'
import { EventEmitter } from '@/components/event'
import { ScrollPosition } from '@/components/utils/scroll'
import useReloadable from '@/components/utils/reloadable'
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 { MUTATION_TYPES as CONTENTS_MUTATION } from '@/store/TimelineSpace/Contents'
import { ACTION_TYPES, MUTATION_TYPES } from '@/store/TimelineSpace/Contents/Public'
export default { export default defineComponent({
data() {
return {
focusedId: null,
scrollPosition: null,
observer: null,
scrollTime: null,
resizeTime: null
}
},
name: 'public', name: 'public',
components: { Toot }, components: { Toot },
computed: { setup() {
...mapState('TimelineSpace/Contents/Public', { const space = 'TimelineSpace/Contents/Public'
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({ const focusedId = ref<string | null>(null)
openSideBar: state => state.TimelineSpace.Contents.SideBar.openSideBar, const scrollPosition = ref<ScrollPosition | null>(null)
backgroundColor: state => state.App.theme.background_color, const observer = ref<ResizeObserver | null>(null)
startReload: state => state.TimelineSpace.HeaderMenu.reload, const scrollTime = ref<moment.Moment | null>(null)
unreadNotification: state => state.TimelineSpace.timelineSetting.unreadNotification const resizeTime = ref<moment.Moment | null>(null)
}), const scroller = ref<any>(null)
...mapGetters('TimelineSpace/Contents/Public', ['filters']),
...mapGetters('TimelineSpace/Modals', ['modalOpened']), const timeline = computed(() => store.state.TimelineSpace.Contents.Public.timeline)
shortcutEnabled: function () { const lazyLoading = computed(() => store.state.TimelineSpace.Contents.Public.lazyLoading)
if (this.modalOpened) { const heading = computed(() => store.state.TimelineSpace.Contents.Public.heading)
return false const scrolling = computed(() => store.state.TimelineSpace.Contents.Public.scrolling)
} const openSideBar = computed(() => store.state.TimelineSpace.Contents.SideBar.openSideBar)
if (!this.focusedId) { const startReload = computed(() => store.state.TimelineSpace.HeaderMenu.reload)
return true const unreadNotification = computed(() => store.state.TimelineSpace.timelineSetting.unreadNotification)
} const modalOpened = computed(() => store.getters[`TimelineSpace/Modals/modalOpened`])
// Sometimes toots are deleted, so perhaps focused toot don't exist. const filters = computed(() => store.getters[`${space}/filters`])
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id) const currentFocusedIndex = computed(() => timeline.value.findIndex(toot => focusedId.value === toot.uri + toot.id))
return currentIndex === -1
} onMounted(async () => {
}, store.commit(`TimelineSpace/SideMenu/${SIDE_MENU_MUTATION.CHANGE_UNREAD_PUBLIC_TIMELINE}`, false)
async mounted() { document.getElementById('scroller')?.addEventListener('scroll', onScroll)
this.$store.commit('TimelineSpace/SideMenu/changeUnreadPublicTimeline', false) if (!unreadNotification.value.public) {
document.getElementById('scroller').addEventListener('scroll', this.onScroll) store.commit(`TimelineSpace/Contents/${CONTENTS_MUTATION.CHANGE_LOADING}`, true)
if (!this.unreadNotification.public) { await initialize().finally(() => {
this.$store.commit('TimelineSpace/Contents/changeLoading', true) store.commit(`TimelineSpace/Contents/${CONTENTS_MUTATION.CHANGE_LOADING}`, false)
await this.initialize().finally(_ => {
this.$store.commit('TimelineSpace/Contents/changeLoading', false)
}) })
} }
EventEmitter.on('focus-timeline', () => {
// If focusedId does not change, we have to refresh focusedId because Toot component watch change events.
const previousFocusedId = this.focusedId
this.focusedId = 0
this.$nextTick(function () {
this.focusedId = previousFocusedId
})
})
const el = document.getElementById('scroller') const el = document.getElementById('scroller')
this.scrollPosition = new ScrollPosition(el) if (el) {
this.scrollPosition.prepare() scrollPosition.value = new ScrollPosition(el)
scrollPosition.value.prepare()
this.observer = new ResizeObserver(() => { observer.value = new ResizeObserver(() => {
if (this.scrollPosition && !this.heading && !this.lazyLoading && !this.scrolling) { if (scrollPosition.value && !heading.value && !lazyLoading.value && !scrolling.value) {
this.resizeTime = moment() resizeTime.value = moment()
this.scrollPosition.restore() scrollPosition.value.restore()
} }
}) })
const scrollWrapper = el.getElementsByClassName('vue-recycle-scroller__item-wrapper')[0] const scrollWrapper = el.getElementsByClassName('vue-recycle-scroller__item-wrapper')[0]
this.observer.observe(scrollWrapper) observer.value?.observe(scrollWrapper)
},
beforeUpdate() {
if (this.$store.state.TimelineSpace.SideMenu.unreadPublicTimeline && this.heading) {
this.$store.commit('TimelineSpace/SideMenu/changeUnreadPublicTimeline', false)
} }
if (this.scrollPosition) { })
this.scrollPosition.prepare() onBeforeUpdate(() => {
if (store.state.TimelineSpace.SideMenu.unreadPublicTimeline && heading.value) {
store.commit('TimelineSpace/SideMenu/changeUnreadPublicTimeline', false)
} }
}, if (scrollPosition.value) {
beforeUnmount() { scrollPosition.value.prepare()
if (!this.unreadNotification.public) { }
this.$store.dispatch('TimelineSpace/stopPublicStreaming') })
this.$store.dispatch('TimelineSpace/unbindPublicStreaming') onBeforeUnmount(() => {
if (!unreadNotification.value.public) {
store.dispatch(`TimelineSpace/${TIMELINE_ACTION.STOP_PUBLIC_STREAMING}`)
store.dispatch(`TimelineSpace/${TIMELINE_ACTION.UNBIND_PUBLIC_STREAMING}`)
} }
EventEmitter.off('focus-timeline') EventEmitter.off('focus-timeline')
this.observer.disconnect() observer.value?.disconnect()
}, })
unmounted() { onUnmounted(() => {
this.$store.commit('TimelineSpace/Contents/Public/changeHeading', true) store.commit(`${space}/${MUTATION_TYPES.CHANGE_HEADING}`, true)
this.$store.commit('TimelineSpace/Contents/Public/archiveTimeline') store.commit(`${space}/${MUTATION_TYPES.ARCHIVE_TIMELINE}`)
if (!this.unreadNotification.public) { if (!unreadNotification.value.public) {
this.$store.commit('TimelineSpace/Contents/Public/clearTimeline') store.commit(`${space}/${MUTATION_TYPES.CLEAR_TIMELINE}`)
} }
if (document.getElementById('scroller') !== undefined && document.getElementById('scroller') !== null) { const el = document.getElementById('scroller')
document.getElementById('scroller').removeEventListener('scroll', this.onScroll) if (el !== undefined && el !== null) {
document.getElementById('scroller').scrollTop = 0 el.removeEventListener('scroll', onScroll)
el.scrollTop = 0
} }
}, })
watch: { watch(startReload, (newVal, oldVal) => {
startReload: function (newState, oldState) { if (!oldVal && newVal) {
if (!oldState && newState) { reload().finally(() => {
this.reload().finally(() => { store.commit(`TimelineSpace/HeaderMenu/${HEADER_MUTATION.CHANGE_RELOAD}`, false)
this.$store.commit('TimelineSpace/HeaderMenu/changeReload', false)
}) })
} }
}, })
focusedId: function (newState, _oldState) {
if (newState && this.heading) { const initialize = async () => {
this.$store.commit('TimelineSpace/Contents/Public/changeHeading', false) await store.dispatch(`${space}/${ACTION_TYPES.FETCH_PUBLIC_TIMELINE}`).catch(_ => {
} else if (newState === null && !this.heading) { ElMessage({
this.$store.commit('TimelineSpace/Contents/Public/changeHeading', true) message: i18n.t('message.timeline_fetch_error'),
}
}
},
methods: {
async initialize() {
await this.$store.dispatch('TimelineSpace/Contents/Public/fetchPublicTimeline').catch(_ => {
this.$message({
message: this.$t('message.timeline_fetch_error'),
type: 'error' type: 'error'
}) })
}) })
await this.$store.dispatch('TimelineSpace/bindPublicStreaming') await store.dispatch(`TimelineSpace/${TIMELINE_ACTION.BIND_PUBLIC_STREAMING}`)
this.$store.dispatch('TimelineSpace/startPublicStreaming') store.dispatch(`TimelineSpace/${TIMELINE_ACTION.START_PUBLIC_STREAMING}`)
}, }
updateToot(message) { const onScroll = (event: Event) => {
this.$store.commit('TimelineSpace/Contents/Public/updateToot', message) if (moment().diff(resizeTime.value) < 500) {
},
deleteToot(message) {
this.$store.commit('TimelineSpace/Contents/Public/deleteToot', message.id)
},
onScroll(event) {
if (moment().diff(this.resizeTime) < 500) {
return return
} }
this.scrollTime = moment() scrollTime.value = moment()
if (!this.scrolling) { if (!scrolling.value) {
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', true) store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, true)
} }
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/Public/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) { if (statuses.length > 0) {
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', true) store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, true)
setTimeout(() => { setTimeout(() => {
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', false) store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, false)
}, 500) }, 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/Public/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/Public/changeHeading', true) store.commit(`${space}/${MUTATION_TYPES.CHANGE_HEADING}`, true)
} }
setTimeout(() => { setTimeout(() => {
const now = moment() const now = moment()
if (now.diff(this.scrollTime) >= 150) { if (now.diff(scrollTime.value) >= 150) {
this.scrollTime = null scrollTime.value = null
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', false) store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, false)
} }
}, 150) }, 150)
}, }
async reload() { const reload = async () => {
this.$store.commit('TimelineSpace/changeLoading', true) store.commit(`TimelineSpace/${TIMELINE_MUTATION.CHANGE_LOADING}`, true)
try { try {
await reloadable()
} finally { } finally {
this.$store.commit('TimelineSpace/changeLoading', false) store.commit(`TimelineSpace/${TIMELINE_MUTATION.CHANGE_LOADING}`, false)
} }
},
upper() {
this.$refs.scroller.scrollToItem(0)
this.focusedId = null
},
focusNext() {
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id)
if (currentIndex === -1) {
this.focusedId = this.timeline[0].uri + this.timeline[0].id
} else if (currentIndex < this.timeline.length) {
this.focusedId = this.timeline[currentIndex + 1].uri + this.timeline[currentIndex + 1].id
} }
}, const updateToot = (message: Entity.Status) => {
focusPrev() { store.commit(`${space}/${MUTATION_TYPES.UPDATE_TOOT}`, message)
const currentIndex = this.timeline.findIndex(toot => this.focusedId === toot.uri + toot.id)
if (currentIndex === 0) {
this.focusedId = null
} else if (currentIndex > 0) {
this.focusedId = this.timeline[currentIndex - 1].uri + this.timeline[currentIndex - 1].id
} }
}, const deleteToot = (message: Entity.Status) => {
focusToot(message) { store.commit(`${space}/${MUTATION_TYPES.DELETE_TOOT}`, message.id)
this.focusedId = message.uri + message.id }
}, const upper = () => {
focusSidebar() { scroller.value.scrollToItem(0)
focusedId.value = null
}
const focusNext = () => {
if (currentFocusedIndex.value === -1) {
focusedId.value = timeline.value[0].uri + timeline.value[0].id
} else if (currentFocusedIndex.value < timeline.value.length) {
focusedId.value = timeline.value[currentFocusedIndex.value + 1].uri + timeline.value[currentFocusedIndex.value + 1].id
}
}
const focusPrev = () => {
if (currentFocusedIndex.value === 0) {
focusedId.value = null
} else if (currentFocusedIndex.value > 0) {
focusedId.value = timeline.value[currentFocusedIndex.value - 1].uri + timeline.value[currentFocusedIndex.value - 1].id
}
}
const focusToot = (message: Entity.Status) => {
focusedId.value = message.uri + message.id
}
const focusSidebar = () => {
EventEmitter.emit('focus-sidebar') EventEmitter.emit('focus-sidebar')
},
handleKey(event) {
switch (event.srcKey) {
case 'next':
this.focusedId = this.timeline[0].uri + this.timeline[0].id
break
} }
}, const sizeChanged = () => {
sizeChanged() { store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, true)
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', true)
setTimeout(() => { setTimeout(() => {
this.$store.commit('TimelineSpace/Contents/Public/changeScrolling', false) store.commit(`${space}/${MUTATION_TYPES.CHANGE_SCROLLING}`, false)
}, 500) }, 500)
} }
return {
timeline,
scroller,
focusedId,
modalOpened,
filters,
updateToot,
deleteToot,
focusNext,
focusPrev,
focusSidebar,
focusToot,
sizeChanged,
openSideBar,
heading,
upper
} }
} }
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -84,8 +84,13 @@ const mutations: MutationTree<PublicState> = {
} }
} }
export const ACTION_TYPES = {
FETCH_PUBLIC_TIMELINE: 'fetchPublicTimeline',
LAZY_FETCH_TIMELINE: 'lazyFetchTimeline'
}
const actions: ActionTree<PublicState, RootState> = { const actions: ActionTree<PublicState, RootState> = {
fetchPublicTimeline: async ({ dispatch, commit, rootState }): Promise<Array<Entity.Status>> => { [ACTION_TYPES.FETCH_PUBLIC_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,
@ -102,7 +107,10 @@ const actions: ActionTree<PublicState, 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)
} }