Skip to content

Commit

Permalink
perf(Visibility): use RAF
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Fedyashov committed Aug 29, 2017
1 parent e1ff28a commit 8bab0a1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 18 deletions.
10 changes: 9 additions & 1 deletion src/behaviors/Visibility/Visibility.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,9 +272,17 @@ export default class Visibility extends Component {
})
}

handleScroll = () => {
if (this.ticking) return

this.ticking = true
requestAnimationFrame(() => this.handleUpdate())
}

handleRef = c => (this.ref = c)

handleScroll = () => {
handleUpdate = () => {
this.ticking = false
const { bottom, height, top, width } = this.ref.getBoundingClientRect()

const topPassed = top < 0
Expand Down
50 changes: 33 additions & 17 deletions test/specs/behaviors/Visibility/Visibility-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,29 +95,23 @@ const expectations = [{
describe('Visibility', () => {
common.isConformant(Visibility)

beforeEach(() => {
wrapper = undefined
let requestAnimationFrame

before(() => {
requestAnimationFrame = window.requestAnimationFrame
window.requestAnimationFrame = fn => fn()
})

afterEach(() => {
if (wrapper && wrapper.unmount) wrapper.unmount()
after(() => {
window.requestAnimationFrame = requestAnimationFrame
})

it('should use window as default scroll context', () => {
const onUpdate = sandbox.spy()
mount(<Visibility onUpdate={onUpdate} />)
window.dispatchEvent(new Event('scroll'))
onUpdate.should.have.been.called()
beforeEach(() => {
wrapper = undefined
})

it('should set a scroll context', () => {
const div = document.createElement('div')
const onUpdate = sandbox.spy()
mount(<Visibility onUpdate={onUpdate} context={div} />)
window.dispatchEvent(new Event('scroll'))
onUpdate.should.not.have.been.called()
div.dispatchEvent(new Event('scroll'))
onUpdate.should.have.been.called()
afterEach(() => {
if (wrapper && wrapper.unmount) wrapper.unmount()
})

describe('calculations', () => {
Expand Down Expand Up @@ -185,6 +179,28 @@ describe('Visibility', () => {
})
})

describe('context', () => {
it('should use window as default scroll context', () => {
const onUpdate = sandbox.spy()
mount(<Visibility onUpdate={onUpdate} />)

window.dispatchEvent(new Event('scroll'))
onUpdate.should.have.been.called()
})

it('should set a scroll context', () => {
const div = document.createElement('div')
const onUpdate = sandbox.spy()
mount(<Visibility onUpdate={onUpdate} context={div} />)

window.dispatchEvent(new Event('scroll'))
onUpdate.should.not.have.been.called()

div.dispatchEvent(new Event('scroll'))
onUpdate.should.have.been.called()
})
})

describe('onPassed', () => {
it('fires callback when pixels passed', () => {
const onPassed = {
Expand Down

0 comments on commit 8bab0a1

Please sign in to comment.