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

37 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-01-08 08:45:12 +00:00
import type { mastodon } from 'masto'
2023-01-07 15:27:09 +00:00
import { STORAGE_KEY_LAST_SCROLL_POSITION } from '~/constants'
2023-01-07 17:30:18 +00:00
interface RestoreScroll {
id: string
type: 'status' | 'follow'
}
2023-01-07 15:27:09 +00:00
export default defineNuxtPlugin(() => {
2023-01-07 17:30:18 +00:00
const lastStatus = useSessionStorage<Record<string, RestoreScroll>>(STORAGE_KEY_LAST_SCROLL_POSITION, {})
2023-01-07 15:27:09 +00:00
return {
provide: {
2023-01-07 17:30:18 +00:00
preventScrollToTop: (path: string) => {
return !!lastStatus.value[path]
},
2023-01-07 15:27:09 +00:00
restoreScrollPosition: () => {
2023-01-07 17:30:18 +00: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}"]`)
2023-01-07 15:27:09 +00:00
if (el)
nextTick().then(() => el?.scrollIntoView())
else
delete lastStatus.value[useRoute().fullPath]
}
},
2023-01-07 17:30:18 +00:00
rememberAccountPosition: (account: string) => {
lastStatus.value[useRoute().fullPath] = { id: account, type: 'follow' }
},
2023-01-08 08:45:12 +00:00
rememberStatusPosition: (status: mastodon.v1.Status) => {
2023-01-07 17:30:18 +00:00
lastStatus.value[useRoute().fullPath] = { id: status.id, type: 'status' }
2023-01-07 15:27:09 +00:00
},
},
}
})