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 #102

Merged
merged 2 commits into from
Jan 7, 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
34 changes: 6 additions & 28 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,16 @@ 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, DOMMargin, IntersectionObserverClass } from './interfaces';

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

import { SpanielIntersectionObserver } from './intersection-observer';
import { SpanielTrackedElement, IntersectionObserverClass } from './interfaces';
import { SpanielObserver } from './spaniel-observer';

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

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

import { on, off, scheduleWork, scheduleRead } from './metal/index';
import w from './metal/window-proxy';

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

const IntersectionObserver: IntersectionObserverClass = !!w.IntersectionObserver
? w.IntersectionObserver
: SpanielIntersectionObserver;
Expand All @@ -40,19 +34,3 @@ export {
setGlobalEngine,
getGlobalEngine
};

export function queryElement(el: Element, callback: (bcr: ClientRect, frame: Frame) => void) {
getGlobalScheduler().queryElement(el, callback);
}

export function elementSatisfiesRatio(
el: Element,
ratio: number = 0,
callback: (result: Boolean) => void,
rootMargin: DOMMargin = { top: 0, bottom: 0, left: 0, right: 0 }
) {
queryElement(el, (bcr: ClientRect, frame: Frame) => {
let entry = generateEntry(frame, bcr, el, rootMargin);
callback(entrySatisfiesRatio(entry, 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
44 changes: 36 additions & 8 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, ElementScheduler, generateToken } from './metal/index';

Expand Down Expand Up @@ -63,7 +63,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 @@ -77,7 +77,7 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
);
return id;
}
private onTick(frame: Frame, id: string, bcr: DOMRectReadOnly, el: Element) {
private onTick(frame: Frame, id: string, bcr: DOMRectReadOnly, el: SpanielTrackedElement) {
let { numSatisfiedThresholds, entry } = this.generateEntryEvent(frame, bcr, el);
let record: EntryEvent =
this.records[id] ||
Expand All @@ -86,8 +86,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 @@ -104,13 +108,13 @@ export class SpanielIntersectionObserver implements IntersectionObserver {
takeRecords(): IntersectionObserverEntry[] {
return [];
}
private generateEntryEvent(frame: Frame, bcr: DOMRectReadOnly, el: Element): EntryEvent {
private generateEntryEvent(frame: Frame, bcr: DOMRectReadOnly, el: HTMLElement): EntryEvent {
let count: number = 0;
let entry = generateEntry(frame, bcr, el, this.rootMarginObj);

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 @@ -149,7 +153,7 @@ function addRatio(entryInit: SpanielIntersectionObserverEntryInit): Intersection
intersectionRect,
target,
intersectionRatio,
isIntersecting: null
isIntersecting: calculateIsIntersecting({ intersectionRect })
};
}

Expand Down Expand Up @@ -179,12 +183,36 @@ 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,
bcr: DOMRectReadOnly,
el: Element,
el: HTMLElement,
rootMargin: DOMMargin
): IntersectionObserverEntry {
if (el.style.display === 'none') {
return {
boundingClientRect: emptyRect(),
intersectionRatio: 0,
intersectionRect: emptyRect(),
isIntersecting: false,
rootBounds: emptyRect(),
target: el,
time: frame.timestamp
};
}
let { bottom, right } = bcr;
let rootBounds: ClientRect = {
left: frame.x - rootMargin.left,
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 @@ -192,9 +192,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
35 changes: 21 additions & 14 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
export function entrySatisfiesRatio(entry: IntersectionObserverEntry, threshold: number) {
let { boundingClientRect, intersectionRatio } = entry;
import { generateEntry } from './intersection-observer';
import { DOMMargin } from './interfaces';
import { getGlobalScheduler, Frame } from './metal/index';

// 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 queryElement(el: Element, callback: (bcr: ClientRect, frame: Frame) => void) {
getGlobalScheduler().queryElement(el, callback);
}

export function elementSatisfiesRatio(
el: HTMLElement,
ratio: number = 0,
callback: (result: Boolean) => void,
rootMargin: DOMMargin = { top: 0, bottom: 0, left: 0, right: 0 }
) {
queryElement(el, (bcr: ClientRect, frame: Frame) => {
let entry = generateEntry(frame, bcr, el, rootMargin);
callback(entry.isIntersecting && entry.intersectionRatio >= ratio);
});
}
24 changes: 13 additions & 11 deletions 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 All @@ -13,19 +13,21 @@ const MAC_WINDOW_BAR_HEIGHT = 22; // See https://github.com/segmentio/nightmare/

export default class Context {
constructor() {
this._nightmare = Nightmare({ show: false }),
this._nightmare.viewport(400, 400 + MAC_WINDOW_BAR_HEIGHT);
(this._nightmare = Nightmare({ show: false })), this._nightmare.viewport(400, 400 + MAC_WINDOW_BAR_HEIGHT);
this._events = [];
this._results = [];
this._assertions = [];
this._execution = this._root = this._nightmare.goto('http://localhost:3000/').wait(10).evaluate(function() {
window.STATE = {};
window.createDiv = function(id) {
var div = document.createElement('div');
div.id = id;
document.body.appendChild(div);
}
});
this._execution = this._root = this._nightmare
.goto('http://localhost:3000/')
.wait(10)
.evaluate(function() {
window.STATE = {};
window.createDiv = function(id) {
var div = document.createElement('div');
div.id = id;
document.body.appendChild(div);
};
});
}
close() {
return this._root.end();
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
Loading