From 72c59adcdf3f6a9b57cebce0a3ab415ba36c2b6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Andersson?= Date: Sun, 2 Mar 2014 04:30:03 +0800 Subject: [PATCH] Initial commit --- .gitattributes | 2 + .gitignore | 3 + .jshintrc | 39 ++++++++ .travis.yml | 8 ++ CONTRIBUTING.md | 141 ++++++++++++++++++++++++++ Gruntfile.js | 30 ++++++ LICENSE.md | 19 ++++ README.md | 90 +++++++++++++++++ bower.json | 22 +++++ karma.conf.js | 89 +++++++++++++++++ lib/scrollspy.js | 47 +++++++++ lib/with_spy.js | 185 +++++++++++++++++++++++++++++++++++ package.json | 23 +++++ test/fixtures/scrollspy.html | 7 ++ test/spec/scrollspy.spec.js | 30 ++++++ test/spec/with_spy.spec.js | 139 ++++++++++++++++++++++++++ test/test-main.js | 22 +++++ 17 files changed, 896 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .jshintrc create mode 100644 .travis.yml create mode 100644 CONTRIBUTING.md create mode 100644 Gruntfile.js create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 bower.json create mode 100644 karma.conf.js create mode 100644 lib/scrollspy.js create mode 100644 lib/with_spy.js create mode 100644 package.json create mode 100644 test/fixtures/scrollspy.html create mode 100644 test/spec/scrollspy.spec.js create mode 100644 test/spec/with_spy.spec.js create mode 100644 test/test-main.js diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..0a91f75 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Automatically normalize line endings for all text-based files +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0173852 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +bower_components +node_modules +coverage diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..7c58d76 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,39 @@ +{ + "node": true, + "browser": true, + "esnext": true, + "bitwise": true, + "camelcase": true, + "curly": true, + "eqeqeq": true, + "immed": true, + "indent": 2, + "latedef": false, + "newcap": true, + "noarg": true, + "quotmark": "single", + "regexp": true, + "smarttabs": true, + "strict": true, + "trailing": true, + "undef": true, + "unused": true, + "validthis": true, + "predef": [ + "$", + "jQuery", + "before", + "beforeEach", + "define", + "describe", + "describeComponent", + "describeMixin", + "expect", + "it", + "jasmine", + "readFixtures", + "requirejs", + "setupComponent", + "spyOnEvent" + ] +} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..5de4fc4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.10" +before_script: + - npm install -g bower grunt-cli + - bower install +after_script: + - grunt coveralls \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a04ec3f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,141 @@ +# Contributing to flight-scrollspy + +Please take a moment to review this document in order to make the contribution +process easy and effective for everyone involved. + +Following these guidelines helps to communicate that you respect the time of +the developers managing and developing this open source project. In return, +they should reciprocate that respect in addressing your issue or assessing +patches and features. + +## Using the issue tracker + +The issue tracker is the preferred channel for [bug reports](#bugs), +[features requests](#features) and [submitting pull +requests](#pull-requests), but please respect the following restrictions: + +* Please **do not** use the issue tracker for personal support requests. + +* Please **do not** derail or troll issues. Keep the discussion on topic and + respect the opinions of others. + + + +## Bug reports + +A bug is a _demonstrable problem_ that is caused by the code in the repository. +Good bug reports are extremely helpful - thank you! + +Guidelines for bug reports: + +1. **Use the issue search** — check if the issue has already been + reported. + +2. **Check if the issue has been fixed** — try to reproduce it using the + latest `master` or development branch in the repository. + +3. **Isolate the problem** – create a live example of a [reduced test + case](http://css-tricks.com/6263-reduced-test-cases/). + +A good bug report shouldn't leave others needing to chase you up for more +information. Please try to be as detailed as possible in your report. What is +your environment? What steps will reproduce the issue? What browser(s) and OS +experience the problem? What would you expect to be the outcome? All these +details will help people to fix any potential bugs. + +Example: + +> Short and descriptive example bug report title +> +> A summary of the issue and the browser/OS environment in which it occurs. If +> suitable, include the steps required to reproduce the bug. +> +> 1. This is the first step +> 2. This is the second step +> 3. Further steps, etc. +> +> `` - a link to the reduced test case +> +> Any other information you want to share that is relevant to the issue being +> reported. This might include the lines of code that you have identified as +> causing the bug, and potential solutions (and your opinions on their +> merits). + + + +## Feature requests + +Feature requests are welcome. But take a moment to find out whether your idea +fits with the scope and aims of the project. It's up to *you* to make a strong +case to convince the project's developers of the merits of this feature. Please +provide as much detail and context as possible. + + + +## Pull requests + +Good pull requests - patches, improvements, new features - are a fantastic +help. They should remain focused in scope and avoid containing unrelated +commits. + +**Please ask first** before embarking on any significant pull request (e.g. +implementing features, refactoring code, porting to a different language), +otherwise you risk spending a lot of time working on something that the +project's developers might not want to merge into the project. + +Please adhere to the coding conventions used throughout a project (indentation, +accurate comments, etc.) and any other requirements (such as test coverage). + +Adhering to the following this process is the best way to get your work +included in the project: + +1. If you do not have permissions to push to the upstream remote origin, + [fork](http://help.github.com/fork-a-repo/) the project, clone your fork, + and configure the remotes: + + ```bash + # Clone your fork of the repo into the current directory + git clone + # Navigate to the newly cloned directory + cd + # Assign the original repo to a remote called "upstream" + git remote add upstream + ``` + +2. If you cloned a while ago, get the latest changes from upstream: + + ```bash + git checkout + git pull upstream + ``` + +3. Create a new topic branch (off the main project development branch) to + contain your feature, change, or fix: + + ```bash + git checkout -b + ``` + +4. Commit your changes in logical chunks. Please adhere to these [git commit + message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) + or your code is unlikely be merged into the main project. Use Git's + [interactive rebase](https://help.github.com/articles/interactive-rebase) + feature to tidy up your commits before making them public. + +5. Locally merge (or rebase) the upstream development branch into your topic branch: + + ```bash + git pull [--rebase] upstream + ``` + +6. Push your topic branch up to your fork: + + ```bash + git push origin + ``` + +7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) + with a clear title and description. + +**IMPORTANT**: By submitting a patch, you agree to allow the project owner to +license your work under the same license as that used by the project. diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..26c36da --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,30 @@ +module.exports = function (grunt) { + 'use strict'; + + require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); + + grunt.initConfig({ + bump: { + options: { + files: [ + 'package.json', + 'bower.json' + ], + commit: true, + commitMessage: 'v%VERSION%', + commitFiles: ['-a'], + createTag: true, + tagName: 'v%VERSION%', + tagMessage: 'v%VERSION%', + push: true, + pushTo: 'origin', + gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' + } + }, + coveralls: { + options: { + 'coverage_dir': 'coverage' + } + } + }); +}; diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..39d1fa3 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,19 @@ +Copyright (c) 2014 Björn Andersson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..64d4aed --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# flight-scrollspy + +[![Build Status](https://travis-ci.org/gaqzi/flight-scrollspy.png)](http://travis-ci.org/gaqzi/flight-scrollspy) +[![Coverage Status](https://coveralls.io/repos/gaqzi/flight-scrollspy/badge.png)](https://coveralls.io/r/gaqzi/flight-scrollspy) + +A [Flight](https://github.com/flightjs/flight) component for +triggering events when an element is scrolled into view. + +This component was originally built to be able to handle infinity scroll. + +## Installation + +```bash +bower install --save flight-scrollspy +``` + +## Example + +```js +define(function(require) { + 'use strict'; + + var scrollSpy = require('flight-scrollspy/lib/scrollspy'); + + return page; + + function page() { + scrollSpy.attachTo('body', { + throttle: 200 // ms, the default is 100ms. + }); + } +}); + +define(function(require) { + var defineComponent = require('flight/lib/component'), + withSpy = require('flight-scrollspy/lib/with_spy'); + + return defineComponent(infiniteScroll, withSpy); + + function infiniteScroll() { + this.fetchMoreComments = function( { ... }; + + this.after('initialize', function() { + this.addSpy('.last-comment', {once: true}) + this.on('uiSpied', this.fetchMoreComments); + + // this.removeSpy('.last-comment'); + }); + } +}); +``` + +## Events + +* `uiScrolled` all the positions of the node element. Top, right, bottom and left +* `uiSpied` when a target element is seen within the viewport +* `addedSpy` when a new spy target is added +* `removedSpy` when a spy target is removed +* `spiesRefreshed` when the spies offsets has been updated after a window resize + +## Development + +Development of this component requires [Bower](http://bower.io) to be globally +installed: + +```bash +npm install -g bower +``` + +Then install the Node.js and client-side dependencies by running the following +commands in the repo's root directory. + +```bash +npm install & bower install flight-scrollspy +``` + +To continuously run the tests in Chrome during development, just run: + +```bash +npm run watch-test +``` + +## Contributing to this project + +Anyone and everyone is welcome to contribute. Please take a moment to +review the [guidelines for contributing](CONTRIBUTING.md). + +* [Bug reports](CONTRIBUTING.md#bugs) +* [Feature requests](CONTRIBUTING.md#features) +* [Pull requests](CONTRIBUTING.md#pull-requests) diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..fbd81ef --- /dev/null +++ b/bower.json @@ -0,0 +1,22 @@ +{ + "name": "flight-scrollspy", + "version": "1.0.0-alpha", + "main": "lib/scrollspy.js", + "dependencies": { + "flight": "~1.1.0" + }, + "devDependencies": { + "jasmine-flight": "~2.2.0" + }, + "ignore": [ + ".gitignore", + ".gitattributes", + ".travis.yml", + "CONTRIBUTING.md", + "CHANGELOG.md", + "test", + "package.json", + "karma.conf.js", + "Gruntfile.js" + ] +} diff --git a/karma.conf.js b/karma.conf.js new file mode 100644 index 0000000..5eda567 --- /dev/null +++ b/karma.conf.js @@ -0,0 +1,89 @@ +// Karma configuration file +// +// For all available config options and default values, see: +// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54 + +module.exports = function (config) { + 'use strict'; + + config.set({ + // base path, that will be used to resolve files and exclude + basePath: '', + + frameworks: [ + 'jasmine' + ], + + // list of files / patterns to load in the browser + files: [ + // loaded without require + 'bower_components/es5-shim/es5-shim.js', + 'bower_components/es5-shim/es5-sham.js', + 'bower_components/jquery/dist/jquery.js', + 'bower_components/jasmine-jquery/lib/jasmine-jquery.js', + 'bower_components/jasmine-flight/lib/jasmine-flight.js', + + // hack to load RequireJS after the shim libs + 'node_modules/karma-requirejs/lib/require.js', + 'node_modules/karma-requirejs/lib/adapter.js', + + // loaded with require + {pattern: 'bower_components/flight/**/*.js', included: false}, + {pattern: 'lib/**/*.js', included: false}, + {pattern: 'test/fixtures/**/*.html', included: false}, + {pattern: 'test/spec/**/*.spec.js', included: false}, + + 'test/test-main.js' + ], + + preprocessors: { + 'lib/*.js': ['coverage'] + }, + + // use dots reporter, as travis terminal does not support escaping sequences + // possible values: 'dots', 'progress' + // CLI --reporters progress + reporters: ['progress', 'coverage'], + + // enable / disable watching file and executing tests whenever any file changes + // CLI --auto-watch --no-auto-watch + autoWatch: true, + + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + // CLI --browsers Chrome, Firefox, Safari + browsers: [ + 'Chrome' + ], + + // If browser does not capture in given timeout [ms], kill it + // CLI --capture-timeout 5000 + captureTimeout: 20000, + + // Auto run tests on start (when browsers are captured) and exit + // CLI --single-run --no-single-run + singleRun: false, + + coverageReporter: { + type : 'lcov', + dir : 'coverage/' + }, + + plugins: [ + 'karma-jasmine', + 'karma-requirejs', + 'karma-coverage', + 'karma-chrome-launcher', + 'karma-firefox-launcher', + 'karma-ie-launcher', + 'karma-phantomjs-launcher', + 'karma-safari-launcher' + ] + }); +}; diff --git a/lib/scrollspy.js b/lib/scrollspy.js new file mode 100644 index 0000000..d696854 --- /dev/null +++ b/lib/scrollspy.js @@ -0,0 +1,47 @@ +define(function (require) { + + 'use strict'; + + var defineComponent = require('flight/lib/component'), + utils = require('flight/lib/utils'); + + return defineComponent(scrollSpy); + + /** + * Whenever a scroll occurs on the target element trigger + * `uiScrolled`, as long as it has bee `throttle` ms since last time + * the event was triggered. + * + * Options: + * throttle: How long min between scroll events. Default: 100ms. + * + * @fires uiScrolled + */ + function scrollSpy() { + this.defaultAttrs({ + throttle: 100 + }); + + this._triggerScroll = function() { + var top = this.$node.scrollTop(), + left = this.$node.scrollLeft(); + + this.trigger('uiScrolled', { + top: top, + bottom: top + this.$node.height(), + left: left, + right: left + this.$node.width() + }); + }; + + this.after('initialize', function() { + this.triggerScroll = utils.throttle( + this._triggerScroll, + this.attr.throttle + ); + + this.on('scroll', this.triggerScroll); + }); + } + +}); diff --git a/lib/with_spy.js b/lib/with_spy.js new file mode 100644 index 0000000..5dfc69c --- /dev/null +++ b/lib/with_spy.js @@ -0,0 +1,185 @@ +define(function() { + 'use strict'; + + return withSpy; + + function withSpy() { + var spyAttached = false, + scrollEventName = 'uiScrolled', + spiedEventName = 'uiSpied'; + + /** + * A spy is attached to a selector, whenever a scroll event occurs + * and the selector is in view a 'uiSped' event will be triggered. + * + * You can only attach one spy at a time and if the selector + * returns multiple hits the first match will be used. If you need + * to refresh the position of the target for the selector just + * addSpy again for the same selector and the old one will be + * replaced with the new. Note: it will not remember options + * between calls to addSpy. + * + * Valid options: + * - once: will only trigger this event once. + * + * @fires addedSpy when successfully adding a spy + * @fires uiSpied when a target element is in the viewport + * @param {String} selector a jQuery selector + * @param {Object} options + * @returns {Boolean} wheter spy was added successfully or not. + */ + this.addSpy = function(selector, options) { + options = options || {}; + + var el = this.$node.find(selector), + offset = getElementOffset(el); + + if(offset) { + this._addSpyTarget(selector, options, offset); + this.trigger('addedSpy', {selector: selector}); + + return true; + } + + return false; + }; + + /** + * Removes the selector from being spied upon. + * + * @param {String} selector a jQuery selector + * @fires removedSpy + */ + this.removeSpy = function(selector) { + this._removeSpyTarget(selector); + this.trigger('removedSpy', {selector: selector}); + }; + + // This is silly, I'm declaring this on its own to silence jsHint + var spyTargets = { + selectors: {}, + handlers: 0, + once: [] + }; + + function getElementOffset(el) { + var offset = el.offset(); + + if(offset) { + offset.bottom = offset.top + el.height(); + offset.right = offset.left + el.width(); + } + + return offset; + } + + this._addSpyTarget = function(selector, options, offset) { + if(spyTargets.selectors[selector] !== undefined) { + this._removeSpyTarget(selector); + } + + spyTargets.selectors[selector] = offset; + spyTargets.handlers++; + if(options.once) { + spyTargets.once.push(selector); + } + + if(!spyAttached) { + this.on(scrollEventName, _spyHandler); + this.on(window, 'resize', _onWindowResize); + spyAttached = true; + } + }; + + this._removeSpyTarget = function(selector) { + delete spyTargets.selectors[selector]; + spyTargets.handlers--; + var oncePos = spyTargets.once.indexOf(selector); + if(oncePos > -1) { + spyTargets.once.splice(oncePos, 1); + } + + if(spyTargets.handlers <= 0 && spyAttached) { + this.off(document, scrollEventName, _spyHandler); + this.off(window, 'resize', _onWindowResize); + } + }; + + // Finds all selectors that is within the given the bounds for + // the searchSpace (horizontal/vertical). + function _find(searchSpace, min, max) { + var l = spyTargets, + all = []; + + for(var selector in l.selectors) { + var target = l.selectors[selector], + firstPos = parseInt(target[searchSpace[0]], 10), + secondPos = parseInt(target[searchSpace[1]], 10); + + // top >= top of the browser window && + // (top <= bottom of the browser window || bottom <= bottom) + // || + // bottom >= top of the browser window && + // (bottom <= bottom of the browser window || top <= bottom + if((firstPos >= min && (firstPos <= max || secondPos <= max)) || + secondPos >= min && (secondPos <= max || firstPos <= max)) { + all.push(selector); + } + } + + return all; + } + + // Any elements that is to any extent visible in the viewport? + function _spyHandler(e, data) { + var top = _find(['top', 'bottom'], data.top, data.bottom), + left = _find(['left', 'right'], data.left, data.right), + triggered = [], + max = top.length; + + if(!(top.length > 0 && left.length > 0)) { + return; + } + + for(var i=0;max > i;i++) { + var selector = top[i]; + + if(triggered.indexOf(selector) === -1 && + left.indexOf(selector) !== -1) { + triggered.push(selector); + this.$node.find(selector).trigger(spiedEventName, selector); + + if(spyTargets.once.indexOf(selector) > -1) { + this.removeSpy(selector); + } + } + } + } + + // This one is not as automatically tested as I would've + // wanted. But I can't resize the window programatically. + function _onWindowResize() { + var refreshed = []; + for(var selector in spyTargets.selectors) { + var options = {}; + if(spyTargets.once.indexOf(selector) > -1) { + options.once = true; + } + + var el = this.$node.find(selector), + offset = getElementOffset(el); + + if(offset) { + this._addSpyTarget(selector, options, getElementOffset(el)); + refreshed.push(selector); + } else { + this.removeSpy(selector); + } + } + + if(refreshed.length > 0) { + this.trigger('spiesRefreshed', {targets: refreshed}); + } + } + } +}); diff --git a/package.json b/package.json new file mode 100644 index 0000000..1ccf81f --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "flight-scrollspy", + "version": "1.0.0-alpha", + "devDependencies": { + "grunt": "~0.4.1", + "grunt-bump": "latest", + "karma": "~0.10.0", + "karma-jasmine": "~0.1.0", + "karma-requirejs": "~0.1.0", + "karma-chrome-launcher": "~0.1.0", + "karma-ie-launcher": "~0.1.1", + "karma-firefox-launcher": "~0.1.0", + "karma-phantomjs-launcher": "~0.1.0", + "karma-safari-launcher": "~0.1.1", + "matchdep": "latest", + "grunt-karma-coveralls": "~2.4.0", + "karma-coverage": "~0.2.0" + }, + "scripts": { + "test": "karma start --single-run --reporters dots,coverage --browsers PhantomJS", + "watch-test": "karma start" + } +} diff --git a/test/fixtures/scrollspy.html b/test/fixtures/scrollspy.html new file mode 100644 index 0000000..76b2f66 --- /dev/null +++ b/test/fixtures/scrollspy.html @@ -0,0 +1,7 @@ +
+
+
+
+ +
+
diff --git a/test/spec/scrollspy.spec.js b/test/spec/scrollspy.spec.js new file mode 100644 index 0000000..acd9902 --- /dev/null +++ b/test/spec/scrollspy.spec.js @@ -0,0 +1,30 @@ +'use strict'; + +describeComponent('lib/scrollspy', function () { + + // Initialize the component and attach it to the DOM + beforeEach(function () { + setupComponent(readFixtures('scrollspy.html')); + }); + + it('should trigger uiScrolled when the target element scrolls', function() { + var eventSpy = spyOnEvent(document, 'uiScrolled'); + this.$node.scroll(); + + expect(eventSpy.mostRecentCall.data).toEqual({ + top: 0, + bottom: 100, + left: 0, + right: 100 + }); + }); + + it('should only trigger uiScrolled once every "throttle" ms', function() { + var eventSpy = spyOnEvent(document, 'uiScrolled'); + this.$node.scroll(); + this.$node.scroll(); + + expect(eventSpy.callCount).toBe(1); + }); + +}); diff --git a/test/spec/with_spy.spec.js b/test/spec/with_spy.spec.js new file mode 100644 index 0000000..59d1b63 --- /dev/null +++ b/test/spec/with_spy.spec.js @@ -0,0 +1,139 @@ +'use strict'; + +describeMixin('lib/with_spy', function () { + var addedEventSpy, + removedEventSpy, + spiedEventSpy; + var scrollDataMiss = { + top: 0, + left: 0, + bottom: 100, + right: 100 + }; + var scrollDataHit = { + top: 150, + left: 150, + bottom: 200, + right: 200 + }; + beforeEach(function () { + setupComponent(readFixtures('scrollspy.html')); + addedEventSpy = spyOnEvent(document, 'addedSpy'); + removedEventSpy = spyOnEvent(document, 'removedSpy'); + spiedEventSpy = spyOnEvent(document, 'uiSpied'); + }); + + it('should register a new spy for a valid selector', function() { + expect(this.component.addSpy('.target')).toBe(true); + expect(addedEventSpy.callCount).toBe(1); + }); + + it('should not register a new spy for an invalid selector', function() { + expect(this.component.addSpy('.invalid')).toBe(false); + expect(addedEventSpy.callCount).toBe(0); + }); + + it('should trigger removed event when spy is removed', function() { + this.component.addSpy('.target'); + this.component.removeSpy('.target'); + + expect(addedEventSpy.callCount).toBe(1); + expect(removedEventSpy.callCount).toBe(1); + }); + + it('should trigger on every uiScrolled and target is seen', function() { + this.component.addSpy('.target'); + this.component.trigger('uiScrolled', scrollDataHit); + this.component.trigger('uiScrolled', scrollDataHit); + + expect(spiedEventSpy.callCount).toBe(2); + expect(spiedEventSpy.mostRecentCall.data).toEqual('.target'); + }); + + it('should only trigger once when added with option "once"', function() { + expect(this.component.addSpy('.target', {once: true})).toBe(true); + + this.component.trigger('uiScrolled', scrollDataHit); + this.component.trigger('uiScrolled', scrollDataHit); + + expect(spiedEventSpy.callCount).toBe(1); + expect(removedEventSpy.callCount).toBe(1); + }); + + it('should not trigger uiScrolled when no targets found', function() { + this.component.addSpy('.target'); + this.component.trigger('uiScrolled', scrollDataMiss); + + expect(spiedEventSpy.callCount).toBe(0); + }); + + it('should attachable to several targets at once', function() { + this.component.addSpy('.target'); + this.component.addSpy('.inner'); + + expect(addedEventSpy.callCount).toBe(2); + }); + + it('should trigger uiScrolled for both when both visible', function() { + this.component.addSpy('.target'); + this.component.addSpy('.inner'); + + this.component.trigger('uiScrolled', scrollDataHit); + expect(spiedEventSpy.callCount).toBe(2); + }); + + it('should trigger uiScrolled for one when not all visible', function() { + this.component.addSpy('.target'); + this.component.addSpy('.inner'); + this.component.addSpy('.impossible-target'); + + this.component.trigger('uiScrolled', scrollDataMiss); + expect(spiedEventSpy.callCount).toBe(1); + }); + + describe('should refresh element offsets on window resize', function() { + it('should do it successfully', function() { + this.component.addSpy('.target'); + var eventSpy = spyOnEvent(document, 'spiesRefreshed'); + + $(window).resize(); + + expect(eventSpy.callCount).toBe(1); + expect(eventSpy.mostRecentCall.data).toEqual({targets: ['.target']}); + }); + + it('should honor once', function() { + this.component.addSpy('.target', {once: true}); + var eventSpy = spyOnEvent(document, 'spiesRefreshed'); + + $(window).resize(); + + expect(eventSpy.callCount).toBe(1); + expect(eventSpy.mostRecentCall.data).toEqual({targets: ['.target']}); + + this.component.trigger('uiScrolled', scrollDataHit); + expect(removedEventSpy.callCount).toBe(1); + }); + + it('should remove elements which has been removed from the page', function() { + this.component.addSpy('.target'); + this.component.addSpy('.inner'); + this.component.$node.find('.target').remove(); + + var eventSpy = spyOnEvent(document, 'spiesRefreshed'); + + $(window).resize(); + + expect(eventSpy.callCount).toBe(1); + expect(removedEventSpy.callCount).toBe(1); + }); + + it('should not refresh if there is no elements to refresh', function() { + var eventSpy = spyOnEvent(document, 'spiesRefreshed'); + + $(window).resize(); + + expect(eventSpy.callCount).toBe(0); + }); + }); +}); diff --git a/test/test-main.js b/test/test-main.js new file mode 100644 index 0000000..a039fd1 --- /dev/null +++ b/test/test-main.js @@ -0,0 +1,22 @@ +'use strict'; + +var tests = Object.keys(window.__karma__.files).filter(function (file) { + return (/\.spec\.js$/.test(file)); +}); + +requirejs.config({ + // Karma serves files from '/base' + baseUrl: '/base', + + paths: { + 'flight': 'bower_components/flight' + }, + + // ask Require.js to load these files (all our tests) + deps: tests, + + // start test run, once Require.js is done + callback: window.__karma__.start +}); + +jasmine.getFixtures().fixturesPath = 'base/test/fixtures';