Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | 31x 31x 31x 31x 31x 31x 6x 31x 31x 31x 31x 31x 2x 2x 2x 2x 31x 31x 31x | import {Defer} from '../func/defer';
export interface ElementVisibilityObject {
observer: IntersectionObserver | null;
dispose: Function;
state: Function;
readyPromise: Promise<void>;
}
/**
* A composition around the IntersectionObserver API.
* Support is fairly good but if you want legacy browsers, look into polyfills.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
*/
export class elementVisibility {
/**
* Uses the interaction API to detect element visibility.
* @param {Element} el The element to observe
* @param {Object?} options Interaction api options.
* This includes, root, threshold and rootMargin.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
* @param {Function} callback A callback function that is called on each change.
* The callback returns the element, changes, done. Done is called to stop
* observiing.
* @return {Object} The intersection observer.
*
* Basic usage:
*
*
* ```ts
*
* let ev = elementVisibility.inview(element);
*
* // EV takes a moment to boot up so promise provided.
* ev.readyPromise.then(())=> {
* console.log(ev.state().inview); // Is the elmeent inview.
* });
* ev.dispose();
*
* ```
*
*
* Basic usage with callback structure.
* ```ts
*
*
* elementVisibility.inview(element, { threshold: 0.3 },
* // Note that your callback will get immediately
* // called once to check visibility
* (element, changes, dispose)=> {
* if(changes.isIntersecting) {
* // The element is visibile.
*
* dispose(); // Dispose if you want.
* }
* }
* );
*
*
* ```
*
*
* Element visibility internally caches the last known changes so you
* can use that in your app.
*
* This is often an easier way to do things that use the callback.
*
*
* ```ts
* let ev = elementVisibility.inview(element);
*
* console.log(ev.state().inview); // Is the elmeent inview now?
*
* window.setTimeout(()=> {
* console.log(ev.state().inview); // Is it inview now after 3 seconds.
* }, 3000);
*
* window.addEventListener('scroll', () => {
* console.log(ev.state().inview); // Check to see it is in view.
* });
*
* ev.state().changes; // A list of all known last changes.
* Contains IntersectionObserverEntry list.
* ev.state().lastChange; // Just the last known IntersectionObserverEntry.
*
*
* ev.dispose(); // Remember to dispose.
*
* ```
*
*
* --> I want to check if my element is inview just once.
*
* ```ts
* let ev = elementVisibility.inview(element, {});
*
* // This could be falsy since ev takes a moment to boot up.
* ev.inview; // True or False.
*
* // Instead
* if(ev.state().ready) {
* ev.inview; // True or False.
* }
*
* // Or
* ev.readyPromise.then(()=> {
* ev.inview; // True or False.
* })
*
*
*
* ev.dipose(); // Dispose it.
* ```
*
* --> I want to run scroll events only when the element is inview.
* See [[DomWatcher]] for an example of this.
*
*
*/
static inview(
element: HTMLElement,
options: Object = {},
callback?: Function
): ElementVisibilityObject {
// Cache the last known state in the closure.
let cachedChanges: Array<IntersectionObserverEntry> | null = null;
let cachedLastChange: IntersectionObserverEntry | null = null;
let cachedInview: boolean | null = null;
let ready = false;
const readyPromise: Defer = new Defer();
/**
* Get the last known state values of inview.
*/
const state = () => {
return {
changes: cachedChanges,
lastChange: cachedLastChange,
inview: cachedInview,
ready: ready,
};
};
const onChange = (entries: Array<IntersectionObserverEntry>) => {
// Cache the values only if there was a change
// so that it maintains the last known change.
if (entries.length >= 1) {
cachedChanges = entries;
cachedLastChange = entries.slice(-1)[0];
cachedInview = cachedLastChange.isIntersecting;
ready = true;
readyPromise.resolve();
}
// Callback always passes the "current" entries even if there
// are none.
callback && callback(element, entries.slice(-1)[0], dispose);
};
/**
* If evBypass=true is the url parameter, we allow IntersectionObserver
* to be bypassed and we immediately return true for inview. This is
* useful for automated testing.
*/
let inviewBypassParam = window.location.search.split('evBypass=')[1];
inviewBypassParam = inviewBypassParam && inviewBypassParam.split('&')[0];
Iif (inviewBypassParam === 'true') {
window.setTimeout(() => {
callback &&
callback(
element,
{
isIntersecting: true,
isVisible: true,
},
() => {}
);
readyPromise.resolve();
});
return {
observer: null,
dispose: () => {},
state: () => {
return {
ready: true,
inview: true,
};
},
readyPromise: readyPromise.getPromise(),
};
}
const dispose = () => {
observer && observer.unobserve(element);
observer && observer.disconnect();
cachedChanges = [];
cachedLastChange = null;
};
const observer = new IntersectionObserver(
onChange as IntersectionObserverCallback,
options
);
observer.observe(element);
return {
observer: observer,
dispose: dispose,
/**
* A method you can call to acquire the last known inview state.
*/
state: state,
/**
* A promise that resolved when the observer is ready.
*/
readyPromise: readyPromise.getPromise(),
};
}
}
|