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

no jquery fixes #123

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 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
48 changes: 46 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,54 @@ module.exports = {
ecmaVersion: 2017,
sourceType: 'module'
},
extends: 'eslint:recommended',
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
}
},
overrides: [
// node files
{
files: [
'index.js',
'testem.js',
'ember-cli-build.js',
'config/**/*.js',
'tests/dummy/config/**/*.js'
],
excludedFiles: [
'app/**',
'addon/**',
'tests/dummy/app/**'
],
parserOptions: {
sourceType: 'script',
ecmaVersion: 2015
},
env: {
browser: false,
node: true
},
plugins: ['node'],
rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, {
// add your custom rules and overrides for node files here
})
},

// test files
{
files: ['tests/**/*.js'],
excludedFiles: ['tests/dummy/**/*.js'],
env: {
embertest: true
}
}
]
};
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
.bowerrc
.editorconfig
.ember-cli
.gitignore
.eslintrc.js
.gitignore
.watchmanconfig
.travis.yml
bower.json
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ The mixin comes with some options. Due to the way listeners and `IntersectionObs

```js
export default Ember.Component.extend(InViewportMixin, {
viewportOptionsOverride: Ember.on('didInsertElement', function() {
init() {
this._super(...arguments);

Ember.setProperties(this, {
viewportEnabled : true,
viewportUseRAF : true,
Expand All @@ -93,7 +95,7 @@ export default Ember.Component.extend(InViewportMixin, {
right : 20
}
});
})
}
});
```

Expand Down
79 changes: 48 additions & 31 deletions addon/mixins/in-viewport.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { assign } from '@ember/polyfills';
import Mixin from '@ember/object/mixin';
import { typeOf } from '@ember/utils';
import { assert } from '@ember/debug';
import $ from 'jquery';
import { set, get, setProperties } from '@ember/object';
import { next, bind, debounce, scheduleOnce } from '@ember/runloop';
import { not } from '@ember/object/computed';
import { getOwner } from '@ember/application';
import canUseDOM from 'ember-in-viewport/utils/can-use-dom';
import canUseRAF from 'ember-in-viewport/utils/can-use-raf';
import findElem from 'ember-in-viewport/utils/find-elem';
import canUseIntersectionObserver from 'ember-in-viewport/utils/can-use-intersection-observer';
import isInViewport from 'ember-in-viewport/utils/is-in-viewport';
import checkScrollDirection from 'ember-in-viewport/utils/check-scroll-direction';
Expand Down Expand Up @@ -37,6 +37,8 @@ export default Mixin.create({
}, this._buildOptions());

setProperties(this, options);
this._triggerDidScrollDirectionHandler = this._triggerDidScrollDirectionHandler.bind(this);
this._setViewportEnteredHandler = this._setViewportEnteredHandler.bind(this);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This somewhat spreads out the logic wrt to setViewportEntered. What do ou think?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you have any better idea how to remove handlers?

},

didInsertElement() {
Expand Down Expand Up @@ -71,7 +73,7 @@ export default Mixin.create({
_startListening() {
this._setInitialViewport();
this._addObserverIfNotSpying();
this._bindScrollDirectionListener(get(this, 'viewportScrollSensitivity'));
this._bindScrollDirectionListener();

if (!get(this, 'viewportUseRAF')) {
get(this, 'viewportListeners').forEach((listener) => {
Expand All @@ -98,6 +100,8 @@ export default Mixin.create({
}

if (get(this, 'viewportUseIntersectionObserver')) {
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
// IntersectionObserver takes either a Document Element or null for `root`
const { top, left, bottom, right } = this.viewportTolerance;
const options = {
root: scrollableArea,
Expand All @@ -108,15 +112,16 @@ export default Mixin.create({
this.intersectionObserver = new IntersectionObserver(bind(this, this._onIntersection), options);
this.intersectionObserver.observe(element);
} else {
const $contextEl = scrollableArea ? $(scrollableArea) : $(window);
const height = scrollableArea ? scrollableArea.offsetHeight : window.innerHeight;
const width = scrollableArea ? scrollableArea.offsetWidth : window.innerWidth;
const boundingClientRect = element.getBoundingClientRect();

if (boundingClientRect) {
this._triggerDidAccessViewport(
isInViewport(
boundingClientRect,
$contextEl.innerHeight(),
$contextEl.innerWidth(),
height,
width,
get(this, 'viewportTolerance')
)
);
Expand All @@ -136,27 +141,29 @@ export default Mixin.create({
* @param {Array} - entries
*/
_onIntersection(entries) {
const entry = entries[0];

if (entry.isIntersecting) {
set(this, 'viewportEntered', true);
this.trigger('didEnterViewport');
} else if (entry.intersectionRatio <= 0) { // exiting viewport
set(this, 'viewportEntered', false);
this.trigger('didExitViewport');
if (!this.isDestroyed && !this.isDestroying) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good catch! I’m guessing you saw this error when trying out this branch?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see this error now. Nice

const entry = entries[0];

if (entry.isIntersecting) {
set(this, 'viewportEntered', true);
this.trigger('didEnterViewport');
} else if (entry.intersectionRatio <= 0) { // exiting viewport
set(this, 'viewportEntered', false);
this.trigger('didExitViewport');
}
}
},

_triggerDidScrollDirection($contextEl = null, sensitivity = 1) {
assert('You must pass a valid context element to _triggerDidScrollDirection', $contextEl);
_triggerDidScrollDirection(contextEl = null, sensitivity = 1) {
assert('You must pass a valid context element to _triggerDidScrollDirection', contextEl);
assert('sensitivity cannot be 0', sensitivity);

const elementId = get(this, 'elementId');
const lastDirectionForEl = lastDirection[elementId];
const lastPositionForEl = lastPosition[elementId];
const newPosition = {
top: $contextEl.scrollTop(),
left: $contextEl.scrollLeft()
top: contextEl.scrollTop,
left: contextEl.scrollLeft
};

const scrollDirection = checkScrollDirection(lastPositionForEl, newPosition, sensitivity);
Expand Down Expand Up @@ -205,29 +212,37 @@ export default Mixin.create({
});
},

_triggerDidScrollDirectionHandler(event) {
const sensitivity = get(this, 'viewportScrollSensitivity') || 1;

this._debouncedEventHandler('_triggerDidScrollDirection', event.currentTarget, sensitivity);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious what your thoughts are bw ever.currentTarget vs scrollableArea vs window in detecting scroll direction. Perhaps irrelevant thus this might be a good fix?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scrollableArea property may be null if it's not set in the component where the mixin is used. So I believe currentTarget is the best idea here.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@latata If scrollableArea is not defined, then it defaults to window. Did you happen to see in error wrt to this?

},

_setViewportEnteredHandler() {
this._debouncedEventHandler('_setViewportEntered');
},

_debouncedEventHandler(methodName, ...args) {
assert('You must pass a methodName to _debouncedEventHandler', methodName);
assert('methodName must be a string', typeOf(methodName) === 'string');

debounce(this, () => this[methodName](...args), get(this, 'viewportRefreshRate'));
},

_bindScrollDirectionListener(sensitivity = 1) {
assert('sensitivity cannot be 0', sensitivity);

const $contextEl = get(this, 'scrollableArea') ? $(get(this, 'scrollableArea')) : $(window);
_bindScrollDirectionListener() {
const contextEl = get(this, 'scrollableArea') || window;
let elem = findElem(contextEl);

$contextEl.on(`scroll.directional#${get(this, 'elementId')}`, () => {
this._debouncedEventHandler('_triggerDidScrollDirection', $contextEl, sensitivity);
});
elem.addEventListener('scroll', this._triggerDidScrollDirectionHandler);
},

