Repository URL to install this package:
|
Version:
0.0.15 ▾
|
import * as React from 'react';
import { styled } from 'styleh-components';
import { createObserver, observeElement, unobserveElement, } from '@skava/react-dom-observable';
import { getContentRect } from '@skava/react-dom-observable/dist/measure/getContentRect';
// pad to see more effect
const Wrap = styled.div `
transition: background-color 2s ease-in-out;
height: 30rem;
padding: 5rem;
${(props) => props.isIntersecting === true &&
styled.css `
background-color: purple;
`}
img {
object-fit: cover;
max-height: 100%;
max-width: 100%;
width: 100%;
object-position: top;
}
`;
/**
* @todo @@perf only use the ones required
*/
const observerProps = ['disabled', 'root', 'rootMargin', 'threshold'];
const types = Object.freeze(['client', 'offset', 'scroll', 'bounds', 'margin']);
function fromTargetToContentRect(target) {
return getContentRect(target, types);
}
export default class ImageIntersectionObserver extends React.PureComponent {
constructor() {
super(...arguments);
this.wrapperRef = React.createRef();
this.state = {
isIntersecting: false,
height: 0,
width: 0,
};
this.handleChange = (event) => {
console.warn('CHANGE! ' + event.isIntersecting);
if (event.isIntersecting && !this.state.isIntersecting) {
this.measure();
this.setState({ isIntersecting: true });
}
};
this.measure = (entries) => {
console.log('___measure___');
const contentRect = fromTargetToContentRect(this.target);
this.setState(contentRect.bounds);
};
}
get target() {
return this.wrapperRef.current;
}
observe() {
this.observer = createObserver(observerProps);
observeElement(this);
}
unobserve() {
if (this.target !== undefined) {
unobserveElement(this);
}
}
componentDidMount() {
this.observe();
}
componentWillUnmount() {
this.unobserve();
}
render() {
// &h=${this.state.height}
const url = `https://raderain.sirv.com/rue21/Barbie/Barbie_HP_Banner_01.jpg?format=webp&w=${this.state.width}`;
return (React.createElement(Wrap, { ref: this.wrapperRef, isIntersecting: this.state.isIntersecting }, this.state.isIntersecting === true && React.createElement("img", { src: url })));
}
}
ImageIntersectionObserver.displayName = 'IntersectionObserver';
//# sourceMappingURL=ImageIntersectionObserver.js.map