Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improving offset and adding resize listener #69

Merged
merged 15 commits into from
Apr 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,16 @@ Props
- `onChange`: callback for whenever the element changes from being within the window viewport or not. Function is called with 1 argument `(isVisible: boolean)`
- `active`: (default `true`) boolean flag for enabling / disabling the sensor. When `active !== true` the sensor will not fire the `onChange` callback.
- `partialVisibility`: (default `false`) consider element visible if only part of it is visible. Also possible values are - 'top', 'right', 'bottom', 'left' - in case it's needed to detect when one of these become visible explicitly.
- `offset`: (default `{}`) with offset you can define amount of px from one side when the visibility should already change. So in example setting `offset={{direction: 'top', value:10}}` means that the visibility changes hidden when there is less than 10px to top of the viewport. Setting offset automatically disables the `partialVisibility`
- `offset`: (default `{}`) with offset you can define amount of px from one side when the visibility should already change. So in example setting `offset={{top:10}}` means that the visibility changes hidden when there is less than 10px to top of the viewport. Offset works along with `partialVisibility`
- `minTopValue`: (default `0`) consider element visible if only part of it is visible and a minimum amount of pixels could be set, so if at least 100px are in viewport, we mark element as visible.
- `intervalCheck`: (default `true`) the default usage of Visibility Sensor is to trigger a check on user scrolling, by checking this as true, it gives you the possibility to check if the element is in view even if it wasn't because of a user scroll
- `intervalDelay`: (default `1500`) integer, number of milliseconds between checking the element's position in relation the the window viewport. Making this number too low will have a negative impact on performance.
- `scrollCheck`: (default: `false`) by making this true, the scroll listener is enabled.
- `scrollDelay`: (default: `250`) is the debounce rate at which the check is triggered. Ex: 250ms after the user stopped scrolling.
- `scrollThrottle`: (default: `-1`) by specifying a value > -1, you are enabling throttle instead of the delay to trigger checks on scroll event. Throttle supercedes delay.
- `resizeCheck`: (default: `false`) by making this true, the resize listener is enabled. Resize listener only listens to the window.
- `resizeDelay`: (default: `250`) is the debounce rate at which the check is triggered. Ex: 250ms after the user stopped resizing.
- `resizeThrottle`: (default: `-1`) by specifying a value > -1, you are enabling throttle instead of the delay to trigger checks on resize event. Throttle supercedes delay.
- `containment`: (optional) element to use as a viewport when checking visibility. Default behaviour is to use the browser window as viewport.
- `delayedCall`: (default `false`) if is set to true, wont execute on page load ( prevents react apps triggering elements as visible before styles are loaded )