_unbindScrollDirectionListener() {
const elementId = get(this, 'elementId');

const context = get(this, 'scrollableArea') || window;
let elem = findElem(context);

$(context).off(`scroll.directional#${elementId}`);
elem.removeEventListener('scroll', this._triggerDidScrollDirectionHandler);
delete lastPosition[elementId];
delete lastDirection[elementId];
},
Expand All @@ -236,9 +251,9 @@ export default Mixin.create({
assert('You must pass a valid context to _bindListeners', context);
assert('You must pass a valid event to _bindListeners', event);

$(context).on(`${event}.${get(this, 'elementId')}`, () => {
this._debouncedEventHandler('_setViewportEntered', context);
});
let elem = findElem(context);

elem.addEventListener(event, this._setViewportEnteredHandler);
},

_unbindListeners() {
Expand All @@ -253,10 +268,12 @@ export default Mixin.create({

get(this, 'viewportListeners').forEach((listener) => {
let { context, event } = listener;
context = get(this, 'scrollableArea') ? get(this, 'scrollableArea') : context;
$(context).off(`${event}.${elementId}`);
context = get(this, 'scrollableArea') || context;

let elem = findElem(context);
elem.removeEventListener(event, this._setViewportEnteredHandler);
});

this._unbindScrollDirectionListener();
}
},
});
14 changes: 14 additions & 0 deletions addon/utils/find-elem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export default function(context) {
let elem;
if (
context.nodeType === Node.ELEMENT_NODE ||
context.nodeType === Node.DOCUMENT_NODE ||
context instanceof Window
) {
elem = context
} else {
elem = document.querySelector(context);
}

return elem;
}
4 changes: 2 additions & 2 deletions app/initializers/viewport-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ const defaultConfig = {
viewportScrollSensitivity: 1,
viewportRefreshRate: 100,
viewportListeners: [
{ context: window, event: 'scroll.scrollable' },
{ context: window, event: 'resize.resizable' }
{ context: window, event: 'scroll' },
{ context: window, event: 'resize' }
],
viewportTolerance: {
top: 0,
Expand Down
1 change: 0 additions & 1 deletion config/ember-try.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-env node */
module.exports = {
scenarios: [
{
Expand Down
1 change: 0 additions & 1 deletion config/environment.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-env node */
'use strict';

module.exports = function(/* environment, appConfig */) {
Expand Down
4 changes: 3 additions & 1 deletion ember-cli-build.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* eslint-env node */
'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
let app = new EmberAddon(defaults, {
babel: {
includePolyfill: true,
}
// Add options here
});

Expand Down
1 change: 0 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-env node */
'use strict';

module.exports = {
Expand Down
Loading