diff --git a/app/assets/article.scss b/app/assets/article.scss index 30cfd2f..9488104 100644 --- a/app/assets/article.scss +++ b/app/assets/article.scss @@ -3,7 +3,7 @@ article { padding-bottom: 1em; padding-left: 1em; - @include column(6); + width: 50%; @include box-sizing(border-box); &.hidden { @@ -65,6 +65,14 @@ article { margin-bottom: 1em; } + pre { + word-wrap: nowrap; + white-space: pre; + background-color: $darker_brown; + color: #fff; + overflow-x: auto; + } + code { font-size: 95%; font-family: 'Source Code Pro' Sans-Serif; diff --git a/app/views/aggregator/index.html.haml b/app/views/aggregator/index.html.haml index 4df9597..60b7d79 100644 --- a/app/views/aggregator/index.html.haml +++ b/app/views/aggregator/index.html.haml @@ -1,6 +1,6 @@ %script{type: 'text/html', id: 'article_tmpl'} :plain -
+

<%=title%> diff --git a/config/jammit.yml b/config/jammit.yml index a07648e..a49d442 100644 --- a/config/jammit.yml +++ b/config/jammit.yml @@ -7,6 +7,8 @@ javascripts: aggregator: - public/js/jquery-1.8.1.js - public/js/underscore.js + - public/js/masonry.js + - public/js/images_loaded.js - public/js/aggregator/article.js - public/js/aggregator/feed.js - public/js/aggregator/service.js diff --git a/public/js/aggregator/articles_view.js b/public/js/aggregator/articles_view.js index 2f7676b..53267f4 100644 --- a/public/js/aggregator/articles_view.js +++ b/public/js/aggregator/articles_view.js @@ -3,16 +3,32 @@ var SMF = SMF || {}; SMF.ArticlesView = function() { this.$el = $('#articles'); this.template = $('#article_tmpl').html(); + this.masonry = new Masonry(document.querySelector("#articles"), {itemSelecotr: "article"}); + this.articleElements = null; }; SMF.ArticlesView.prototype = { render: function() { var self = this; - this.$el.html(''); + + var $articles = $("article", self.$el); + if ($articles.length > 0) { + this.masonry.remove($articles); + $articles.remove(); + } _(this.articles).each(function(article) { var renderedArticle = _.template(self.template, article); self.$el.append(renderedArticle); }); + + var $articles = $("article", self.$el); + + this.$el.imagesLoaded(function() { + setTimeout(function() { + self.masonry.appended($articles); + self.masonry.layout(); + }, 800); + }); } }; diff --git a/public/js/images_loaded.js b/public/js/images_loaded.js new file mode 100644 index 0000000..ad6b37e --- /dev/null +++ b/public/js/images_loaded.js @@ -0,0 +1,744 @@ +/*! + * imagesLoaded PACKAGED v3.0.2 + * JavaScript is all like "You images are done yet or what?" + */ + +/*! + * EventEmitter v4.1.0 - git.io/ee + * Oliver Caldwell + * MIT license + * @preserve + */ + +(function (exports) { + // Place the script in strict mode + 'use strict'; + + /** + * Class for managing events. + * Can be extended to provide event functionality in other classes. + * + * @class Manages event registering and emitting. + */ + function EventEmitter() {} + + // Shortcuts to improve speed and size + + // Easy access to the prototype + var proto = EventEmitter.prototype, + nativeIndexOf = Array.prototype.indexOf ? true : false; + + /** + * Finds the index of the listener for the event in it's storage array. + * + * @param {Function} listener Method to look for. + * @param {Function[]} listeners Array of listeners to search through. + * @return {Number} Index of the specified listener, -1 if not found + * @api private + */ + function indexOfListener(listener, listeners) { + // Return the index via the native method if possible + if (nativeIndexOf) { + return listeners.indexOf(listener); + } + + // There is no native method + // Use a manual loop to find the index + var i = listeners.length; + while (i--) { + // If the listener matches, return it's index + if (listeners[i] === listener) { + return i; + } + } + + // Default to returning -1 + return -1; + } + + /** + * Fetches the events object and creates one if required. + * + * @return {Object} The events storage object. + * @api private + */ + proto._getEvents = function () { + return this._events || (this._events = {}); + }; + + /** + * Returns the listener array for the specified event. + * Will initialise the event object and listener arrays if required. + * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. + * Each property in the object response is an array of listener functions. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Function[]|Object} All listener functions for the event. + */ + proto.getListeners = function (evt) { + // Create a shortcut to the storage object + // Initialise it if it does not exists yet + var events = this._getEvents(), + response, + key; + + // Return a concatenated array of all matching events if + // the selector is a regular expression. + if (typeof evt === 'object') { + response = {}; + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + response[key] = events[key]; + } + } + } + else { + response = events[evt] || (events[evt] = []); + } + + return response; + }; + + /** + * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Object} All listener functions for an event in an object. + */ + proto.getListenersAsObject = function (evt) { + var listeners = this.getListeners(evt), + response; + + if (listeners instanceof Array) { + response = {}; + response[evt] = listeners; + } + + return response || listeners; + }; + + /** + * Adds a listener function to the specified event. + * The listener will not be added if it is a duplicate. + * If the listener returns true then it will be removed after it is called. + * If you pass a regular expression as the event name then the listener will be added to all events that match it. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListener = function (evt, listener) { + var listeners = this.getListenersAsObject(evt), + key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key) && + indexOfListener(listener, listeners[key]) === -1) { + listeners[key].push(listener); + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of addListener + */ + proto.on = proto.addListener; + + /** + * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. + * You need to tell it what event names should be matched by a regex. + * + * @param {String} evt Name of the event to create. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvent = function (evt) { + this.getListeners(evt); + return this; + }; + + /** + * Uses defineEvent to define multiple events. + * + * @param {String[]} evts An array of event names to define. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvents = function (evts) + { + for (var i = 0; i < evts.length; i += 1) { + this.defineEvent(evts[i]); + } + return this; + }; + + /** + * Removes a listener function from the specified event. + * When passed a regular expression as the event name, it will remove the listener from all events that match it. + * + * @param {String|RegExp} evt Name of the event to remove the listener from. + * @param {Function} listener Method to remove from the event. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListener = function (evt, listener) { + var listeners = this.getListenersAsObject(evt), + index, + key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + index = indexOfListener(listener, listeners[key]); + + if (index !== -1) { + listeners[key].splice(index, 1); + } + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of removeListener + */ + proto.off = proto.removeListener; + + /** + * Adds listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. + * You can also pass it a regular expression to add the array of listeners to all events that match it. + * Yeah, this function does quite a bit. That's probably a bad thing. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListeners = function (evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(false, evt, listeners); + }; + + /** + * Removes listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be removed. + * You can also pass it a regular expression to remove the listeners from all events that match it. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListeners = function (evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(true, evt, listeners); + }; + + /** + * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. + * The first argument will determine if the listeners are removed (true) or added (false). + * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be added/removed. + * You can also pass it a regular expression to manipulate the listeners of all events that match it. + * + * @param {Boolean} remove True if you want to remove listeners, false if you want to add. + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add/remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.manipulateListeners = function (remove, evt, listeners) { + // Initialise any required variables + var i, + value, + single = remove ? this.removeListener : this.addListener, + multiple = remove ? this.removeListeners : this.addListeners; + + // If evt is an object then pass each of it's properties to this method + if (typeof evt === 'object' && !(evt instanceof RegExp)) { + for (i in evt) { + if (evt.hasOwnProperty(i) && (value = evt[i])) { + // Pass the single listener straight through to the singular method + if (typeof value === 'function') { + single.call(this, i, value); + } + else { + // Otherwise pass back to the multiple function + multiple.call(this, i, value); + } + } + } + } + else { + // So evt must be a string + // And listeners must be an array of listeners + // Loop over it and pass each one to the multiple method + i = listeners.length; + while (i--) { + single.call(this, evt, listeners[i]); + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Removes all listeners from a specified event. + * If you do not specify an event then all listeners will be removed. + * That means every event will be emptied. + * You can also pass a regex to remove all events that match it. + * + * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeEvent = function (evt) { + var type = typeof evt, + events = this._getEvents(), + key; + + // Remove different things depending on the state of evt + if (type === 'string') { + // Remove all listeners for the specified event + delete events[evt]; + } + else if (type === 'object') { + // Remove all events matching the regex. + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + delete events[key]; + } + } + } + else { + // Remove all listeners in all events + delete this._events; + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Emits an event of your choice. + * When emitted, every listener attached to that event will be executed. + * If you pass the optional argument array then those arguments will be passed to every listener upon execution. + * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. + * So they will not arrive within the array on the other side, they will be separate. + * You can also pass a regular expression to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {Array} [args] Optional array of arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emitEvent = function (evt, args) { + var listeners = this.getListenersAsObject(evt), + i, + key, + response; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + i = listeners[key].length; + + while (i--) { + // If the listener returns true then it shall be removed from the event + // The function is executed either with a basic call or an apply if there is an args array + response = args ? listeners[key][i].apply(null, args) : listeners[key][i](); + if (response === true) { + this.removeListener(evt, listeners[key][i]); + } + } + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of emitEvent + */ + proto.trigger = proto.emitEvent; + + /** + * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. + * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {...*} Optional additional arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emit = function (evt) { + var args = Array.prototype.slice.call(arguments, 1); + return this.emitEvent(evt, args); + }; + + // Expose the class either via AMD or the global object + if (typeof define === 'function' && define.amd) { + define(function () { + return EventEmitter; + }); + } + else { + exports.EventEmitter = EventEmitter; + } +}(this)); +/*! + * eventie v1.0.3 + * event binding helper + * eventie.bind( elem, 'click', myFn ) + * eventie.unbind( elem, 'click', myFn ) + */ + +/*jshint browser: true, undef: true, unused: true */ +/*global define: false */ + +( function( window ) { + +'use strict'; + +var docElem = document.documentElement; + +var bind = function() {}; + +if ( docElem.addEventListener ) { + bind = function( obj, type, fn ) { + obj.addEventListener( type, fn, false ); + }; +} else if ( docElem.attachEvent ) { + bind = function( obj, type, fn ) { + obj[ type + fn ] = fn.handleEvent ? + function() { + var event = window.event; + // add event.target + event.target = event.target || event.srcElement; + fn.handleEvent.call( fn, event ); + } : + function() { + var event = window.event; + // add event.target + event.target = event.target || event.srcElement; + fn.call( obj, event ); + }; + obj.attachEvent( "on" + type, obj[ type + fn ] ); + }; +} + +var unbind = function() {}; + +if ( docElem.removeEventListener ) { + unbind = function( obj, type, fn ) { + obj.removeEventListener( type, fn, false ); + }; +} else if ( docElem.detachEvent ) { + unbind = function( obj, type, fn ) { + obj.detachEvent( "on" + type, obj[ type + fn ] ); + try { + delete obj[ type + fn ]; + } catch ( err ) { + // can't delete window object properties + obj[ type + fn ] = undefined; + } + }; +} + +var eventie = { + bind: bind, + unbind: unbind +}; + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( eventie ); +} else { + // browser global + window.eventie = eventie; +} + +})( this ); + +/*! + * imagesLoaded v3.0.2 + * JavaScript is all like "You images are done yet or what?" + */ + +( function( window ) { + +'use strict'; + +var $ = window.jQuery; +var console = window.console; +var hasConsole = typeof console !== 'undefined'; + +// -------------------------- helpers -------------------------- // + +// extend objects +function extend( a, b ) { + for ( var prop in b ) { + a[ prop ] = b[ prop ]; + } + return a; +} + +var objToString = Object.prototype.toString; +function isArray( obj ) { + return objToString.call( obj ) === '[object Array]'; +} + +// turn element or nodeList into an array +function makeArray( obj ) { + var ary = []; + if ( isArray( obj ) ) { + // use object if already an array + ary = obj; + } else if ( typeof obj.length === 'number' ) { + // convert nodeList to array + for ( var i=0, len = obj.length; i < len; i++ ) { + ary.push( obj[i] ); + } + } else { + // array of single index + ary.push( obj ); + } + return ary; +} + +// -------------------------- -------------------------- // + +function defineImagesLoaded( EventEmitter, eventie ) { + + /** + * @param {Array, Element, NodeList, String} elem + * @param {Object or Function} options - if function, use as callback + * @param {Function} onAlways - callback function + */ + function ImagesLoaded( elem, options, onAlways ) { + // coerce ImagesLoaded() without new, to be new ImagesLoaded() + if ( !( this instanceof ImagesLoaded ) ) { + return new ImagesLoaded( elem, options ); + } + // use elem as selector string + if ( typeof elem === 'string' ) { + elem = document.querySelectorAll( elem ); + } + + this.elements = makeArray( elem ); + this.options = extend( {}, this.options ); + + if ( typeof options === 'function' ) { + onAlways = options; + } else { + extend( this.options, options ); + } + + if ( onAlways ) { + this.on( 'always', onAlways ); + } + + this.getImages(); + + if ( $ ) { + // add jQuery Deferred object + this.jqDeferred = new $.Deferred(); + } + + // HACK check async to allow time to bind listeners + var _this = this; + setTimeout( function() { + _this.check(); + }); + } + + ImagesLoaded.prototype = new EventEmitter(); + + ImagesLoaded.prototype.options = {}; + + ImagesLoaded.prototype.getImages = function() { + this.images = []; + + // filter & find items if we have an item selector + for ( var i=0, len = this.elements.length; i < len; i++ ) { + var elem = this.elements[i]; + // filter siblings + if ( elem.nodeName === 'IMG' ) { + this.addImage( elem ); + } + // find children + var childElems = elem.querySelectorAll('img'); + // concat childElems to filterFound array + for ( var j=0, jLen = childElems.length; j < jLen; j++ ) { + var img = childElems[j]; + this.addImage( img ); + } + } + }; + + /** + * @param {Image} img + */ + ImagesLoaded.prototype.addImage = function( img ) { + var loadingImage = new LoadingImage( img ); + this.images.push( loadingImage ); + }; + + ImagesLoaded.prototype.check = function() { + var _this = this; + var checkedCount = 0; + var length = this.images.length; + this.hasAnyBroken = false; + // complete if no images + if ( !length ) { + this.complete(); + return; + } + + function onConfirm( image, message ) { + if ( _this.options.debug && hasConsole ) { + console.log( 'confirm', image, message ); + } + + _this.progress( image ); + checkedCount++; + if ( checkedCount === length ) { + _this.complete(); + } + return true; // bind once + } + + for ( var i=0; i < length; i++ ) { + var loadingImage = this.images[i]; + loadingImage.on( 'confirm', onConfirm ); + loadingImage.check(); + } + }; + + ImagesLoaded.prototype.progress = function( image ) { + this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded; + this.emit( 'progress', this, image ); + if ( this.jqDeferred ) { + this.jqDeferred.notify( this, image ); + } + }; + + ImagesLoaded.prototype.complete = function() { + var eventName = this.hasAnyBroken ? 'fail' : 'done'; + this.isComplete = true; + this.emit( eventName, this ); + this.emit( 'always', this ); + if ( this.jqDeferred ) { + var jqMethod = this.hasAnyBroken ? 'reject' : 'resolve'; + this.jqDeferred[ jqMethod ]( this ); + } + }; + + // -------------------------- jquery -------------------------- // + + if ( $ ) { + $.fn.imagesLoaded = function( options, callback ) { + var instance = new ImagesLoaded( this, options, callback ); + return instance.jqDeferred.promise( $(this) ); + }; + } + + + // -------------------------- -------------------------- // + + var cache = {}; + + function LoadingImage( img ) { + this.img = img; + } + + LoadingImage.prototype = new EventEmitter(); + + LoadingImage.prototype.check = function() { + // first check cached any previous images that have same src + var cached = cache[ this.img.src ]; + if ( cached ) { + this.useCached( cached ); + return; + } + // add this to cache + cache[ this.img.src ] = this; + + // If complete is true and browser supports natural sizes, + // try to check for image status manually. + if ( this.img.complete && this.img.naturalWidth !== undefined ) { + // report based on naturalWidth + this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' ); + return; + } + + // If none of the checks above matched, simulate loading on detached element. + var proxyImage = this.proxyImage = new Image(); + eventie.bind( proxyImage, 'load', this ); + eventie.bind( proxyImage, 'error', this ); + proxyImage.src = this.img.src; + }; + + LoadingImage.prototype.useCached = function( cached ) { + if ( cached.isConfirmed ) { + this.confirm( cached.isLoaded, 'cached was confirmed' ); + } else { + var _this = this; + cached.on( 'confirm', function( image ) { + _this.confirm( image.isLoaded, 'cache emitted confirmed' ); + return true; // bind once + }); + } + }; + + LoadingImage.prototype.confirm = function( isLoaded, message ) { + this.isConfirmed = true; + this.isLoaded = isLoaded; + this.emit( 'confirm', this, message ); + }; + + // trigger specified handler for event type + LoadingImage.prototype.handleEvent = function( event ) { + var method = 'on' + event.type; + if ( this[ method ] ) { + this[ method ]( event ); + } + }; + + LoadingImage.prototype.onload = function() { + this.confirm( true, 'onload' ); + this.unbindProxyEvents(); + }; + + LoadingImage.prototype.onerror = function() { + this.confirm( false, 'onerror' ); + this.unbindProxyEvents(); + }; + + LoadingImage.prototype.unbindProxyEvents = function() { + eventie.unbind( this.proxyImage, 'load', this ); + eventie.unbind( this.proxyImage, 'error', this ); + }; + + // ----- ----- // + + return ImagesLoaded; +} + +// -------------------------- transport -------------------------- // + +if ( typeof define === 'function' && define.amd ) { + // AMD + define( [ + 'eventEmitter', + 'eventie' + ], + defineImagesLoaded ); +} else { + // browser global + window.imagesLoaded = defineImagesLoaded( + window.EventEmitter, + window.eventie + ); +} + +})( window ); diff --git a/public/js/masonry.js b/public/js/masonry.js new file mode 100644 index 0000000..41e1ad1 --- /dev/null +++ b/public/js/masonry.js @@ -0,0 +1,2547 @@ +/*! + * Masonry PACKAGED v3.0.1 + * Cascading grid layout library + * http://masonry.desandro.com + * MIT License + * by David DeSandro + */ + +/*! + * getStyleProperty by kangax + * http://perfectionkills.com/feature-testing-css-properties/ + */ + +/*jshint browser: true, strict: true, undef: true */ +/*globals define: false */ + +( function( window ) { + +'use strict'; + +var prefixes = 'Webkit Moz ms Ms O'.split(' '); +var docElemStyle = document.documentElement.style; + +function getStyleProperty( propName ) { + if ( !propName ) { + return; + } + + // test standard property first + if ( typeof docElemStyle[ propName ] === 'string' ) { + return propName; + } + + // capitalize + propName = propName.charAt(0).toUpperCase() + propName.slice(1); + + // test vendor specific properties + var prefixed; + for ( var i=0, len = prefixes.length; i < len; i++ ) { + prefixed = prefixes[i] + propName; + if ( typeof docElemStyle[ prefixed ] === 'string' ) { + return prefixed; + } + } +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( function() { + return getStyleProperty; + }); +} else { + // browser global + window.getStyleProperty = getStyleProperty; +} + +})( window ); + +/** + * getSize v1.1.3 + * measure size of elements + */ + +/*jshint browser: true, strict: true, undef: true, unused: true */ +/*global define: false */ + +( function( window, undefined ) { + +'use strict'; + +// -------------------------- helpers -------------------------- // + +var defView = document.defaultView; + +var getStyle = defView && defView.getComputedStyle ? + function( elem ) { + return defView.getComputedStyle( elem, null ); + } : + function( elem ) { + return elem.currentStyle; + }; + +// get a number from a string, not a percentage +function getStyleSize( value ) { + var num = parseFloat( value ); + // not a percent like '100%', and a number + var isValid = value.indexOf('%') === -1 && !isNaN( num ); + return isValid && num; +} + +// -------------------------- measurements -------------------------- // + +var measurements = [ + 'paddingLeft', + 'paddingRight', + 'paddingTop', + 'paddingBottom', + 'marginLeft', + 'marginRight', + 'marginTop', + 'marginBottom', + 'borderLeftWidth', + 'borderRightWidth', + 'borderTopWidth', + 'borderBottomWidth' +]; + +function getZeroSize() { + var size = { + width: 0, + height: 0, + innerWidth: 0, + innerHeight: 0, + outerWidth: 0, + outerHeight: 0 + }; + for ( var i=0, len = measurements.length; i < len; i++ ) { + var measurement = measurements[i]; + size[ measurement ] = 0; + } + return size; +} + + + +function defineGetSize( getStyleProperty ) { + +// -------------------------- box sizing -------------------------- // + +var boxSizingProp = getStyleProperty('boxSizing'); +var isBoxSizeOuter; + +/** + * WebKit measures the outer-width on style.width on border-box elems + * IE & Firefox measures the inner-width + */ +( function() { + if ( !boxSizingProp ) { + return; + } + + var div = document.createElement('div'); + div.style.width = '200px'; + div.style.padding = '1px 2px 3px 4px'; + div.style.borderStyle = 'solid'; + div.style.borderWidth = '1px 2px 3px 4px'; + div.style[ boxSizingProp ] = 'border-box'; + + var body = document.body || document.documentElement; + body.appendChild( div ); + var style = getStyle( div ); + + isBoxSizeOuter = getStyleSize( style.width ) === 200; + body.removeChild( div ); +})(); + + +// -------------------------- getSize -------------------------- // + +function getSize( elem ) { + // use querySeletor if elem is string + if ( typeof elem === 'string' ) { + elem = document.querySelector( elem ); + } + + // do not proceed on non-objects + if ( !elem || typeof elem !== 'object' || !elem.nodeType ) { + return; + } + + var style = getStyle( elem ); + + // if hidden, everything is 0 + if ( style.display === 'none' ) { + return getZeroSize(); + } + + var size = {}; + size.width = elem.offsetWidth; + size.height = elem.offsetHeight; + + var isBorderBox = size.isBorderBox = !!( boxSizingProp && + style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' ); + + // get all measurements + for ( var i=0, len = measurements.length; i < len; i++ ) { + var measurement = measurements[i]; + var value = style[ measurement ]; + var num = parseFloat( value ); + // any 'auto', 'medium' value will be 0 + size[ measurement ] = !isNaN( num ) ? num : 0; + } + + var paddingWidth = size.paddingLeft + size.paddingRight; + var paddingHeight = size.paddingTop + size.paddingBottom; + var marginWidth = size.marginLeft + size.marginRight; + var marginHeight = size.marginTop + size.marginBottom; + var borderWidth = size.borderLeftWidth + size.borderRightWidth; + var borderHeight = size.borderTopWidth + size.borderBottomWidth; + + var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter; + + // overwrite width and height if we can get it from style + var styleWidth = getStyleSize( style.width ); + if ( styleWidth !== false ) { + size.width = styleWidth + + // add padding and border unless it's already including it + ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth ); + } + + var styleHeight = getStyleSize( style.height ); + if ( styleHeight !== false ) { + size.height = styleHeight + + // add padding and border unless it's already including it + ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight ); + } + + size.innerWidth = size.width - ( paddingWidth + borderWidth ); + size.innerHeight = size.height - ( paddingHeight + borderHeight ); + + size.outerWidth = size.width + marginWidth; + size.outerHeight = size.height + marginHeight; + + return size; +} + +return getSize; + +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( [ 'get-style-property' ], defineGetSize ); +} else { + // browser global + window.getSize = defineGetSize( window.getStyleProperty ); +} + +})( window ); + +/*! + * eventie v1.0.3 + * event binding helper + * eventie.bind( elem, 'click', myFn ) + * eventie.unbind( elem, 'click', myFn ) + */ + +/*jshint browser: true, undef: true, unused: true */ +/*global define: false */ + +( function( window ) { + +'use strict'; + +var docElem = document.documentElement; + +var bind = function() {}; + +if ( docElem.addEventListener ) { + bind = function( obj, type, fn ) { + obj.addEventListener( type, fn, false ); + }; +} else if ( docElem.attachEvent ) { + bind = function( obj, type, fn ) { + obj[ type + fn ] = fn.handleEvent ? + function() { + var event = window.event; + // add event.target + event.target = event.target || event.srcElement; + fn.handleEvent.call( fn, event ); + } : + function() { + var event = window.event; + // add event.target + event.target = event.target || event.srcElement; + fn.call( obj, event ); + }; + obj.attachEvent( "on" + type, obj[ type + fn ] ); + }; +} + +var unbind = function() {}; + +if ( docElem.removeEventListener ) { + unbind = function( obj, type, fn ) { + obj.removeEventListener( type, fn, false ); + }; +} else if ( docElem.detachEvent ) { + unbind = function( obj, type, fn ) { + obj.detachEvent( "on" + type, obj[ type + fn ] ); + try { + delete obj[ type + fn ]; + } catch ( err ) { + // can't delete window object properties + obj[ type + fn ] = undefined; + } + }; +} + +var eventie = { + bind: bind, + unbind: unbind +}; + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( eventie ); +} else { + // browser global + window.eventie = eventie; +} + +})( this ); + +/*! + * docReady + * Cross browser DOMContentLoaded event emitter + */ + +/*jshint browser: true, strict: true, undef: true, unused: true*/ +/*global define: false */ + +( function( window ) { + +'use strict'; + +var document = window.document; +// collection of functions to be triggered on ready +var queue = []; + +function docReady( fn ) { + // throw out non-functions + if ( typeof fn !== 'function' ) { + return; + } + + if ( docReady.isReady ) { + // ready now, hit it + fn(); + } else { + // queue function when ready + queue.push( fn ); + } +} + +docReady.isReady = false; + +// triggered on various doc ready events +function init( event ) { + // bail if IE8 document is not ready just yet + var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete'; + if ( docReady.isReady || isIE8NotReady ) { + return; + } + docReady.isReady = true; + + // process queue + for ( var i=0, len = queue.length; i < len; i++ ) { + var fn = queue[i]; + fn(); + } +} + +function defineDocReady( eventie ) { + eventie.bind( document, 'DOMContentLoaded', init ); + eventie.bind( document, 'readystatechange', init ); + eventie.bind( window, 'load', init ); + + return docReady; +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( [ 'eventie' ], defineDocReady ); +} else { + // browser global + window.docReady = defineDocReady( window.eventie ); +} + +})( this ); + +/*! + * EventEmitter v4.1.1 - git.io/ee + * Oliver Caldwell + * MIT license + * @preserve + */ + +(function (exports) { + // Place the script in strict mode + 'use strict'; + + /** + * Class for managing events. + * Can be extended to provide event functionality in other classes. + * + * @class Manages event registering and emitting. + */ + function EventEmitter() {} + + // Shortcuts to improve speed and size + + // Easy access to the prototype + var proto = EventEmitter.prototype, + nativeIndexOf = Array.prototype.indexOf ? true : false; + + /** + * Finds the index of the listener for the event in it's storage array. + * + * @param {Function} listener Method to look for. + * @param {Function[]} listeners Array of listeners to search through. + * @return {Number} Index of the specified listener, -1 if not found + * @api private + */ + function indexOfListener(listener, listeners) { + // Return the index via the native method if possible + if (nativeIndexOf) { + return listeners.indexOf(listener); + } + + // There is no native method + // Use a manual loop to find the index + var i = listeners.length; + while (i--) { + // If the listener matches, return it's index + if (listeners[i] === listener) { + return i; + } + } + + // Default to returning -1 + return -1; + } + + /** + * Fetches the events object and creates one if required. + * + * @return {Object} The events storage object. + * @api private + */ + proto._getEvents = function () { + return this._events || (this._events = {}); + }; + + /** + * Returns the listener array for the specified event. + * Will initialise the event object and listener arrays if required. + * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. + * Each property in the object response is an array of listener functions. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Function[]|Object} All listener functions for the event. + */ + proto.getListeners = function (evt) { + // Create a shortcut to the storage object + // Initialise it if it does not exists yet + var events = this._getEvents(), + response, + key; + + // Return a concatenated array of all matching events if + // the selector is a regular expression. + if (typeof evt === 'object') { + response = {}; + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + response[key] = events[key]; + } + } + } + else { + response = events[evt] || (events[evt] = []); + } + + return response; + }; + + /** + * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Object} All listener functions for an event in an object. + */ + proto.getListenersAsObject = function (evt) { + var listeners = this.getListeners(evt), + response; + + if (listeners instanceof Array) { + response = {}; + response[evt] = listeners; + } + + return response || listeners; + }; + + /** + * Adds a listener function to the specified event. + * The listener will not be added if it is a duplicate. + * If the listener returns true then it will be removed after it is called. + * If you pass a regular expression as the event name then the listener will be added to all events that match it. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListener = function (evt, listener) { + var listeners = this.getListenersAsObject(evt), + key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key) && + indexOfListener(listener, listeners[key]) === -1) { + listeners[key].push(listener); + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of addListener + */ + proto.on = proto.addListener; + + /** + * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. + * You need to tell it what event names should be matched by a regex. + * + * @param {String} evt Name of the event to create. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvent = function (evt) { + this.getListeners(evt); + return this; + }; + + /** + * Uses defineEvent to define multiple events. + * + * @param {String[]} evts An array of event names to define. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvents = function (evts) + { + for (var i = 0; i < evts.length; i += 1) { + this.defineEvent(evts[i]); + } + return this; + }; + + /** + * Removes a listener function from the specified event. + * When passed a regular expression as the event name, it will remove the listener from all events that match it. + * + * @param {String|RegExp} evt Name of the event to remove the listener from. + * @param {Function} listener Method to remove from the event. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListener = function (evt, listener) { + var listeners = this.getListenersAsObject(evt), + index, + key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + index = indexOfListener(listener, listeners[key]); + + if (index !== -1) { + listeners[key].splice(index, 1); + } + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of removeListener + */ + proto.off = proto.removeListener; + + /** + * Adds listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. + * You can also pass it a regular expression to add the array of listeners to all events that match it. + * Yeah, this function does quite a bit. That's probably a bad thing. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListeners = function (evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(false, evt, listeners); + }; + + /** + * Removes listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be removed. + * You can also pass it a regular expression to remove the listeners from all events that match it. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListeners = function (evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(true, evt, listeners); + }; + + /** + * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. + * The first argument will determine if the listeners are removed (true) or added (false). + * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be added/removed. + * You can also pass it a regular expression to manipulate the listeners of all events that match it. + * + * @param {Boolean} remove True if you want to remove listeners, false if you want to add. + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add/remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.manipulateListeners = function (remove, evt, listeners) { + // Initialise any required variables + var i, + value, + single = remove ? this.removeListener : this.addListener, + multiple = remove ? this.removeListeners : this.addListeners; + + // If evt is an object then pass each of it's properties to this method + if (typeof evt === 'object' && !(evt instanceof RegExp)) { + for (i in evt) { + if (evt.hasOwnProperty(i) && (value = evt[i])) { + // Pass the single listener straight through to the singular method + if (typeof value === 'function') { + single.call(this, i, value); + } + else { + // Otherwise pass back to the multiple function + multiple.call(this, i, value); + } + } + } + } + else { + // So evt must be a string + // And listeners must be an array of listeners + // Loop over it and pass each one to the multiple method + i = listeners.length; + while (i--) { + single.call(this, evt, listeners[i]); + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Removes all listeners from a specified event. + * If you do not specify an event then all listeners will be removed. + * That means every event will be emptied. + * You can also pass a regex to remove all events that match it. + * + * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeEvent = function (evt) { + var type = typeof evt, + events = this._getEvents(), + key; + + // Remove different things depending on the state of evt + if (type === 'string') { + // Remove all listeners for the specified event + delete events[evt]; + } + else if (type === 'object') { + // Remove all events matching the regex. + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + delete events[key]; + } + } + } + else { + // Remove all listeners in all events + delete this._events; + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Emits an event of your choice. + * When emitted, every listener attached to that event will be executed. + * If you pass the optional argument array then those arguments will be passed to every listener upon execution. + * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. + * So they will not arrive within the array on the other side, they will be separate. + * You can also pass a regular expression to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {Array} [args] Optional array of arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emitEvent = function (evt, args) { + var listeners = this.getListenersAsObject(evt), + i, + key, + response; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + i = listeners[key].length; + + while (i--) { + // If the listener returns true then it shall be removed from the event + // The function is executed either with a basic call or an apply if there is an args array + response = args ? listeners[key][i].apply(null, args) : listeners[key][i](); + if (response === true) { + this.removeListener(evt, listeners[key][i]); + } + } + } + } + + // Return the instance of EventEmitter to allow chaining + return this; + }; + + /** + * Alias of emitEvent + */ + proto.trigger = proto.emitEvent; + + /** + * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. + * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {...*} Optional additional arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emit = function (evt) { + var args = Array.prototype.slice.call(arguments, 1); + return this.emitEvent(evt, args); + }; + + // Expose the class either via AMD or the global object + if (typeof define === 'function' && define.amd) { + define(function () { + return EventEmitter; + }); + } + else { + exports.EventEmitter = EventEmitter; + } +}(this)); +/** + * Bridget makes jQuery widgets + * v1.0.0 + */ + +( function( window ) { + +'use strict'; + +// -------------------------- utils -------------------------- // + +var slice = Array.prototype.slice; + +function noop() {} + +// -------------------------- definition -------------------------- // + +function defineBridget( $ ) { + +// bail if no jQuery +if ( !$ ) { + return; +} + +// -------------------------- addOptionMethod -------------------------- // + +/** + * adds option method -> $().plugin('option', {...}) + * @param {Function} PluginClass - constructor class + */ +function addOptionMethod( PluginClass ) { + // don't overwrite original option method + if ( PluginClass.prototype.option ) { + return; + } + + // option setter + PluginClass.prototype.option = function( opts ) { + // bail out if not an object + if ( !$.isPlainObject( opts ) ){ + return; + } + this.options = $.extend( true, this.options, opts ); + }; +} + + +// -------------------------- plugin bridge -------------------------- // + +// helper function for logging errors +// $.error breaks jQuery chaining +var logError = typeof console === 'undefined' ? noop : + function( message ) { + console.error( message ); + }; + +/** + * jQuery plugin bridge, access methods like $elem.plugin('method') + * @param {String} namespace - plugin name + * @param {Function} PluginClass - constructor class + */ +function bridge( namespace, PluginClass ) { + // add to jQuery fn namespace + $.fn[ namespace ] = function( options ) { + if ( typeof options === 'string' ) { + // call plugin method when first argument is a string + // get arguments for method + var args = slice.call( arguments, 1 ); + + for ( var i=0, len = this.length; i < len; i++ ) { + var elem = this[i]; + var instance = $.data( elem, namespace ); + if ( !instance ) { + logError( "cannot call methods on " + namespace + " prior to initialization; " + + "attempted to call '" + options + "'" ); + continue; + } + if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) { + logError( "no such method '" + options + "' for " + namespace + " instance" ); + continue; + } + + // trigger method with arguments + var returnValue = instance[ options ].apply( instance, args ); + + // break look and return first value if provided + if ( returnValue !== undefined ) { + return returnValue; + } + } + // return this if no return value + return this; + } else { + return this.each( function() { + var instance = $.data( this, namespace ); + if ( instance ) { + // apply options & init + instance.option( options ); + instance._init(); + } else { + // initialize new instance + instance = new PluginClass( this, options ); + $.data( this, namespace, instance ); + } + }); + } + }; + +} + +// -------------------------- bridget -------------------------- // + +/** + * converts a Prototypical class into a proper jQuery plugin + * the class must have a ._init method + * @param {String} namespace - plugin name, used in $().pluginName + * @param {Function} PluginClass - constructor class + */ +$.bridget = function( namespace, PluginClass ) { + addOptionMethod( PluginClass ); + bridge( namespace, PluginClass ); +}; + +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( [ 'jquery' ], defineBridget ); +} else { + // get jquery from browser global + defineBridget( window.jQuery ); +} + +})( window ); + +/** + * matchesSelector helper v1.0.1 + * + * @name matchesSelector + * @param {Element} elem + * @param {String} selector + */ + +/*jshint browser: true, strict: true, undef: true, unused: true */ +/*global define: false */ + +( function( global, ElemProto ) { + + 'use strict'; + + var matchesMethod = ( function() { + // check un-prefixed + if ( ElemProto.matchesSelector ) { + return 'matchesSelector'; + } + // check vendor prefixes + var prefixes = [ 'webkit', 'moz', 'ms', 'o' ]; + + for ( var i=0, len = prefixes.length; i < len; i++ ) { + var prefix = prefixes[i]; + var method = prefix + 'MatchesSelector'; + if ( ElemProto[ method ] ) { + return method; + } + } + })(); + + // ----- match ----- // + + function match( elem, selector ) { + return elem[ matchesMethod ]( selector ); + } + + // ----- appendToFragment ----- // + + function checkParent( elem ) { + // not needed if already has parent + if ( elem.parentNode ) { + return; + } + var fragment = document.createDocumentFragment(); + fragment.appendChild( elem ); + } + + // ----- query ----- // + + // fall back to using QSA + // thx @jonathantneal https://gist.github.com/3062955 + function query( elem, selector ) { + // append to fragment if no parent + checkParent( elem ); + + // match elem with all selected elems of parent + var elems = elem.parentNode.querySelectorAll( selector ); + for ( var i=0, len = elems.length; i < len; i++ ) { + // return true if match + if ( elems[i] === elem ) { + return true; + } + } + // otherwise return false + return false; + } + + // ----- matchChild ----- // + + function matchChild( elem, selector ) { + checkParent( elem ); + return match( elem, selector ); + } + + // ----- matchesSelector ----- // + + var matchesSelector; + + if ( matchesMethod ) { + // IE9 supports matchesSelector, but doesn't work on orphaned elems + // check for that + var div = document.createElement('div'); + var supportsOrphans = match( div, 'div' ); + matchesSelector = supportsOrphans ? match : matchChild; + } else { + matchesSelector = query; + } + + // transport + if ( typeof define === 'function' && define.amd ) { + // AMD + define( function() { + return matchesSelector; + }); + } else { + // browser global + window.matchesSelector = matchesSelector; + } + +})( this, Element.prototype ); + +/** + * Outlayer Item +**/ + +( function( window ) { + +'use strict'; + +// dependencies +var getSize = window.getSize; +var getStyleProperty = window.getStyleProperty; +var EventEmitter = window.EventEmitter; + +// ----- get style ----- // + +var defView = document.defaultView; + +var getStyle = defView && defView.getComputedStyle ? + function( elem ) { + return defView.getComputedStyle( elem, null ); + } : + function( elem ) { + return elem.currentStyle; + }; + + +// extend objects +function extend( a, b ) { + for ( var prop in b ) { + a[ prop ] = b[ prop ]; + } + return a; +} + +// -------------------------- CSS3 support -------------------------- // + +var transitionProperty = getStyleProperty('transition'); +var transformProperty = getStyleProperty('transform'); +var supportsCSS3 = transitionProperty && transformProperty; +var is3d = !!getStyleProperty('perspective'); + +var transitionEndEvent = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'otransitionend', + transition: 'transitionend' +}[ transitionProperty ]; + +// properties that could have vendor prefix +var prefixableProperties = [ + 'transform', + 'transition', + 'transitionDuration', + 'transitionProperty' +]; + +// cache all vendor properties +var vendorProperties = ( function() { + var cache = {}; + for ( var i=0, len = prefixableProperties.length; i < len; i++ ) { + var prop = prefixableProperties[i]; + var supportedProp = getStyleProperty( prop ); + if ( supportedProp && supportedProp !== prop ) { + cache[ prop ] = supportedProp; + } + } + return cache; +})(); + +// -------------------------- Item -------------------------- // + +function Item( element, layout ) { + if ( !element ) { + return; + } + + this.element = element; + // parent layout class, i.e. Masonry, Isotope, or Packery + this.layout = layout; + this.position = { + x: 0, + y: 0 + }; + + this._create(); +} + +// inherit EventEmitter +extend( Item.prototype, EventEmitter.prototype ); + +Item.prototype._create = function() { + this.css({ + position: 'absolute' + }); +}; + +// trigger specified handler for event type +Item.prototype.handleEvent = function( event ) { + var method = 'on' + event.type; + if ( this[ method ] ) { + this[ method ]( event ); + } +}; + +Item.prototype.getSize = function() { + this.size = getSize( this.element ); +}; + +/** + * apply CSS styles to element + * @param {Object} style + */ +Item.prototype.css = function( style ) { + var elemStyle = this.element.style; + + for ( var prop in style ) { + // use vendor property if available + var supportedProp = vendorProperties[ prop ] || prop; + elemStyle[ supportedProp ] = style[ prop ]; + } +}; + + // measure position, and sets it +Item.prototype.getPosition = function() { + var style = getStyle( this.element ); + var layoutOptions = this.layout.options; + var isOriginLeft = layoutOptions.isOriginLeft; + var isOriginTop = layoutOptions.isOriginTop; + var x = parseInt( style[ isOriginLeft ? 'left' : 'right' ], 10 ); + var y = parseInt( style[ isOriginTop ? 'top' : 'bottom' ], 10 ); + + // clean up 'auto' or other non-integer values + x = isNaN( x ) ? 0 : x; + y = isNaN( y ) ? 0 : y; + // remove padding from measurement + var layoutSize = this.layout.size; + x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight; + y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom; + + this.position.x = x; + this.position.y = y; +}; + +// set settled position, apply padding +Item.prototype.layoutPosition = function() { + var layoutSize = this.layout.size; + var layoutOptions = this.layout.options; + var style = {}; + + if ( layoutOptions.isOriginLeft ) { + style.left = ( this.position.x + layoutSize.paddingLeft ) + 'px'; + // reset other property + style.right = ''; + } else { + style.right = ( this.position.x + layoutSize.paddingRight ) + 'px'; + style.left = ''; + } + + if ( layoutOptions.isOriginTop ) { + style.top = ( this.position.y + layoutSize.paddingTop ) + 'px'; + style.bottom = ''; + } else { + style.bottom = ( this.position.y + layoutSize.paddingBottom ) + 'px'; + style.top = ''; + } + + this.css( style ); + this.emitEvent( 'layout', [ this ] ); +}; + + +// transform translate function +var translate = is3d ? + function( x, y ) { + return 'translate3d(' + x + 'px, ' + y + 'px, 0)'; + } : + function( x, y ) { + return 'translate(' + x + 'px, ' + y + 'px)'; + }; + + +Item.prototype._transitionTo = function( x, y ) { + this.getPosition(); + // get current x & y from top/left + var curX = this.position.x; + var curY = this.position.y; + + var compareX = parseInt( x, 10 ); + var compareY = parseInt( y, 10 ); + var didNotMove = compareX === this.position.x && compareY === this.position.y; + + // save end position + this.setPosition( x, y ); + + // if did not move and not transitioning, just go to layout + if ( didNotMove && !this.isTransitioning ) { + this.layoutPosition(); + return; + } + + var transX = x - curX; + var transY = y - curY; + var transitionStyle = {}; + // flip cooridinates if origin on right or bottom + var layoutOptions = this.layout.options; + transX = layoutOptions.isOriginLeft ? transX : -transX; + transY = layoutOptions.isOriginTop ? transY : -transY; + transitionStyle.transform = translate( transX, transY ); + + this.transition({ + to: transitionStyle, + onTransitionEnd: this.layoutPosition, + isCleaning: true + }); +}; + +// non transition + transform support +Item.prototype.goTo = function( x, y ) { + this.setPosition( x, y ); + this.layoutPosition(); +}; + +// use transition and transforms if supported +Item.prototype.moveTo = supportsCSS3 ? + Item.prototype._transitionTo : Item.prototype.goTo; + +Item.prototype.setPosition = function( x, y ) { + this.position.x = parseInt( x, 10 ); + this.position.y = parseInt( y, 10 ); +}; + +// ----- transition ----- // + +/** + * @param {Object} style - CSS + * @param {Function} onTransitionEnd + */ + +// non transition, just trigger callback +Item.prototype._nonTransition = function( args ) { + this.css( args.to ); + if ( args.isCleaning ) { + this._removeStyles( args.to ); + } + if ( args.onTransitionEnd ) { + args.onTransitionEnd.call( this ); + } +}; + +/** + * proper transition + * @param {Object} args - arguments + * @param {Object} to - style to transition to + * @param {Object} from - style to start transition from + * @param {Boolean} isCleaning - removes transition styles after transition + * @param {Function} onTransitionEnd - callback + */ +Item.prototype._transition = function( args ) { + // redirect to nonTransition if no transition duration + var transitionDuration = this.layout.options.transitionDuration; + if ( !parseFloat( transitionDuration ) ) { + this._nonTransition( args ); + return; + } + + var style = args.to; + // make transition: foo, bar, baz from style object + var transitionValue = []; + for ( var prop in style ) { + transitionValue.push( prop ); + } + + // enable transition + var transitionStyle = {}; + transitionStyle.transitionProperty = transitionValue.join(','); + transitionStyle.transitionDuration = transitionDuration; + + this.element.addEventListener( transitionEndEvent, this, false ); + + // if there's stuff to do after the transition + if ( args.isCleaning || args.onTransitionEnd ) { + this.on( 'transitionEnd', function( _this ) { + // remove transition styles after transition + if ( args.isCleaning ) { + _this._removeStyles( style ); + } + // trigger callback now that transition has ended + if ( args.onTransitionEnd ) { + args.onTransitionEnd.call( _this ); + } + return true; // bind once + }); + } + + // set from styles + if ( args.from ) { + this.css( args.from ); + // force redraw. http://blog.alexmaccaw.com/css-transitions + var h = this.element.offsetHeight; + // hack for JSHint to hush about unused var + h = null; + } + // set transition styles, to enable transition + this.css( transitionStyle ); + // set styles that are transitioning + this.css( style ); + + this.isTransitioning = true; +}; + +Item.prototype.transition = Item.prototype[ transitionProperty ? '_transition' : '_nonTransition' ]; + +// ----- events ----- // + +Item.prototype.onwebkitTransitionEnd = function( event ) { + this.ontransitionend( event ); +}; + +Item.prototype.onotransitionend = function( event ) { + this.ontransitionend( event ); +}; + +Item.prototype.ontransitionend = function( event ) { + // console.log('transition end'); + // disregard bubbled events from children + if ( event.target !== this.element ) { + return; + } + + this.removeTransitionStyles(); + + this.element.removeEventListener( transitionEndEvent, this, false ); + + this.isTransitioning = false; + + this.emitEvent( 'transitionEnd', [ this ] ); +}; + +/** + * removes style property from element + * @param {Object} style +**/ +Item.prototype._removeStyles = function( style ) { + // clean up transition styles + var cleanStyle = {}; + for ( var prop in style ) { + cleanStyle[ prop ] = ''; + } + this.css( cleanStyle ); +}; + +var cleanTransitionStyle = { + transitionProperty: '', + transitionDuration: '' +}; + +Item.prototype.removeTransitionStyles = function() { + // remove transition + this.css( cleanTransitionStyle ); +}; + +// ----- show/hide/remove ----- // + +// remove element from DOM +Item.prototype.removeElem = function() { + this.element.parentNode.removeChild( this.element ); + this.emitEvent( 'remove', [ this ] ); +}; + +Item.prototype.remove = transitionProperty ? function() { + // start transition + var _this = this; + this.on( 'transitionEnd', function() { + _this.removeElem(); + return true; // bind once + }); + this.hide(); +// if no transition just remove element +} : Item.prototype.removeElem; + +Item.prototype.reveal = function() { + // remove display: none + this.css({ display: '' }); + + var options = this.layout.options; + this.transition({ + from: options.hiddenStyle, + to: options.visibleStyle, + isCleaning: true + }); +}; + +Item.prototype.hide = function() { + // remove display: none + this.css({ display: '' }); + + var options = this.layout.options; + this.transition({ + from: options.visibleStyle, + to: options.hiddenStyle, + // keep hidden stuff hidden + isCleaning: true, + onTransitionEnd: function() { + this.css({ display: 'none' }); + } + }); +}; + +Item.prototype.destroy = function() { + this.css({ + position: '', + left: '', + right: '', + top: '', + bottom: '', + transition: '', + transform: '' + }); +}; + +// -------------------------- -------------------------- // + +// publicize +window.Outlayer = { + Item: Item +}; + +})( window ); + +/*! + * Outlayer v1.0.0 + * the brains and guts of a layout library + */ + +( function( window ) { + +'use strict'; + +// Outlayer classes +var _Outlayer = window.Outlayer; +var Item = _Outlayer.Item; + +// dependencies +var docReady = window.docReady; +var EventEmitter = window.EventEmitter; +var eventie = window.eventie; +var getSize = window.getSize; +var matchesSelector = window.matchesSelector; + +// ----- vars ----- // + +var document = window.document; +var console = window.console; +var jQuery = window.jQuery; + +var noop = function() {}; + +// -------------------------- helpers -------------------------- // + +// extend objects +function extend( a, b ) { + for ( var prop in b ) { + a[ prop ] = b[ prop ]; + } + return a; +} + + +var objToString = Object.prototype.toString; +function isArray( obj ) { + return objToString.call( obj ) === '[object Array]'; +} + +// turn element or nodeList into an array +function makeArray( obj ) { + var ary = []; + if ( isArray( obj ) ) { + // use object if already an array + ary = obj; + } else if ( typeof obj.length === 'number' ) { + // convert nodeList to array + for ( var i=0, len = obj.length; i < len; i++ ) { + ary.push( obj[i] ); + } + } else { + // array of single index + ary.push( obj ); + } + return ary; +} + +// http://stackoverflow.com/a/384380/182183 +var isElement = ( typeof HTMLElement === 'object' ) ? + function isElementDOM2( obj ) { + return obj instanceof HTMLElement; + } : + function isElementQuirky( obj ) { + return obj && typeof obj === 'object' && + obj.nodeType === 1 && typeof obj.nodeName === 'string'; + }; + +// index of helper cause IE8 +var indexOf = Array.prototype.indexOf ? function( ary, obj ) { + return ary.indexOf( obj ); + } : function( ary, obj ) { + for ( var i=0, len = ary.length; i < len; i++ ) { + if ( ary[i] === obj ) { + return i; + } + } + return -1; + }; + +// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/ +function toDashed( str ) { + return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) { + return $1 + '-' + $2; + }).toLowerCase(); +} + + +// -------------------------- Outlayer -------------------------- // + +// globally unique identifiers +var GUID = 0; +// internal store of all Outlayer intances +var instances = {}; + + +/** + * @param {Element, String} element + * @param {Object} options + * @constructor + */ +function Outlayer( element, options ) { + // use element as selector string + if ( typeof element === 'string' ) { + element = document.querySelector( element ); + } + + // bail out if not proper element + if ( !element || !isElement( element ) ) { + if ( console ) { + console.error( 'Bad ' + this.settings.namespace + ' element: ' + element ); + } + return; + } + + this.element = element; + + // options + this.options = extend( {}, this.options ); + extend( this.options, options ); + + // add id for Outlayer.getFromElement + var id = ++GUID; + this.element.outlayerGUID = id; // expando + instances[ id ] = this; // associate via id + + // kick it off + this._create(); + + if ( this.options.isInitLayout ) { + this.layout(); + } +} + +// settings are for internal use only +Outlayer.prototype.settings = { + namespace: 'outlayer', + item: _Outlayer.Item +}; + +// default options +Outlayer.prototype.options = { + containerStyle: { + position: 'relative' + }, + isInitLayout: true, + isOriginLeft: true, + isOriginTop: true, + isResizeBound: true, + // item options + transitionDuration: '0.4s', + hiddenStyle: { + opacity: 0, + transform: 'scale(0.001)' + }, + visibleStyle: { + opacity: 1, + transform: 'scale(1)' + } +}; + +// inherit EventEmitter +extend( Outlayer.prototype, EventEmitter.prototype ); + +Outlayer.prototype._create = function() { + // get items from children + this.reloadItems(); + // elements that affect layout, but are not laid out + this.stamps = []; + this.stamp( this.options.stamp ); + // set container style + extend( this.element.style, this.options.containerStyle ); + + // bind resize method + if ( this.options.isResizeBound ) { + this.bindResize(); + } +}; + +// goes through all children again and gets bricks in proper order +Outlayer.prototype.reloadItems = function() { + // collection of item elements + this.items = this._getItems( this.element.children ); +}; + + +/** + * get item elements to be used in layout + * @param {Array or NodeList or HTMLElement} elems + * @returns {Array} items - collection of new Outlayer Items + */ +Outlayer.prototype._getItems = function( elems ) { + + var itemElems = this._filterFindItemElements( elems ); + var Item = this.settings.item; + + // create new Outlayer Items for collection + var items = []; + for ( var i=0, len = itemElems.length; i < len; i++ ) { + var elem = itemElems[i]; + var item = new Item( elem, this, this.options.itemOptions ); + items.push( item ); + } + + return items; +}; + +/** + * get item elements to be used in layout + * @param {Array or NodeList or HTMLElement} elems + * @returns {Array} items - item elements + */ +Outlayer.prototype._filterFindItemElements = function( elems ) { + // make array of elems + elems = makeArray( elems ); + var itemSelector = this.options.itemSelector; + + if ( !itemSelector ) { + return elems; + } + + var itemElems = []; + + // filter & find items if we have an item selector + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + // filter siblings + if ( matchesSelector( elem, itemSelector ) ) { + itemElems.push( elem ); + } + // find children + var childElems = elem.querySelectorAll( itemSelector ); + // concat childElems to filterFound array + for ( var j=0, jLen = childElems.length; j < jLen; j++ ) { + itemElems.push( childElems[j] ); + } + } + + return itemElems; +}; + +/** + * getter method for getting item elements + * @returns {Array} elems - collection of item elements + */ +Outlayer.prototype.getItemElements = function() { + var elems = []; + for ( var i=0, len = this.items.length; i < len; i++ ) { + elems.push( this.items[i].element ); + } + return elems; +}; + +// ----- init & layout ----- // + +/** + * lays out all items + */ +Outlayer.prototype.layout = function() { + this._resetLayout(); + this._manageStamps(); + + // don't animate first layout + var isInstant = this.options.isLayoutInstant !== undefined ? + this.options.isLayoutInstant : !this._isLayoutInited; + this.layoutItems( this.items, isInstant ); + + // flag for initalized + this._isLayoutInited = true; +}; + +// _init is alias for layout +Outlayer.prototype._init = Outlayer.prototype.layout; + +/** + * logic before any new layout + */ +Outlayer.prototype._resetLayout = function() { + this.getSize(); +}; + + +Outlayer.prototype.getSize = function() { + this.size = getSize( this.element ); +}; + +/** + * get measurement from option, for columnWidth, rowHeight, gutter + * if option is String -> get element from selector string, & get size of element + * if option is Element -> get size of element + * else use option as a number + * + * @param {String} measurement + * @param {String} size - width or height + * @private + */ +Outlayer.prototype._getMeasurement = function( measurement, size ) { + var option = this.options[ measurement ]; + var elem; + if ( !option ) { + // default to 0 + this[ measurement ] = 0; + } else { + if ( typeof option === 'string' ) { + elem = this.element.querySelector( option ); + } else if ( isElement( option ) ) { + elem = option; + } + // use size of element, if element + this[ measurement ] = elem ? getSize( elem )[ size ] : option; + } +}; + +/** + * layout a collection of item elements + * @api public + */ +Outlayer.prototype.layoutItems = function( items, isInstant ) { + items = this._getItemsForLayout( items ); + + this._layoutItems( items, isInstant ); + + this._postLayout(); +}; + +/** + * get the items to be laid out + * you may want to skip over some items + * @param {Array} items + * @returns {Array} items + */ +Outlayer.prototype._getItemsForLayout = function( items ) { + var layoutItems = []; + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + if ( !item.isIgnored ) { + layoutItems.push( item ); + } + } + return layoutItems; +}; + +/** + * layout items + * @param {Array} items + * @param {Boolean} isInstant + */ +Outlayer.prototype._layoutItems = function( items, isInstant ) { + if ( !items || !items.length ) { + // no items, emit event with empty array + this.emitEvent( 'layoutComplete', [ this, items ] ); + return; + } + + // emit layoutComplete when done + this._itemsOn( items, 'layout', function onItemsLayout() { + this.emitEvent( 'layoutComplete', [ this, items ] ); + }); + + var queue = []; + + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + // get x/y object from method + var position = this._getItemLayoutPosition( item ); + // enqueue + position.item = item; + position.isInstant = isInstant; + queue.push( position ); + } + + this._processLayoutQueue( queue ); +}; + +/** + * get item layout position + * @param {Outlayer.Item} item + * @returns {Object} x and y position + */ +Outlayer.prototype._getItemLayoutPosition = function( /* item */ ) { + return { + x: 0, + y: 0 + }; +}; + +/** + * iterate over array and position each item + * Reason being - separating this logic prevents 'layout invalidation' + * thx @paul_irish + * @param {Array} queue + */ +Outlayer.prototype._processLayoutQueue = function( queue ) { + for ( var i=0, len = queue.length; i < len; i++ ) { + var obj = queue[i]; + this._positionItem( obj.item, obj.x, obj.y, obj.isInstant ); + } +}; + +/** + * Sets position of item in DOM + * @param {Outlayer.Item} item + * @param {Number} x - horizontal position + * @param {Number} y - vertical position + * @param {Boolean} isInstant - disables transitions + */ +Outlayer.prototype._positionItem = function( item, x, y, isInstant ) { + if ( isInstant ) { + // if not transition, just set CSS + item.goTo( x, y ); + } else { + item.moveTo( x, y ); + } +}; + +/** + * Any logic you want to do after each layout, + * i.e. size the container + */ +Outlayer.prototype._postLayout = function() { + var size = this._getContainerSize(); + if ( size ) { + this._setContainerMeasure( size.width, true ); + this._setContainerMeasure( size.height, false ); + } +}; + +/** + * @returns {Object} size + * @param {Number} width + * @param {Number} height + */ +Outlayer.prototype._getContainerSize = noop; + +/** + * @param {Number} measure - size of width or height + * @param {Boolean} isWidth + */ +Outlayer.prototype._setContainerMeasure = function( measure, isWidth ) { + if ( measure === undefined ) { + return; + } + + var elemSize = this.size; + // add padding and border width if border box + if ( elemSize.isBorderBox ) { + measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight + + elemSize.borderLeftWidth + elemSize.borderRightWidth : + elemSize.paddingBottom + elemSize.paddingTop + + elemSize.borderTopWidth + elemSize.borderBottomWidth; + } + + measure = Math.max( measure, 0 ); + this.element.style[ isWidth ? 'width' : 'height' ] = measure + 'px'; +}; + +/** + * trigger a callback for a collection of items events + * @param {Array} items - Outlayer.Items + * @param {String} eventName + * @param {Function} callback + */ +Outlayer.prototype._itemsOn = function( items, eventName, callback ) { + var doneCount = 0; + var count = items.length; + // event callback + var _this = this; + function tick() { + doneCount++; + if ( doneCount === count ) { + callback.call( _this ); + } + return true; // bind once + } + // bind callback + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + item.on( eventName, tick ); + } +}; + +// -------------------------- ignore & stamps -------------------------- // + + +/** + * keep item in collection, but do not lay it out + * ignored items do not get skipped in layout + * @param {Element} elem + */ +Outlayer.prototype.ignore = function( elem ) { + var item = this.getItem( elem ); + if ( item ) { + item.isIgnored = true; + } +}; + +/** + * return item to layout collection + * @param {Element} elem + */ +Outlayer.prototype.unignore = function( elem ) { + var item = this.getItem( elem ); + if ( item ) { + delete item.isIgnored; + } +}; + +/** + * adds elements to stamps + * @param {NodeList, Array, Element, or String} elems + */ +Outlayer.prototype.stamp = function( elems ) { + elems = this._find( elems ); + if ( !elems ) { + return; + } + + this.stamps = this.stamps.concat( elems ); + // ignore + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + this.ignore( elem ); + } +}; + +/** + * removes elements to stamps + * @param {NodeList, Array, or Element} elems + */ +Outlayer.prototype.unstamp = function( elems ) { + elems = this._find( elems ); + if ( !elems ){ + return; + } + + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + // filter out removed stamp elements + var index = indexOf( this.stamps, elem ); + if ( index !== -1 ) { + this.stamps.splice( index, 1 ); + } + this.unignore( elem ); + } + +}; + +/** + * finds child elements + * @param {NodeList, Array, Element, or String} elems + * @returns {Array} elems + */ +Outlayer.prototype._find = function( elems ) { + if ( !elems ) { + return; + } + // if string, use argument as selector string + if ( typeof elems === 'string' ) { + elems = this.element.querySelectorAll( elems ); + } + elems = makeArray( elems ); + return elems; +}; + +Outlayer.prototype._manageStamps = function() { + if ( !this.stamps || !this.stamps.length ) { + return; + } + + this._getBoundingRect(); + + for ( var i=0, len = this.stamps.length; i < len; i++ ) { + var stamp = this.stamps[i]; + this._manageStamp( stamp ); + } +}; + +// update boundingLeft / Top +Outlayer.prototype._getBoundingRect = function() { + // get bounding rect for container element + var boundingRect = this.element.getBoundingClientRect(); + var size = this.size; + this._boundingRect = { + left: boundingRect.left + size.paddingLeft + size.borderLeftWidth, + top: boundingRect.top + size.paddingTop + size.borderTopWidth, + right: boundingRect.right - ( size.paddingRight + size.borderRightWidth ), + bottom: boundingRect.bottom - ( size.paddingBottom + size.borderBottomWidth ) + }; +}; + +/** + * @param {Element} stamp +**/ +Outlayer.prototype._manageStamp = noop; + +/** + * get x/y position of element relative to container element + * @param {Element} elem + * @returns {Object} offset - has left, top, right, bottom + */ +Outlayer.prototype._getElementOffset = function( elem ) { + var boundingRect = elem.getBoundingClientRect(); + var thisRect = this._boundingRect; + var size = getSize( elem ); + var offset = { + left: boundingRect.left - thisRect.left - size.marginLeft, + top: boundingRect.top - thisRect.top - size.marginTop, + right: thisRect.right - boundingRect.right - size.marginRight, + bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom + }; + return offset; +}; + +// -------------------------- resize -------------------------- // + +// enable event handlers for listeners +// i.e. resize -> onresize +Outlayer.prototype.handleEvent = function( event ) { + var method = 'on' + event.type; + if ( this[ method ] ) { + this[ method ]( event ); + } +}; + +/** + * Bind layout to window resizing + */ +Outlayer.prototype.bindResize = function() { + // bind just one listener + if ( this.isResizeBound ) { + return; + } + eventie.bind( window, 'resize', this ); + this.isResizeBound = true; +}; + +/** + * Unbind layout to window resizing + */ +Outlayer.prototype.unbindResize = function() { + eventie.unbind( window, 'resize', this ); + this.isResizeBound = false; +}; + +// original debounce by John Hann +// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ + +// this fires every resize +Outlayer.prototype.onresize = function() { + if ( this.resizeTimeout ) { + clearTimeout( this.resizeTimeout ); + } + + var _this = this; + function delayed() { + _this.resize(); + } + + this.resizeTimeout = setTimeout( delayed, 100 ); +}; + +// debounced, layout on resize +Outlayer.prototype.resize = function() { + // don't trigger if size did not change + var size = getSize( this.element ); + // check that this.size and size are there + // IE8 triggers resize on body size change, so they might not be + var hasSizes = this.size && size; + if ( hasSizes && size.innerWidth === this.size.innerWidth ) { + return; + } + + this.layout(); + + delete this.resizeTimeout; +}; + + +// -------------------------- methods -------------------------- // + +/** + * add items to Outlayer instance + * @param {Array or NodeList or Element} elems + * @returns {Array} items - Outlayer.Items +**/ +Outlayer.prototype.addItems = function( elems ) { + var items = this._getItems( elems ); + if ( !items.length ) { + return; + } + // add items to collection + this.items = this.items.concat( items ); + return items; +}; + +/** + * Layout newly-appended item elements + * @param {Array or NodeList or Element} elems + */ +Outlayer.prototype.appended = function( elems ) { + var items = this.addItems( elems ); + if ( !items.length ) { + return; + } + // layout and reveal just the new items + this.layoutItems( items, true ); + this.reveal( items ); +}; + +/** + * Layout prepended elements + * @param {Array or NodeList or Element} elems + */ +Outlayer.prototype.prepended = function( elems ) { + var items = this._getItems( elems ); + if ( !items.length ) { + return; + } + // add items to beginning of collection + var previousItems = this.items.slice(0); + this.items = items.concat( previousItems ); + // start new layout + this._resetLayout(); + // layout new stuff without transition + this.layoutItems( items, true ); + this.reveal( items ); + // layout previous items + this.layoutItems( previousItems ); +}; + +/** + * reveal a collection of items + * @param {Array of Outlayer.Items} items + */ +Outlayer.prototype.reveal = function( items ) { + if ( !items || !items.length ) { + return; + } + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + item.reveal(); + } +}; + +/** + * hide a collection of items + * @param {Array of Outlayer.Items} items + */ +Outlayer.prototype.hide = function( items ) { + if ( !items || !items.length ) { + return; + } + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + item.hide(); + } +}; + +/** + * get Outlayer.Item, given an Element + * @param {Element} elem + * @param {Function} callback + * @returns {Outlayer.Item} item + */ +Outlayer.prototype.getItem = function( elem ) { + // loop through items to get the one that matches + for ( var i=0, len = this.items.length; i < len; i++ ) { + var item = this.items[i]; + if ( item.element === elem ) { + // return item + return item; + } + } +}; + +/** + * get collection of Outlayer.Items, given Elements + * @param {Array} elems + * @returns {Array} items - Outlayer.Items + */ +Outlayer.prototype.getItems = function( elems ) { + if ( !elems || !elems.length ) { + return; + } + var items = []; + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + var item = this.getItem( elem ); + if ( item ) { + items.push( item ); + } + } + + return items; +}; + +/** + * remove element(s) from instance and DOM + * @param {Array or NodeList or Element} elems + */ +Outlayer.prototype.remove = function( elems ) { + elems = makeArray( elems ); + + var removeItems = this.getItems( elems ); + + this._itemsOn( removeItems, 'remove', function() { + this.emitEvent( 'removeComplete', [ this, removeItems ] ); + }); + + for ( var i=0, len = removeItems.length; i < len; i++ ) { + var item = removeItems[i]; + item.remove(); + // remove item from collection + var index = indexOf( this.items, item ); + this.items.splice( index, 1 ); + } +}; + +// ----- destroy ----- // + +// remove and disable Outlayer instance +Outlayer.prototype.destroy = function() { + // clean up dynamic styles + var style = this.element.style; + style.height = ''; + style.position = ''; + style.width = ''; + // destroy items + for ( var i=0, len = this.items.length; i < len; i++ ) { + var item = this.items[i]; + item.destroy(); + } + + this.unbindResize(); + + delete this.element.outlayerGUID; +}; + +// -------------------------- data -------------------------- // + +/** + * get Outlayer instance from element + * @param {Element} elem + * @returns {Outlayer} + */ +Outlayer.data = function( elem ) { + var id = elem && elem.outlayerGUID; + return id && instances[ id ]; +}; + +// -------------------------- -------------------------- // + +// copy an object on the Outlayer prototype +// used in options and settings +function copyOutlayerProto( obj, property ) { + obj.prototype[ property ] = extend( {}, Outlayer.prototype[ property ] ); +} + +// -------------------------- create Outlayer class -------------------------- // + +/** + * create a layout class + * @param {String} namespace + */ +Outlayer.create = function( namespace, options ) { + // sub-class Outlayer + function Layout() { + Outlayer.apply( this, arguments ); + } + + extend( Layout.prototype, Outlayer.prototype ); + + copyOutlayerProto( Layout, 'options' ); + copyOutlayerProto( Layout, 'settings' ); + + extend( Layout.prototype.options, options ); + + Layout.prototype.settings.namespace = namespace; + + Layout.data = Outlayer.data; + + // sub-class Item + Layout.Item = function LayoutItem() { + Item.apply( this, arguments ); + }; + + Layout.Item.prototype = new Outlayer.Item(); + + Layout.prototype.settings.item = Layout.Item; + + // -------------------------- declarative -------------------------- // + + /** + * allow user to initialize Outlayer via .js-namespace class + * options are parsed from data-namespace-option attribute + */ + docReady( function() { + var dashedNamespace = toDashed( namespace ); + var elems = document.querySelectorAll( '.js-' + dashedNamespace ); + var dataAttr = 'data-' + dashedNamespace + '-options'; + + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + var attr = elem.getAttribute( dataAttr ); + var options; + try { + options = attr && JSON.parse( attr ); + } catch ( error ) { + // log error, do not initialize + if ( console ) { + console.error( 'Error parsing ' + dataAttr + ' on ' + + elem.nodeName.toLowerCase() + ( elem.id ? '#' + elem.id : '' ) + ': ' + + error ); + } + continue; + } + // initialize + var instance = new Layout( elem, options ); + // make available via $().data('layoutname') + if ( jQuery ) { + jQuery.data( elem, namespace, instance ); + } + } + }); + + // -------------------------- jQuery bridge -------------------------- // + + // make into jQuery plugin + if ( jQuery && jQuery.bridget ) { + jQuery.bridget( namespace, Layout ); + } + + return Layout; +}; + +// -------------------------- transport -------------------------- // + +// back in global +Outlayer.Item = Item; +window.Outlayer = Outlayer; + +})( window ); + +/*! + * Masonry v3.0.1 + * Cascading grid layout library + * http://masonry.desandro.com + * MIT License + * by David DeSandro + */ + +( function( window ) { + +'use strict'; + +// vars +// var document = window.document; + +// -------------------------- helpers -------------------------- // + +var indexOf = Array.prototype.indexOf ? + function( items, value ) { + return items.indexOf( value ); + } : + function ( items, value ) { + for ( var i=0, len = items.length; i < len; i++ ) { + var item = items[i]; + if ( item === value ) { + return i; + } + } + return -1; + }; + +// -------------------------- masonryDefinition -------------------------- // + +// used for AMD definition and requires +function masonryDefinition( Outlayer, getSize ) { + // create an Outlayer layout class + var Masonry = Outlayer.create('masonry'); + + Masonry.prototype._resetLayout = function() { + this.getSize(); + this._getMeasurement( 'columnWidth', 'outerWidth' ); + this._getMeasurement( 'gutter', 'outerWidth' ); + this.measureColumns(); + + // reset column Y + var i = this.cols; + this.colYs = []; + while (i--) { + this.colYs.push( 0 ); + } + + this.maxY = 0; + }; + + Masonry.prototype.measureColumns = function() { + // if columnWidth is 0, default to outerWidth of first item + var firstItem = this.items[0]; + var firstItemElem = firstItem && firstItem.element; + if ( !this.columnWidth ) { + // columnWidth fall back to item of first element + this.columnWidth = firstItemElem ? getSize( firstItemElem ).outerWidth : + // or size of container + this.size.innerWidth; + } + this.columnWidth += this.gutter; + + this.cols = Math.floor( ( this.size.innerWidth + this.gutter ) / this.columnWidth ); + this.cols = Math.max( this.cols, 1 ); + }; + + Masonry.prototype._getItemLayoutPosition = function( item ) { + item.getSize(); + // how many columns does this brick span + var colSpan = Math.ceil( item.size.outerWidth / this.columnWidth ); + colSpan = Math.min( colSpan, this.cols ); + + var colGroup = this._getColGroup( colSpan ); + // get the minimum Y value from the columns + var minimumY = Math.min.apply( Math, colGroup ); + var shortColIndex = indexOf( colGroup, minimumY ); + + // position the brick + var position = { + x: this.columnWidth * shortColIndex, + y: minimumY + }; + + // apply setHeight to necessary columns + var setHeight = minimumY + item.size.outerHeight; + var setSpan = this.cols + 1 - colGroup.length; + for ( var i = 0; i < setSpan; i++ ) { + this.colYs[ shortColIndex + i ] = setHeight; + } + + return position; + }; + + /** + * @param {Number} colSpan - number of columns the element spans + * @returns {Array} colGroup + */ + Masonry.prototype._getColGroup = function( colSpan ) { + if ( colSpan === 1 ) { + // if brick spans only one column, use all the column Ys + return this.colYs; + } + + var colGroup = []; + // how many different places could this brick fit horizontally + var groupCount = this.cols + 1 - colSpan; + // for each group potential horizontal position + for ( var i = 0; i < groupCount; i++ ) { + // make an array of colY values for that one group + var groupColYs = this.colYs.slice( i, i + colSpan ); + // and get the max value of the array + colGroup[i] = Math.max.apply( Math, groupColYs ); + } + return colGroup; + }; + + Masonry.prototype._manageStamp = function( stamp ) { + var stampSize = getSize( stamp ); + var offset = this._getElementOffset( stamp ); + // get the columns that this stamp affects + var firstX = this.options.isOriginLeft ? offset.left : offset.right; + var lastX = firstX + stampSize.outerWidth; + var firstCol = Math.floor( firstX / this.columnWidth ); + firstCol = Math.max( 0, firstCol ); + var lastCol = Math.floor( lastX / this.columnWidth ); + lastCol = Math.min( this.cols - 1, lastCol ); + // set colYs to bottom of the stamp + var stampMaxY = ( this.options.isOriginTop ? offset.top : offset.bottom ) + + stampSize.outerHeight; + for ( var i = firstCol; i <= lastCol; i++ ) { + this.colYs[i] = Math.max( stampMaxY, this.colYs[i] ); + } + }; + + Masonry.prototype._getContainerSize = function() { + this.maxY = Math.max.apply( Math, this.colYs ); + return { + height: this.maxY + }; + }; + + return Masonry; +} + +// -------------------------- transport -------------------------- // + +if ( typeof define === 'function' && define.amd ) { + // AMD + define( [ + 'outlayer', + 'get-size' + ], + masonryDefinition ); +} else { + // browser global + window.Masonry = masonryDefinition( + window.Outlayer, + window.getSize + ); +} + +})( window ); \ No newline at end of file