Expand All @@ -76,6 +80,7 @@ Special thanks to contributors:
- [@kompot](https://github.com/kompot)
- [@EugeneHlushko](https://github.com/EugeneHlushko)
- [@eek](http://github.com/eek)
- [@falcon1kr](http://github.com/falcon1kr)

License
----
Expand Down
2 changes: 1 addition & 1 deletion example/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var Example = React.createClass({
<div className='before'></div>
<VisibilitySensor
scrollCheck
scrollDelay={100}
scrollThrottle={100}
intervalDelay={8000}
containment={this.props.containment}
onChange={this.onChange}
Expand Down
35 changes: 0 additions & 35 deletions lib/is-visible-with-offset.js

This file was deleted.

20 changes: 11 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@
"react-dom": "^0.14.0 || ^15.0.0"
},
"devDependencies": {
"browserify": "^14.0.0",
"browserify-shim": "^3.8.13",
"es5-shim": "^4.5.9",
"gh-pages": "^0.12.0",
"karma": "^1.4.1",
"karma-chrome-launcher": "^2.0.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^3.2.0",
"browserify": "^5.11.2",
"browserify-shim": "^3.8.12",
"es5-shim": "^4.1.0",
"gh-pages": "^0.2.0",
"karma": "^0.12.31",
"karma-chrome-launcher": "^0.1.4",
"karma-mocha": "^0.1.9",
"karma-phantomjs-launcher": "^0.1.4",
"mocha": "^1.21.4",
"react": "^0.14.0 || ^15.0.0",
"react-dom": "^0.14.0 || ^15.0.0",
"reactify": "^1.1.1",
"uglifyjs": "^2.4.10"
},
Expand Down
13 changes: 7 additions & 6 deletions tests/visibility-sensor-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,21 +139,22 @@ describe('VisibilitySensor', function () {
var onChange = function () {};

var element1 = (
<VisibilitySensor active={true} onChange={onChange} scrollCheck />
<VisibilitySensor active={true} onChange={onChange} scrollCheck resizeCheck />
);

var element2 = (
<VisibilitySensor active={false} onChange={onChange} scrollCheck />
<VisibilitySensor active={false} onChange={onChange} scrollCheck resizeCheck />
);

var component1 = ReactDOM.render(element1, node);
assert(component1.interval, 'interval should be set');
assert(component1.debounceCheck, 'debounceCheck should be set');
assert(component1.debounceCheck.scroll, 'debounceCheck.scroll should be set');
assert(component1.debounceCheck.resize, 'debounceCheck.scroll should be set');

var component2 = ReactDOM.render(element2, node);
assert(!component2.interval, 'interval should not be set');
assert(!component2.debounceCheck, 'debounceCheck should not be set');

});

it('should work when using offset prop and moving to outside of offset area', function (done) {
Expand All @@ -171,7 +172,7 @@ describe('VisibilitySensor', function () {
}

var element = (
<VisibilitySensor onChange={onChange} offset={{direction: 'top', value:50}} intervalDelay={10} />
<VisibilitySensor onChange={onChange} offset={{top:50}} intervalDelay={10} />
);

ReactDOM.render(element, node);
Expand All @@ -192,7 +193,7 @@ describe('VisibilitySensor', function () {
}

var element = (
<VisibilitySensor onChange={onChange} offset={{direction: 'top', value:50}} intervalDelay={10} />
<VisibilitySensor onChange={onChange} offset={{top:50}} intervalDelay={10} />
);

ReactDOM.render(element, node);
Expand All @@ -213,7 +214,7 @@ describe('VisibilitySensor', function () {
}

var element = (
<VisibilitySensor onChange={onChange} offset={{direction: 'top', value:-50}} intervalDelay={10} />
<VisibilitySensor onChange={onChange} offset={{top:-50}} intervalDelay={10} />
);

ReactDOM.render(element, node);
Expand Down
129 changes: 110 additions & 19 deletions visibility-sensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@

var React = require('react');
var ReactDOM = require('react-dom');
var isVisibleWithOffset = require('./lib/is-visible-with-offset')

var containmentPropType = React.PropTypes.any;

if (typeof window !== 'undefined') {
containmentPropType = React.PropTypes.instanceOf(window.Element);
}

function throttle (callback, limit) {
var wait = false;
return function () {
if (!wait) {
wait = true;
setTimeout(function () {
callback();
wait = false;
}, limit);
}
}
}

function debounce(func, wait) {
var timeout;
return function() {
Expand Down Expand Up @@ -40,11 +52,15 @@ module.exports = React.createClass({
}),
scrollCheck: React.PropTypes.bool,
scrollDelay: React.PropTypes.number,
scrollThrottle: React.PropTypes.number,
resizeCheck: React.PropTypes.bool,
resizeDelay: React.PropTypes.number,
resizeThrottle: React.PropTypes.number,
intervalCheck: React.PropTypes.bool,
intervalDelay: React.PropTypes.number,
containment: containmentPropType,
children: React.PropTypes.element,
minTopValue: React.PropTypes.number
minTopValue: React.PropTypes.number,
},

getDefaultProps: function () {
Expand All @@ -54,8 +70,12 @@ module.exports = React.createClass({
minTopValue: 0,
scrollCheck: false,
scrollDelay: 250,
scrollThrottle: -1,
resizeCheck: false,
resizeDelay: 250,
resizeThrottle: -1,
intervalCheck: true,
intervalDelay: 1500,
intervalDelay: 100,
delayedCall: false,
offset: {},
containment: null,
Expand All @@ -71,6 +91,7 @@ module.exports = React.createClass({
},

componentDidMount: function () {
this.node = ReactDOM.findDOMNode(this);
if (this.props.active) {
this.startWatching();
}
Expand All @@ -93,6 +114,44 @@ module.exports = React.createClass({
return this.props.containment || window;
},

addEventListener: function (target, event, delay, throttle) {
if (!this.debounceCheck) {
this.debounceCheck = {};
}

var timeout;
var func;

var later = function () {
timeout = null;
this.check();
}.bind(this);

if (throttle > -1) {
func = function () {
if (!timeout) {
timeout = setTimeout(later, throttle || 0);
}
};
} else {
func = function () {
clearTimeout(timeout);
timeout = setTimeout(later, delay || 0);
};
}

var info = {
target: target,
fn: func,
getLastTimeout: function () {
return timeout;
},
};

target.addEventListener(event, info.fn);
this.debounceCheck[event] = info;
},

startWatching: function () {
if (this.debounceCheck || this.interval) { return; }

Expand All @@ -101,8 +160,21 @@ module.exports = React.createClass({
}

if (this.props.scrollCheck) {
this.debounceCheck = debounce(this.check, this.props.scrollDelay);
this.getContainer().addEventListener('scroll', this.debounceCheck);
this.addEventListener(
this.getContainer(),
'scroll',
this.props.scrollDelay,
this.props.scrollThrottle
);
}

if (this.props.resizeCheck) {
this.addEventListener(
window,
'resize',
this.props.resizeDelay,
this.props.resizeThrottle
);
}

// if dont need delayed call, check on load ( before the first interval fires )
Expand All @@ -111,20 +183,32 @@ module.exports = React.createClass({

stopWatching: function () {
if (this.debounceCheck) {
this.getContainer().removeEventListener('scroll', this.debounceCheck);
this.debounceCheck = null;
// clean up event listeners and their debounce callers
for (var debounceEvent in this.debounceCheck) {
if (this.debounceCheck.hasOwnProperty(debounceEvent)) {
var debounceInfo = this.debounceCheck[debounceEvent];

clearTimeout(debounceInfo.getLastTimeout());
debounceInfo.target.removeEventListener(
debounceEvent, debounceInfo.fn
);

this.debounceCheck[debounceEvent] = null;
}
}
}
this.debounceCheck = null;

if (this.interval) { this.interval = clearInterval(this.interval); }
},

/**
* Check if the element is within the visible viewport
*/
check: function () {
var el = ReactDOM.findDOMNode(this);
var el = this.node;
var rect;
var containmentRect;

// if the component has rendered to null, dont update visibility
if (!el) {
return this.state;
Expand All @@ -133,7 +217,13 @@ module.exports = React.createClass({
rect = el.getBoundingClientRect();

if (this.props.containment) {
containmentRect = this.props.containment.getBoundingClientRect();
var containmentDOMRect = this.props.containment.getBoundingClientRect();
containmentRect = {
top: containmentDOMRect.top,
left: containmentDOMRect.left,
bottom: containmentDOMRect.bottom,
right: containmentDOMRect.right,
}
} else {
containmentRect = {
top: 0,
Expand All @@ -143,6 +233,16 @@ module.exports = React.createClass({
};
}

// Check if visibility is wanted via offset?
var offset = this.props.offset || {};
var hasValidOffset = typeof offset === 'object';
if (hasValidOffset) {
containmentRect.top += offset.top || 0;
containmentRect.left += offset.left || 0;
containmentRect.bottom -= offset.bottom || 0;
containmentRect.right -= offset.right || 0;
}

var visibilityRect = {
top: rect.top >= containmentRect.top,
left: rect.left >= containmentRect.left,
Expand Down Expand Up @@ -175,15 +275,6 @@ module.exports = React.createClass({
: partialVisible
}

// Check if visibility is wanted via offset?
var offset = this.props.offset
var hasValidOffset = typeof offset === 'object' &&
typeof offset.direction === 'string' &&
typeof offset.value === 'number';
if (hasValidOffset) {
isVisible = isVisibleWithOffset(offset, rect, containmentRect);
}

var state = this.state;
// notify the parent when the value changes
if (this.state.isVisible !== isVisible) {
Expand Down