| 1 | /** @module SectionObserver */ |
| 2 | |
| 3 | /** |
| 4 | * @callback OnIntersection |
| 5 | * @param {HTMLElement} element The section that triggered the new intersection change. |
| 6 | */ |
| 7 | |
| 8 | /** |
| 9 | * @typedef {Object} SectionObserverProps |
| 10 | * @property {NodeList} elements A list of HTML elements to observe for |
| 11 | * intersection changes. This list can be updated through the `elements` setter. |
| 12 | * @property {OnIntersection} onIntersection Called when a new intersection is observed. |
| 13 | * @property {number} [topMargin] The number of pixels to shrink the top of |
| 14 | * the viewport's bounding box before calculating intersections. This is useful |
| 15 | * for sticky elements (e.g. sticky headers). Defaults to 0 pixels. |
| 16 | * @property {number} [throttleMs] The number of milliseconds that the scroll |
| 17 | * handler should be throttled. |
| 18 | */ |
| 19 | |
| 20 | /** |
| 21 | * @callback initSectionObserver |
| 22 | * @param {SectionObserverProps} props |
| 23 | * @return {SectionObserver} |
| 24 | */ |
| 25 | |
| 26 | /** |
| 27 | * Observe intersection changes with the viewport for one or more elements. This |
| 28 | * is intended to be used with the headings in the content so that the |
| 29 | * corresponding section(s) in the table of contents can be "activated" (e.g. |
| 30 | * bolded). |
| 31 | * |
| 32 | * When sectionObserver notices a new intersection change, the |
| 33 | * `props.onIntersection` callback will be fired with the corresponding section |
| 34 | * as a param. |
| 35 | * |
| 36 | * Because sectionObserver uses a scroll event listener (in combination with |
| 37 | * IntersectionObserver), the changes are throttled to a default maximum rate of |
| 38 | * 200ms so that the main thread is not excessively blocked. |
| 39 | * IntersectionObserver is used to asynchronously calculate the positions of the |
| 40 | * observed tags off the main thread and in a manner that does not cause |
| 41 | * expensive forced synchronous layouts. |
| 42 | * |
| 43 | * @param {SectionObserverProps} props |
| 44 | * @return {SectionObserver} |
| 45 | */ |
| 46 | module.exports = function sectionObserver( props ) { |
| 47 | props = Object.assign( { |
| 48 | topMargin: 0, |
| 49 | throttleMs: 200, |
| 50 | onIntersection: () => {} |
| 51 | }, props ); |
| 52 | |
| 53 | let /** @type {number | undefined} */ timeoutId; |
| 54 | let /** @type {HTMLElement | undefined} */ current; |
| 55 | |
| 56 | const observer = new IntersectionObserver( ( entries ) => { |
| 57 | let /** @type {IntersectionObserverEntry | undefined} */ closestNegativeEntry; |
| 58 | let /** @type {IntersectionObserverEntry | undefined} */ closestPositiveEntry; |
| 59 | const topMargin = /** @type {number} */ ( props.topMargin ); |
| 60 | |
| 61 | entries.forEach( ( entry ) => { |
| 62 | const top = |
| 63 | entry.boundingClientRect.top - topMargin; |
| 64 | if ( |
| 65 | top > 0 && |
| 66 | ( |
| 67 | closestPositiveEntry === undefined || |
| 68 | top < closestPositiveEntry.boundingClientRect.top - topMargin |
| 69 | ) |
| 70 | ) { |
| 71 | closestPositiveEntry = entry; |
| 72 | } |
| 73 | |
| 74 | if ( |
| 75 | top <= 0 && |
| 76 | ( |
| 77 | closestNegativeEntry === undefined || |
| 78 | top > closestNegativeEntry.boundingClientRect.top - topMargin |
| 79 | ) |
| 80 | ) { |
| 81 | closestNegativeEntry = entry; |
| 82 | } |
| 83 | } ); |
| 84 | |
| 85 | const closestTag = |
| 86 | /** @type {HTMLElement} */ ( closestNegativeEntry ? closestNegativeEntry.target : |
| 87 | /** @type {IntersectionObserverEntry} */ ( closestPositiveEntry ).target |
| 88 | ); |
| 89 | |
| 90 | // If the intersection is new, fire the `onIntersection` callback. |
| 91 | if ( current !== closestTag ) { |
| 92 | props.onIntersection( closestTag ); |
| 93 | } |
| 94 | current = closestTag; |
| 95 | |
| 96 | // When finished finding the intersecting element, stop observing all |
| 97 | // observed elements. The scroll event handler will be responsible for |
| 98 | // throttling and reobserving the elements again. Because we don't have a |
| 99 | // wrapper element around our content headings and their children, we can't |
| 100 | // rely on IntersectionObserver (which is optimized to detect intersecting |
| 101 | // elements *within* the viewport) to reliably fire this callback without |
| 102 | // this manual step. Instead, we offload the work of calculating the |
| 103 | // position of each element in an efficient manner to IntersectionObserver, |
| 104 | // but do not use it to detect when a new element has entered the viewport. |
| 105 | observer.disconnect(); |
| 106 | } ); |
| 107 | |
| 108 | /** |
| 109 | * Calculate the intersection of each observed element. |
| 110 | */ |
| 111 | function calcIntersection() { |
| 112 | // IntersectionObserver will asynchronously calculate the boundingClientRect |
| 113 | // of each observed element off the main thread after `observe` is called. |
| 114 | props.elements.forEach( ( element ) => { |
| 115 | if ( !element.parentNode ) { |
| 116 | mw.log.warn( 'Element being observed is not in DOM', element ); |
| 117 | return; |
| 118 | } |
| 119 | observer.observe( /** @type {HTMLElement} */ ( element ) ); |
| 120 | } ); |
| 121 | } |
| 122 | |
| 123 | function handleScroll() { |
| 124 | // Throttle the scroll event handler to fire at a rate limited by `props.throttleMs`. |
| 125 | if ( !timeoutId ) { |
| 126 | timeoutId = window.setTimeout( () => { |
| 127 | calcIntersection(); |
| 128 | timeoutId = undefined; |
| 129 | }, props.throttleMs ); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | function bindScrollListener() { |
| 134 | window.addEventListener( 'scroll', handleScroll ); |
| 135 | } |
| 136 | |
| 137 | function unbindScrollListener() { |
| 138 | window.removeEventListener( 'scroll', handleScroll ); |
| 139 | } |
| 140 | |
| 141 | /** |
| 142 | * Pauses intersection observation until `resume` is called. |
| 143 | */ |
| 144 | function pause() { |
| 145 | unbindScrollListener(); |
| 146 | clearTimeout( timeoutId ); |
| 147 | timeoutId = undefined; |
| 148 | // Assume current is no longer valid while paused. |
| 149 | current = undefined; |
| 150 | } |
| 151 | |
| 152 | /** |
| 153 | * Resumes intersection observation. |
| 154 | */ |
| 155 | function resume() { |
| 156 | bindScrollListener(); |
| 157 | } |
| 158 | |
| 159 | /** |
| 160 | * Cleans up event listeners and intersection observer. Should be called when |
| 161 | * the observer is permanently no longer needed. |
| 162 | */ |
| 163 | function unmount() { |
| 164 | unbindScrollListener(); |
| 165 | observer.disconnect(); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Set a list of HTML elements to observe for intersection changes. |
| 170 | * |
| 171 | * @param {NodeList} list |
| 172 | */ |
| 173 | function setElements( list ) { |
| 174 | props.elements = list; |
| 175 | } |
| 176 | |
| 177 | bindScrollListener(); |
| 178 | |
| 179 | /** |
| 180 | * @typedef {Object} SectionObserver |
| 181 | * @property {calcIntersection} calcIntersection |
| 182 | * @property {pause} pause |
| 183 | * @property {resume} resume |
| 184 | * @property {unmount} unmount |
| 185 | * @property {setElements} setElements |
| 186 | */ |
| 187 | return { |
| 188 | calcIntersection, |
| 189 | pause, |
| 190 | resume, |
| 191 | unmount, |
| 192 | setElements |
| 193 | }; |
| 194 | }; |