@@ -45,7 +45,7 @@ export function Events(Base) {
45
45
// =========================================================================
46
46
/**
47
47
* Initialize cover observer
48
- * Toggles sticky behavior when when cover is not in view
48
+ * Toggles sticky behavior when cover is not in view
49
49
* @void
50
50
*/
51
51
#initCover( ) {
@@ -74,11 +74,17 @@ export function Events(Base) {
74
74
#initHeadings( ) {
75
75
const headingElms = dom . findAll ( '#main :where(h1, h2, h3, h4, h5)' ) ;
76
76
const headingsInView = new Set ( ) ;
77
+ let isInitialLoad = true ;
77
78
78
79
// Mark sidebar active item on heading intersection
79
80
this . #intersectionObserver?. disconnect ( ) ;
80
81
this . #intersectionObserver = new IntersectionObserver (
81
82
entries => {
83
+ if ( isInitialLoad ) {
84
+ isInitialLoad = false ;
85
+ return ;
86
+ }
87
+
82
88
if ( this . #isScrolling) {
83
89
return ;
84
90
}
@@ -89,18 +95,16 @@ export function Events(Base) {
89
95
headingsInView [ op ] ( entry . target ) ;
90
96
}
91
97
92
- const activeHeading =
93
- headingsInView . size > 1
94
- ? // Sort headings by proximity to viewport top and select first
95
- Array . from ( headingsInView ) . sort ( ( a , b ) =>
96
- a . compareDocumentPosition ( b ) &
97
- Node . DOCUMENT_POSITION_FOLLOWING
98
- ? - 1
99
- : 1 ,
100
- ) [ 0 ]
101
- : // Get first and only item in set.
102
- // May be undefined if no headings are in view.
103
- headingsInView . values ( ) . next ( ) . value ;
98
+ let activeHeading = undefined ;
99
+ if ( headingsInView . size === 1 ) {
100
+ activeHeading = headingsInView . values ( ) . next ( ) . value ;
101
+ } else if ( headingsInView . size > 1 ) {
102
+ activeHeading = Array . from ( headingsInView ) . reduce ( ( closest , current ) => {
103
+ return ! closest || ( closest . compareDocumentPosition ( current ) & Node . DOCUMENT_POSITION_FOLLOWING )
104
+ ? current
105
+ : closest ;
106
+ } , null ) ;
107
+ }
104
108
105
109
if ( activeHeading ) {
106
110
const id = activeHeading . getAttribute ( 'id' ) ;
0 commit comments