elk/plugins/remember-scroll-position.client.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-01-08 09:45:12 +01:00
import type { mastodon } from 'masto'
2023-01-07 16:27:09 +01:00
import { STORAGE_KEY_LAST_SCROLL_POSITION } from '~/constants'
2023-01-07 18:30:18 +01:00
interface RestoreScroll {
id: string
type: 'status' | 'follow'
position: number
2023-01-07 18:30:18 +01:00
}
2023-01-07 16:27:09 +01:00
export default defineNuxtPlugin(() => {
2023-01-07 18:30:18 +01:00
const lastStatus = useSessionStorage<Record<string, RestoreScroll>>(STORAGE_KEY_LAST_SCROLL_POSITION, {})
2023-01-07 16:27:09 +01:00
return {
provide: {
2023-01-07 18:30:18 +01:00
preventScrollToTop: (path: string) => {
return !!lastStatus.value[path]
},
2023-01-07 16:27:09 +01:00
restoreScrollPosition: () => {
2023-01-07 18:30:18 +01:00
const restore = lastStatus.value[useRoute().fullPath]
if (restore) {
const el = restore.type === 'status'
? document.getElementById(`status-${restore.id}`)
: document.querySelector(`a[href="${restore.id}"]`)
if (el) {
if (typeof restore.position === 'undefined')
el.scrollIntoView()
else
window.scrollTo(0, restore.position)
}
else {
2023-01-07 16:27:09 +01:00
delete lastStatus.value[useRoute().fullPath]
}
2023-01-07 16:27:09 +01:00
}
},
2023-01-07 18:30:18 +01:00
rememberAccountPosition: (account: string) => {
lastStatus.value[useRoute().fullPath] = { id: account, type: 'follow', position: window.scrollY }
2023-01-07 18:30:18 +01:00
},
2023-01-08 09:45:12 +01:00
rememberStatusPosition: (status: mastodon.v1.Status) => {
lastStatus.value[useRoute().fullPath] = { id: status.id, type: 'status', position: window.scrollY }
2023-01-07 16:27:09 +01:00
},
},
}
})