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

Handle zero-area and display: none cases for v2 release branch #103

Merged
merged 1 commit into from
Jan 8, 2019
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
12 changes: 5 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,23 @@ Copyright 2017 LinkedIn Corp. Licensed under the Apache License,
Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import { SpanielIntersectionObserver, generateEntry } from './intersection-observer';

import { entrySatisfiesRatio } from './utils';

import { SpanielTrackedElement, SpanielObserverEntry, DOMString, DOMMargin } from './interfaces';
import { SpanielTrackedElement, DOMMargin } from './interfaces';

export { Watcher, WatcherConfig } from './watcher';

import { SpanielObserver } from './spaniel-observer';

import { setGlobalEngine, getGlobalEngine } from './metal/engine';

import { Scheduler, getGlobalScheduler, on, off, scheduleWork, scheduleRead, Frame } from './metal/index';
import { getGlobalScheduler, on, off, scheduleWork, scheduleRead, Frame } from './metal/index';

import w from './metal/window-proxy';

Expand All @@ -46,13 +44,13 @@ export function queryElement(el: Element, callback: (clientRect: ClientRect, fra
}

export function elementSatisfiesRatio(
el: Element,
el: HTMLElement,
ratio: number = 0,
callback: (result: Boolean) => void,
rootMargin: DOMMargin = { top: 0, bottom: 0, left: 0, right: 0 }
) {
queryElement(el, (clientRect: ClientRect, frame: Frame) => {
let entry = generateEntry(frame, clientRect, el, rootMargin);
callback(entrySatisfiesRatio(entry, ratio));
callback(entry.isIntersecting && entry.intersectionRatio >= ratio);
});
}
2 changes: 1 addition & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

export interface SpanielTrackedElement extends Element {
export interface SpanielTrackedElement extends HTMLElement {
__spanielId: string;
}

Expand Down
46 changes: 37 additions & 9 deletions src/intersection-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import { entrySatisfiesRatio } from './utils';
import { calculateIsIntersecting } from './utils';

import { Frame, QueueDOMElementInterface, DOMQueue, ElementScheduler, Engine, generateToken } from './metal/index';

Expand Down Expand Up @@ -65,7 +65,7 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
public thresholds: number[];
private records: { [index: string]: EntryEvent };

observe(target: Element) {
observe(target: HTMLElement) {
let trackedTarget = target as SpanielTrackedElement;

let id = (trackedTarget.__spanielId = trackedTarget.__spanielId || generateToken());
Expand All @@ -79,7 +79,7 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
);
return id;
}
private onTick(frame: Frame, id: string, clientRect: DOMRectReadOnly, el: Element) {
private onTick(frame: Frame, id: string, clientRect: DOMRectReadOnly, el: SpanielTrackedElement) {
let { numSatisfiedThresholds, entry } = this.generateEntryEvent(frame, clientRect, el);
let record: EntryEvent =
this.records[id] ||
Expand All @@ -88,8 +88,12 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
numSatisfiedThresholds: 0
});

if (numSatisfiedThresholds !== record.numSatisfiedThresholds) {
if (
numSatisfiedThresholds !== record.numSatisfiedThresholds ||
entry.isIntersecting !== record.entry.isIntersecting
) {
record.numSatisfiedThresholds = numSatisfiedThresholds;
record.entry = entry;
this.scheduler.scheduleWork(() => {
this.callback([entry]);
});
Expand All @@ -106,14 +110,14 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
takeRecords(): IntersectionObserverEntry[] {
return [];
}
private generateEntryEvent(frame: Frame, clientRect: DOMRectReadOnly, el: Element): EntryEvent {
private generateEntryEvent(frame: Frame, clientRect: DOMRectReadOnly, el: HTMLElement): EntryEvent {
let count: number = 0;
let entry = generateEntry(frame, clientRect, el, this.rootMarginObj);
let ratio = entry.intersectionRatio;

for (let i = 0; i < this.thresholds.length; i++) {
let threshold = this.thresholds[i];
if (entrySatisfiesRatio(entry, threshold)) {
if (entry.intersectionRatio >= threshold) {
count++;
}
}
Expand Down Expand Up @@ -152,7 +156,7 @@ function addRatio(entryInit: SpanielIntersectionObserverEntryInit): Intersection
intersectionRect,
target,
intersectionRatio,
isIntersecting: intersectionRatio > 0
isIntersecting: calculateIsIntersecting({ intersectionRect })
};
}

Expand Down Expand Up @@ -182,13 +186,37 @@ export class IntersectionObserverEntry implements IntersectionObserverEntryInit
};
*/

function emptyRect(): ClientRect | DOMRect {
return {
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
x: 0,
y: 0
};
}

export function generateEntry(
frame: Frame,
clientRect: DOMRectReadOnly,
el: Element,
el: HTMLElement,
rootMargin: DOMMargin
): IntersectionObserverEntry {
let { top, bottom, left, right } = clientRect;
if (el.style.display === 'none') {
return {
boundingClientRect: emptyRect(),
intersectionRatio: 0,
intersectionRect: emptyRect(),
isIntersecting: false,
rootBounds: emptyRect(),
target: el,
time: frame.timestamp
};
}
let { bottom, right } = clientRect;
let rootBounds: ClientRect = {
left: frame.left + rootMargin.left,
top: frame.top + rootMargin.top,
Expand Down
7 changes: 4 additions & 3 deletions src/native-spaniel-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import { entrySatisfiesRatio } from './utils';
import { calculateIsIntersecting } from './utils';

import {
IntersectionObserverInit,
Expand Down Expand Up @@ -187,9 +187,10 @@ export class SpanielObserver implements SpanielObserverInterface {
let hasTimeThreshold = !!state.threshold.time;
let spanielEntry: SpanielObserverEntry = this.generateSpanielEntry(entry, state);

const ratioSatisfied = entrySatisfiesRatio(entry, state.threshold.ratio);
const ratioSatisfied = entry.intersectionRatio >= state.threshold.ratio;
const isIntersecting = calculateIsIntersecting(entry);

if (ratioSatisfied && !state.lastSatisfied) {
if (ratioSatisfied && !state.lastSatisfied && isIntersecting) {
spanielEntry.entering = true;
if (hasTimeThreshold) {
state.lastVisible = time;
Expand Down
7 changes: 4 additions & 3 deletions src/spaniel-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import { entrySatisfiesRatio } from './utils';
import { calculateIsIntersecting } from './utils';

import { SpanielIntersectionObserver } from './intersection-observer';

Expand Down Expand Up @@ -191,9 +191,10 @@ export class SpanielObserver implements SpanielObserverInterface {
let hasTimeThreshold = !!state.threshold.time;
let spanielEntry: SpanielObserverEntry = this.generateSpanielEntry(entry, state);

const ratioSatisfied = entrySatisfiesRatio(entry, state.threshold.ratio);
const ratioSatisfied = entry.intersectionRatio >= state.threshold.ratio;
const isIntersecting = calculateIsIntersecting(entry);

if (ratioSatisfied && !state.lastSatisfied) {
if (ratioSatisfied && !state.lastSatisfied && isIntersecting) {
spanielEntry.entering = true;
if (hasTimeThreshold) {
state.lastVisible = time;
Expand Down
17 changes: 2 additions & 15 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
import { SpanielClientRectInterface } from './metal/interfaces';

export function entrySatisfiesRatio(entry: IntersectionObserverEntry, threshold: number) {
let { boundingClientRect, intersectionRatio } = entry;

// Edge case where item has no actual area
if (boundingClientRect.width === 0 || boundingClientRect.height === 0) {
let { boundingClientRect, intersectionRect } = entry;
return (
boundingClientRect.left === intersectionRect.left &&
boundingClientRect.top === intersectionRect.top &&
intersectionRect.width >= 0 &&
intersectionRect.height >= 0
);
} else {
return intersectionRatio > threshold || (intersectionRatio === 1 && threshold === 1);
}
export function calculateIsIntersecting({ intersectionRect }: { intersectionRect: ClientRect }) {
return intersectionRect.width > 0 || intersectionRect.height > 0;
}

export function getBoundingClientRect(element: Element): SpanielClientRectInterface {
Expand Down
2 changes: 1 addition & 1 deletion test/headless/context.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
Copyright 2017 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
 You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

Expand Down
1 change: 1 addition & 0 deletions test/headless/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ server.stdout.on('data', data => {
'--require',
'@babel/register',
'test/headless/specs/**/*.js',
'test/headless/specs/*.js',
'--exit',
'--timeout',
'5000'
Expand Down
63 changes: 63 additions & 0 deletions test/headless/specs/intersection-observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ Unless required by applicable law or agreed to in writing, software
distribute
import { assert } from 'chai';
import { default as testModule, TestClass } from './../test-module';

import constants from './../../constants.js';

const {
time: { IMPRESSION_THRESHOLD }
} = constants;

testModule(
'IntersectionObserver',
class extends TestClass {
Expand Down Expand Up @@ -55,6 +61,63 @@ testModule(
});
}

['@test observing a hidden element should fire an event with a ratio of 0']() {
return this.context
.evaluate(() => {
window.STATE.intersectionEvents = 0;
window.STATE.impressions = 0;
let target = (window.testTarget = document.querySelector('.tracked-item[data-id="1"]'));
target.style.display = 'none';
let observer = new spaniel.IntersectionObserver(function(entries) {
window.STATE.intersectionEvents++;

if (entries[0].intersectionRatio > 0) {
window.STATE.impressions++;
}
});
observer.observe(target);
})
.wait(IMPRESSION_THRESHOLD)
.getExecution()
.evaluate(function() {
return window.STATE;
})
.then(function({ impressions, intersectionEvents }) {
assert.equal(impressions, 0, 'No visible events');
assert.equal(intersectionEvents, 1, 'Callback fired once');
});
}

['@test hiding an observed element should fire an event without isIntersecting']() {
return this.context
.evaluate(() => {
window.STATE.intersectionEvents = 0;
window.STATE.impressions = 0;
let target = (window.testTarget = document.querySelector('.tracked-item[data-id="1"]'));
let observer = new spaniel.IntersectionObserver(function(entries) {
window.STATE.intersectionEvents++;

if (entries[0].isIntersecting) {
window.STATE.impressions++;
}
});
observer.observe(target);
})
.wait(IMPRESSION_THRESHOLD)
.evaluate(function() {
window.testTarget.style.display = 'none';
})
.wait(IMPRESSION_THRESHOLD)
.getExecution()
.evaluate(function() {
return window.STATE;
})
.then(function({ impressions, intersectionEvents }) {
assert.equal(intersectionEvents, 2, 'Callback fired twice');
assert.equal(impressions, 1, 'One visible event');
});
}

['@test observing a non visible element should not fire']() {
return this.context
.evaluate(function() {
Expand Down