1 export function checkSidebarItemVisibility(
2 item: HTMLElement,
3 withTransition = false,
4 topMargin = 0
5 ) {
6 return withTransition
7 ? checkSidebarItemVisibilityTransition(item, topMargin)
8 : checkSidebarItemVisibilityRelative(item, topMargin)
9 }
10
11 function checkSidebarItemVisibilityRelative(
12 item: HTMLElement,
13 topMargin: number
14 ) {
15 const sidebar = document.getElementById("sidebar")
16 if (!sidebar) {
17 return false
18 }
19 const sidebarBoundingRect = sidebar.getBoundingClientRect()
20 const sidebarTop = sidebarBoundingRect.top - topMargin
21 const sidebarBottom = sidebarTop + sidebarBoundingRect.height
22 const itemBoundingRect = item.getBoundingClientRect()
23 const itemTop =
24 item.offsetParent === sidebar ? item.offsetTop : itemBoundingRect.top
25 const itemBottom = itemTop + itemBoundingRect.height
26
27 return itemTop >= sidebarTop && itemBottom <= sidebarBottom
28 }
29
30 function checkSidebarItemVisibilityTransition(
31 item: HTMLElement,
32 topMargin: number
33 ) {
34 const sidebar = document.getElementById("sidebar")
35 if (!sidebar) {
36 return false
37 }
38
39 const sidebarBoundingRect = sidebar.getBoundingClientRect()
40 const activeItemBoundingRect = item.getBoundingClientRect()
41
42 return (
43 activeItemBoundingRect.top >= topMargin &&
44 activeItemBoundingRect.top - sidebarBoundingRect.height + topMargin < 0 &&
45 activeItemBoundingRect.bottom > 0
46 )
47 }