1
0
Fork 0
mirror of synced 2024-10-02 01:56:57 +13:00

Tidy up logic for scrolling to components

This commit is contained in:
Andrew Kingston 2022-03-21 13:54:46 +00:00
parent 7c39430d1c
commit 2def829ebf

View file

@ -33,41 +33,40 @@
const sidebarWidth = 259 const sidebarWidth = 259
const navItemHeight = 32 const navItemHeight = 32
const { scrollLeft, scrollTop, offsetHeight } = scrollRef
let scrollBounds = scrollRef.getBoundingClientRect() let scrollBounds = scrollRef.getBoundingClientRect()
let newScrollOffsets = {} let newOffsets = {}
// Calculate left offset // Calculate left offset
const offsetX = bounds.left + bounds.width + scrollRef.scrollLeft + 20 const offsetX = bounds.left + bounds.width + scrollLeft + 20
if (offsetX > sidebarWidth) { if (offsetX > sidebarWidth) {
newScrollOffsets.left = offsetX - sidebarWidth newOffsets.left = offsetX - sidebarWidth
} else { } else {
newScrollOffsets.left = 0 newOffsets.left = 0
} }
if (newScrollOffsets.left === scrollRef.scrollLeft) { if (newOffsets.left === scrollLeft) {
delete newScrollOffsets.left delete newOffsets.left
} }
// Calculate top offset // Calculate top offset
const offsetY = bounds.top - scrollBounds?.top + scrollRef.scrollTop const offsetY = bounds.top - scrollBounds?.top + scrollTop
const upperOffset = 2 * navItemHeight - 8 if (offsetY > scrollTop + offsetHeight - 2 * navItemHeight) {
const lowerOffset = navItemHeight + 8 newOffsets.top = offsetY - offsetHeight + 2 * navItemHeight
if (offsetY > scrollRef.scrollTop + scrollRef.offsetHeight - upperOffset) { } else if (offsetY < scrollTop + navItemHeight) {
newScrollOffsets.top = offsetY - scrollRef.offsetHeight + upperOffset newOffsets.top = offsetY - navItemHeight
} else if (offsetY < scrollRef.scrollTop + lowerOffset) {
newScrollOffsets.top = offsetY - lowerOffset
} else { } else {
delete newScrollOffsets.top delete newOffsets.top
} }
// Skip if offset is unchanged // Skip if offset is unchanged
if (newScrollOffsets.left == null && newScrollOffsets.top == null) { if (newOffsets.left == null && newOffsets.top == null) {
return return
} }
// Smoothly scroll to the offset // Smoothly scroll to the offset
scrollRef.scroll({ scrollRef.scroll({
...newScrollOffsets, ...newOffsets,
behavior: "smooth", behavior: "smooth",
}) })
} }