Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

intersection-observer.js

105 lines2.5 KB

1// Packages
2import { Component, cloneElement, Children } from 'react';
3import { findDOMNode } from 'react-dom';
4import PropTypes from 'prop-types';
5​
6// Private Observer Manager functions and manager
7import { getObserver, observeTarget, unobserveTarget } from './manager';
8import { hasEqualOptions, isDOMNode } from './utils';
9​
10export default class Observer extends Component {
11 static propTypes = {
12 disabled: PropTypes.bool,
13 once: PropTypes.bool,
14 onIntersect: PropTypes.func.isRequired,
15 render: PropTypes.func,
16 root: PropTypes.element,
17 rootMargin: PropTypes.string,
18 threshold: PropTypes.oneOfType([
19 PropTypes.arrayOf(PropTypes.number),
20 PropTypes.number,
21 ]),
22 value: PropTypes.string,
23 };
24​
25 static defaultProps = {
26 disabled: false,
27 once: false,
28 };
29​
30 shouldReobserve = false;
31​
32 componentDidMount() {
33 this.observer = getObserver(getOptions(this.props));
34 this.observe();
35 }
36​
37 componentDidUpdate(prevProps) {
38 const nextOptions = getOptions(this.props);
39 if (!hasEqualOptions(this.observer, nextOptions)) {
40 this.unobserve();
41 this.observer = getObserver(nextOptions);
42 this.shouldReobserve = true;
43 }
44​
45 if (prevProps.disabled && !this.props.disabled) {
46 this.shouldReobserve = true;
47 }
48​
49 if (!prevProps.disabled && this.props.disabled) {
50 this.unobserve();
51 }
52​
53 if (this.shouldReobserve) {
54 this.observe();
55 this.shouldReobserve = false;
56 }
57 }
58​
59 componentWillUnmount() {
60 this.unobserve();
61 }
62​
63 handleTarget = (node) => {
64 // eslint-disable-next-line
65 const element = isDOMNode(node) ? node : findDOMNode(node);
66 if (this.target && this.target !== element) {
67 this.unobserve();
68 this.shouldReobserve = true;
69 }
70 this.target = element;
71 };
72​
73 observe() {
74 if (!this.props.disabled && this.target) {
75 observeTarget(this.observer, this.target, this.handleIntersect);
76 }
77 }
78​
79 unobserve() {
80 if (this.target) {
81 unobserveTarget(this.observer, this.target);
82 }
83 }
84​
85 handleIntersect = (entry) => {
86 this.props.onIntersect(entry, this.props.value);
87 if (this.props.once && entry.isIntersecting) {
88 this.unobserve();
89 }
90 };
91​
92 render() {
93 return this.props.render
94 ? this.props.render({ innerRef: this.handleTarget })
95 : cloneElement(Children.only(this.props.children), {
96 ref: this.handleTarget,
97 });
98 }
100​
101const getOptions = (props) => ({
102 root: props.root,
103 rootMargin: props.rootMargin,
104 threshold: props.threshold,
105});