Skip to content

Commit be73761

Browse files
committed
feat: add basic <ViewportScrollSensor> implementat
1 parent 3988734 commit be73761

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/ViewportScrollSensor/index.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import {Component} from 'react';
2+
import {h, on, off} from '../util';
3+
import * as throttle from 'throttle-debounce/throttle';
4+
5+
export const isInViewport = (el) => {
6+
const {top, left, bottom, right} = el.getBoundingClientRect();
7+
8+
return (
9+
top >= 0 &&
10+
left >= 0 &&
11+
bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
12+
right <= (window.innerWidth || document.documentElement.clientWidth)
13+
);
14+
}
15+
16+
export interface IViewportScrollSensorProps {
17+
throttle?: number;
18+
}
19+
20+
export interface IViewportScrollSensorState {
21+
visible: boolean;
22+
}
23+
24+
export class ViewportScrollSensor extends Component<IViewportScrollSensorProps, IViewportScrollSensorState> {
25+
static defaultProps = {
26+
throttle: 150
27+
};
28+
29+
el: HTMLElement;
30+
31+
state = {
32+
visible: false
33+
};
34+
35+
ref = (el) => {
36+
this.el = el;
37+
};
38+
39+
componentWillMount () {
40+
// TODO: TRY TO DETECT IF COMPONENT IS VISIBLE.
41+
}
42+
43+
componentDidMount () {
44+
on(document, 'scroll', this.onScroll);
45+
}
46+
47+
componentWillUnmount () {
48+
off(document, 'scroll', this.onScroll);
49+
}
50+
51+
onScroll = throttle(this.props.throttle, false, () => {
52+
this.setState({
53+
visible: isInViewport(this.el)
54+
});
55+
});
56+
57+
render () {
58+
const {children} = this.props;
59+
60+
return h('div', {},
61+
typeof children === 'function' ? children(this.state) : children
62+
);
63+
}
64+
}

0 commit comments

Comments
 (0)