refactor: re-use @vbelolapotkov's solution

If we make this a mixin, we can re-use the same solution for e.g. the
comment. If sb. notifies you, the browser automatically scrolls to the
comment in which you have been mentioned.
This commit is contained in:
roschaefer 2019-09-29 13:34:27 +02:00
parent b9c0749334
commit 57598df228
4 changed files with 36 additions and 30 deletions

View File

@ -79,8 +79,10 @@ import ContentMenu from '~/components/ContentMenu'
import ContentViewer from '~/components/Editor/ContentViewer'
import HcCommentForm from '~/components/CommentForm/CommentForm'
import CommentMutations from '~/graphql/CommentMutations'
import scrollToAnchor from '~/mixins/scrollToAnchor.js'
export default {
mixins: [scrollToAnchor],
data: function() {
return {
isCollapsed: true,

View File

@ -50,9 +50,6 @@ describe('CommentList.vue', () => {
},
},
},
$route: {
hash: '',
},
}
stubs = {
EditorContent: "<div class='stub'></div>",

View File

@ -32,8 +32,10 @@
<script>
import Comment from '~/components/Comment.vue'
import HcEmpty from '~/components/Empty.vue'
import scrollToAnchor from '~/mixins/scrollToAnchor.js'
export default {
mixins: [scrollToAnchor],
components: {
Comment,
HcEmpty,
@ -47,33 +49,6 @@ export default {
return comment.id === updatedComment.id ? updatedComment : comment
})
},
scrollCommentsIntoView() {
if (!window || !document) {
return
}
const container = document.getElementById('comments')
if (container) {
const top = container.offsetTop
window.scroll({
top,
left: 0,
behavior: 'smooth',
})
}
},
},
watch: {
$route(to, from) {
// scroll inside the same page
if (to.hash === '#comments') {
this.scrollCommentsIntoView()
}
},
},
mounted() {
if (this.$route.hash === '#comments') {
setTimeout(this.scrollCommentsIntoView, 250)
}
},
}
</script>

View File

@ -0,0 +1,32 @@
export function scrollToAnchor(anchor) {
if (!anchor) return
if (!window || !document) {
return
}
const container = document.querySelector(anchor)
if (container) {
const { top } = container.getBoundingClientRect()
setTimeout(() => {
// we have to set a small timeout to ensure this part comes after nuxt
// scrollBehaviour: https://nuxtjs.org/api/configuration-router/#scrollbehavior
window.scroll({
top,
left: 0,
behavior: 'smooth',
})
}, 250)
}
}
export default {
watch: {
$route(to, from) {
const anchor = to && to.hash
scrollToAnchor(anchor)
},
},
mounted() {
const anchor = this.$route && this.$route.hash
scrollToAnchor(anchor)
},
}