From c8fac2f878a1035e6db6bc3d40a28285bc8f5f8e Mon Sep 17 00:00:00 2001 From: Jack Franklin Date: Fri, 10 Nov 2017 10:20:44 +0000 Subject: [PATCH] Add `stayVisible` prop. This makes the `VisibilitySensor` stay visible once it is visible for the first time, even if it then is scrolled out of the viewport. This means that `onChange` will only be called once, the first time it becomes visible, and then never again. --- tests/visibility-sensor-spec.jsx | 26 ++++++++++++++++++++++++++ visibility-sensor.js | 7 +++++++ 2 files changed, 33 insertions(+) diff --git a/tests/visibility-sensor-spec.jsx b/tests/visibility-sensor-spec.jsx index 60a01d2..6e38b29 100644 --- a/tests/visibility-sensor-spec.jsx +++ b/tests/visibility-sensor-spec.jsx @@ -241,6 +241,32 @@ describe('VisibilitySensor', function () { ReactDOM.render(element, node); }); + it('with the stayVisible prop it stays visible once it has been seen once', function (done) { + var firstTime = true; + let callCount = 0; + node.setAttribute('style', 'position:absolute; width:100px; height:100px; top:-49px'); + + var onChange = function (isVisible) { + callCount++; + assert.equal(isVisible, true, 'Component starts out visible'); + node.setAttribute('style', 'position:absolute; width:100px; height:100px; top:-51px'); + setTimeout(function () { + assert.equal( + callCount, + 1, + 'Component is out of the viewport but stays visible and onChange is not called again' + ); + done(); + }, 200) + } + + var element = ( + + ); + + ReactDOM.render(element, node); + }); + it('should call child function with state', function (done) { var wasChildrenCalled = false; var children = function (props) { diff --git a/visibility-sensor.js b/visibility-sensor.js index ea26764..28720f4 100644 --- a/visibility-sensor.js +++ b/visibility-sensor.js @@ -48,6 +48,7 @@ module.exports = createReactClass({ PropTypes.bool, PropTypes.oneOf(['top', 'right', 'bottom', 'left']), ]), + stayVisible: PropTypes.bool, delayedCall: PropTypes.bool, offset: PropTypes.oneOfType([ PropTypes.shape({ @@ -82,6 +83,7 @@ module.exports = createReactClass({ return { active: true, partialVisibility: false, + stayVisible: false, minTopValue: 0, scrollCheck: false, scrollDelay: 250, @@ -229,6 +231,11 @@ module.exports = createReactClass({ return this.state; } + if (this.state.isVisible === true && this.props.stayVisible === true) { + this.stopWatching() + return this.state; + }; + rect = el.getBoundingClientRect(); if (this.props.containment) {