forked from metafizzy/isotope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.isotope.js
1282 lines (1012 loc) · 38.1 KB
/
jquery.isotope.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Isotope v1.0.110214
* An exquisite jQuery plugin for magical layouts
* http://isotope.metafizzy.co
*
* Commercial use requires one-time license fee
* http://metafizzy.co/#licenses
*
* Copyright 2011 David DeSandro / Metafizzy
*/
(function( window, $, undefined ){
// ========================= getStyleProperty by kangax ===============================
// http://perfectionkills.com/feature-testing-css-properties/
var getStyleProperty = (function(){
var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
var _cache = { };
function getStyleProperty(propName, element) {
element = element || document.documentElement;
var style = element.style,
prefixed,
uPropName,
i, l;
// check cache only when no element is given
if (arguments.length === 1 && typeof _cache[propName] === 'string') {
return _cache[propName];
}
// test standard property first
if (typeof style[propName] === 'string') {
return (_cache[propName] = propName);
}
// capitalize
uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
// test vendor specific properties
for (i=0, l=prefixes.length; i<l; i++) {
prefixed = prefixes[i] + uPropName;
if (typeof style[prefixed] === 'string') {
return (_cache[propName] = prefixed);
}
}
}
return getStyleProperty;
}());
// ========================= miniModernizr ===============================
// <3<3<3 and thanks to Faruk and Paul for doing the heavy lifting
/*!
* Modernizr v1.6ish: miniModernizr for Isotope
* http://www.modernizr.com
*
* Developed by:
* - Faruk Ates http://farukat.es/
* - Paul Irish http://paulirish.com/
*
* Copyright (c) 2009-2010
* Dual-licensed under the BSD or MIT licenses.
* http://www.modernizr.com/license/
*/
/*
* This version whittles down the script just to check support for
* CSS transitions, transforms, and 3D transforms.
*/
var docElement = document.documentElement,
vendorCSSPrefixes = ' -o- -moz- -ms- -webkit- -khtml- '.split(' '),
tests = [
{
name : 'csstransforms',
getResult : function() {
return !!getStyleProperty('transform');
}
},
{
name : 'csstransforms3d',
getResult : function() {
var test = !!getStyleProperty('perspective');
// double check for Chrome's false positive
if ( test ){
var st = document.createElement('style'),
div = document.createElement('div'),
mq = '@media (' + vendorCSSPrefixes.join('transform-3d),(') + 'modernizr)';
st.textContent = mq + '{#modernizr{height:3px}}';
(document.head || document.getElementsByTagName('head')[0]).appendChild(st);
div.id = 'modernizr';
docElement.appendChild(div);
test = div.offsetHeight === 3;
st.parentNode.removeChild(st);
div.parentNode.removeChild(div);
}
return !!test;
}
},
{
name : 'csstransitions',
getResult : function() {
return !!getStyleProperty('transitionProperty');
}
}
],
i, len = tests.length
;
if ( window.Modernizr ) {
// if there's a previous Modernzir, check if there are necessary tests
for ( i=0; i < len; i++ ) {
var test = tests[i];
if ( !Modernizr.hasOwnProperty( test.name ) ) {
// if test hasn't been run, use addTest to run it
Modernizr.addTest( test.name, test.getResult );
}
}
} else {
// or create new mini Modernizr that just has the 3 tests
window.Modernizr = (function(){
var miniModernizr = {
_version : '1.6ish: miniModernizr for Isotope'
},
classes = [],
test, result, className;
// Run through tests
for ( i=0; i < len; i++ ) {
test = tests[i];
result = test.getResult();
miniModernizr[ test.name ] = result;
className = ( result ? '' : 'no-' ) + test.name;
classes.push( className );
}
// Add the new classes to the <html> element.
docElement.className += ' ' + classes.join( ' ' );
return miniModernizr;
})();
}
// ========================= isoTransform ===============================
/**
* provides hooks for .css({ scale: value, translate: x y })
* Progressively enhanced CSS transforms
* Uses hardware accelerated 3D transforms for Safari
* or falls back to 2D transforms.
*/
var isoTransform = {
transformProp : getStyleProperty('transform'),
fnUtils : Modernizr.csstransforms3d ?
{ // 3D transform functions
translate : function ( position ) {
return 'translate3d(' + position[0] + 'px, ' + position[1] + 'px, 0) ';
},
scale : function ( scale ) {
return 'scale3d(' + scale + ', ' + scale + ', 1) ';
}
} :
{ // 2D transform functions
translate : function ( position ) {
return 'translate(' + position[0] + 'px, ' + position[1] + 'px) ';
},
scale : function ( scale ) {
return 'scale(' + scale + ') ';
}
}
,
set : function( elem, name, value ) {
// unpack current transform data
var data = $( elem ).data('transform') || {},
// extend new value over current data
newData = {},
fnName,
transformObj = {};
// overwrite new data
newData[ name ] = value;
$.extend( data, newData );
for ( fnName in data ) {
var transformValue = data[ fnName ],
getFn = isoTransform.fnUtils[ fnName ];
transformObj[ fnName ] = getFn( transformValue );
}
// get proper order
// ideally, we could loop through this give an array, but since we only have
// a couple transforms we're keeping track of, we'll do it like so
var translateFn = transformObj.translate || '',
scaleFn = transformObj.scale || '',
valueFns = translateFn + scaleFn;
// set data back in elem
$( elem ).data( 'transform', data );
// sorting so scale always comes before
value = valueFns;
// set name to vendor specific property
elem.style[ isoTransform.transformProp ] = valueFns;
}
};
// ==================== scale ===================
$.cssNumber.scale = true;
$.cssHooks.scale = {
set: function( elem, value ) {
if ( typeof value === 'string' ) {
value = parseFloat( value );
}
isoTransform.set( elem, 'scale', value );
},
get: function( elem, computed ) {
var transform = $.data( elem, 'transform' );
return transform && transform.scale ? transform.scale : 1;
}
};
$.fx.step.scale = function( fx ) {
$.cssHooks.scale.set( fx.elem, fx.now+fx.unit );
};
// ==================== translate ===================
$.cssNumber.translate = true;
$.cssHooks.translate = {
set: function( elem, value ) {
// all this would be for public ease-of-use,
// but we're leaving it out since this add-on is
// only for internal-plugin use
// if ( typeof value === 'string' ) {
// value = value.split(' ');
// }
//
//
// var i, val;
// for ( i = 0; i < 2; i++ ) {
// val = value[i];
// if ( typeof val === 'string' ) {
// val = parseInt( val );
// }
// }
isoTransform.set( elem, 'translate', value );
},
get: function( elem, computed ) {
var transform = $.data( elem, 'transform' );
return transform && transform.translate ? transform.translate : [ 0, 0 ];
}
};
/*!
* smartresize: debounced resize event for jQuery
* http://github.com/lrbabe/jquery-smartresize
*
* Copyright (c) 2009 Louis-Remi Babe
* Licensed under the GPL license.
* http://docs.jquery.com/License
*
*/
var $event = $.event,
resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
// ========================= Isotope ===============================
// our "Widget" object constructor
$.Isotope = function( options, element ){
this.element = $( element );
this._create( options );
this._init();
};
$.Isotope.prototype = {
options : {
resizable: true,
layoutMode : 'masonry',
containerClass : 'isotope',
itemClass : 'isotope-item',
hiddenClass : 'isotope-hidden',
hiddenStyle : Modernizr.csstransforms && !$.browser.opera ?
{ opacity : 0, scale : 0.001 } : // browsers support CSS transforms, not Opera
{ opacity : 0 }, // other browsers, including Opera
visibleStyle : Modernizr.csstransforms && !$.browser.opera ?
{ opacity : 1, scale : 1 } : // browsers support CSS transforms, not Opera
{ opacity : 1 }, // other browsers, including Opera
animationEngine : $.browser.opera ? 'jquery' : 'best-available',
animationOptions: {
queue: false,
duration: 800
},
sortBy : 'original-order',
sortAscending : true,
resizesContainer : true
},
_filterFind: function( $elems, selector ) {
return selector ? $elems.filter( selector ).add( $elems.find( selector ) ) : $elems;
},
// sets up widget
_create : function( options ) {
this.options = $.extend( true, {}, this.options, options );
this.isNew = {};
this.styleQueue = [];
this.elemCount = 0;
// need to get atoms
this.$allAtoms = this._filterFind( this.element.children(), this.options.itemSelector );
this.element.css({
overflow : 'hidden',
position : 'relative'
});
var jQueryAnimation = false;
// get applyStyleFnName
switch ( this.options.animationEngine.toLowerCase().replace( /[ _\-]/g, '') ) {
case 'none' :
this.applyStyleFnName = 'css';
break;
case 'jquery' :
this.applyStyleFnName = 'animate';
jQueryAnimation = true;
break;
case 'bestavailable' :
default :
this.applyStyleFnName = Modernizr.csstransitions ? 'css' : 'animate';
}
this.usingTransforms = Modernizr.csstransforms && Modernizr.csstransitions && !jQueryAnimation;
this.positionFn = this.usingTransforms ? this._translate : this._positionAbs;
// sorting
var originalOrderSorter = {
'original-order' : function( $elem, instance ) {
return instance.elemCount;
}
};
this.options.getSortData = $.extend( this.options.getSortData, originalOrderSorter );
this._setupAtoms( this.$allAtoms );
// get top left position of where the bricks should be
var $cursor = $( document.createElement('div') );
this.element.prepend( $cursor );
this.posTop = Math.round( $cursor.position().top );
this.posLeft = Math.round( $cursor.position().left );
$cursor.remove();
// add isotope class first time around
var instance = this;
setTimeout( function() {
instance.element.addClass( instance.options.containerClass );
}, 0 );
// bind resize method
if ( this.options.resizable ) {
$(window).bind( 'smartresize.isotope', function() {
instance.element.isotope('resize');
});
}
},
_isNewProp : function( prop ) {
return this.prevOpts ? ( this.options[ prop ] !== this.prevOpts[ prop ] ) : true;
},
// _init fires when your instance is first created
// (from the constructor above), and when you
// attempt to initialize the widget again (by the bridge)
// after it has already been initialized.
_init : function( callback ) {
// check if watched properties are new
var instance = this;
$.each( [ 'filter', 'sortBy', 'sortAscending' ], function( i, propName ){
instance.isNew[ propName ] = instance._isNewProp( propName );
});
if ( this.isNew.filter ) {
this.$filteredAtoms = this._filter( this.$allAtoms );
} else {
this.$filteredAtoms = this.$allAtoms;
}
if ( this.isNew.filter || this.isNew.sortBy || this.isNew.sortAscending ) {
this._sort();
}
this.reLayout( callback );
},
option: function( key, value ){
// get/change options AFTER initialization:
// you don't have to support all these cases,
// but here's how:
// signature: $('#foo').bar({ cool:false });
if ( $.isPlainObject( key ) ){
this.options = $.extend(true, this.options, key);
// signature: $('#foo').option('cool'); - getter
} else if ( key && typeof value === "undefined" ){
return this.options[ key ];
// signature: $('#foo').bar('option', 'baz', false);
} else {
this.options[ key ] = value;
}
return this; // make sure to return the instance!
},
// ====================== Adding ======================
_setupAtoms : function( $atoms ) {
// base style for atoms
var atomStyle = { position: 'absolute' };
if ( this.usingTransforms ) {
atomStyle.left = 0;
atomStyle.top = 0;
}
$atoms.css( atomStyle ).addClass( this.options.itemClass );
this.updateSortData( $atoms, true );
},
// ====================== Filtering ======================
_filter : function( $atoms ) {
var $filteredAtoms,
filter = this.options.filter === '' ? '*' : this.options.filter;
if ( !filter ) {
$filteredAtoms = $atoms;
} else {
var hiddenClass = this.options.hiddenClass,
hiddenSelector = '.' + hiddenClass,
$visibleAtoms = $atoms.not( hiddenSelector ),
$hiddenAtoms = $atoms.filter( hiddenSelector ),
$atomsToShow = $hiddenAtoms;
$filteredAtoms = $atoms.filter( filter );
if ( filter !== '*' ) {
$atomsToShow = $hiddenAtoms.filter( filter );
var $atomsToHide = $visibleAtoms.not( filter ).toggleClass( hiddenClass );
$atomsToHide.addClass( hiddenClass );
this.styleQueue.push({ $el: $atomsToHide, style: this.options.hiddenStyle });
}
this.styleQueue.push({ $el: $atomsToShow, style: this.options.visibleStyle });
$atomsToShow.removeClass( hiddenClass );
}
return $filteredAtoms;
},
// ====================== Sorting ======================
updateSortData : function( $atoms, isIncrementingElemCount ) {
var instance = this,
getSortData = this.options.getSortData,
key, $this, sortData;
$atoms.each(function(){
$this = $(this);
sortData = {};
// get value for sort data based on fn( $elem ) passed in
for ( key in getSortData ) {
sortData[ key ] = getSortData[ key ]( $this, instance );
}
// apply sort data to $element
$this.data( 'isotope-sort-data', sortData );
if ( isIncrementingElemCount ) {
instance.elemCount ++;
}
});
},
// used on all the filtered atoms
_sort : function() {
var instance = this,
getSorter = function( elem ) {
return $(elem).data('isotope-sort-data')[ instance.options.sortBy ];
},
sortDir = this.options.sortAscending ? 1 : -1;
sortFn = function( alpha, beta ) {
var a = getSorter( alpha ),
b = getSorter( beta );
return ( ( a > b ) ? 1 : ( a < b ) ? -1 : 0 ) * sortDir;
};
this.$filteredAtoms.sort( sortFn );
return this;
},
// ====================== Layout ======================
_translate : function( x, y ) {
return { translate : [ x, y ] };
},
_positionAbs : function( x, y ) {
return { left: x, top: y };
},
_pushPosition : function( $elem, x, y ) {
var position = this.positionFn( x, y );
this.styleQueue.push({ $el: $elem, style: position });
},
// ====================== General Layout ======================
// used on collection of atoms (should be filtered, and sorted before )
// accepts atoms-to-be-laid-out to start with
layout : function( $elems, callback ) {
var layoutMode = this.options.layoutMode,
layoutMethod = '_' + layoutMode;
// layout logic
this[ '_' + layoutMode + 'Layout' ]( $elems );
// set the size of the container
if ( this.options.resizesContainer ) {
var containerStyle = this[ '_' + layoutMode + 'GetContainerSize' ]();
this.styleQueue.push({ $el: this.element, style: containerStyle });
}
// are we animating the layout arrangement?
// use plugin-ish syntax for css or animate
var styleFn = ( this.applyStyleFnName === 'animate' && !this.isLaidOut ) ?
'css' : this.applyStyleFnName,
animOpts = this.options.animationOptions;
// process styleQueue
$.each( this.styleQueue, function( i, obj ){
// have to extend animation to play nice with jQuery
obj.$el[ styleFn ]( obj.style, $.extend( {}, animOpts ) );
});
// clear out queue for next time
this.styleQueue = [];
// provide $elems as context for the callback
if ( callback ) {
callback.call( $elems );
}
this.isLaidOut = true;
return this;
},
resize : function() {
return this[ '_' + this.options.layoutMode + 'Resize' ]();
},
reLayout : function( callback ) {
return this[ '_' + this.options.layoutMode + 'Reset' ]()
.layout( this.$filteredAtoms, callback );
},
// ====================== Convenience methods ======================
// adds a jQuery object of items to a isotope container
addItems : function( $content, callback ) {
var $newAtoms = this._filterFind( $content, this.options.itemSelector );
this._setupAtoms( $newAtoms );
// add new atoms to atoms pools
// FIXME : this breaks shuffle order and returns to original order
this.$allAtoms = this.$allAtoms.add( $newAtoms );
if ( callback ) {
callback( $newAtoms );
}
},
// convienence method for adding elements properly to any layout
insert : function( $content, callback ) {
this.element.append( $content );
var instance = this;
this.addItems( $content, function( $newAtoms ) {
$filteredAtoms = instance._filter( $newAtoms );
instance.$filteredAtoms = instance.$filteredAtoms.add( $filteredAtoms );
});
this._sort().reLayout( callback );
},
// convienence method for working with Infinite Scroll
appended : function( $content, callback ) {
var instance = this;
this.addItems( $content, function( $newAtoms ){
instance.$filteredAtoms = instance.$filteredAtoms.add( $newAtoms );
instance.layout( $newAtoms, callback );
});
},
// removes elements from Isotope widget
remove : function( $content ) {
this.$allAtoms = this.$allAtoms.not( $content );
this.$filteredAtoms = this.$filteredAtoms.not( $content );
$content.remove();
},
_shuffleArray : function ( array ) {
var tmp, current, i = array.length;
if ( i ){
while(--i) {
current = ~~( Math.random() * (i + 1) );
tmp = array[current];
array[current] = array[i];
array[i] = tmp;
}
}
return array;
},
// HACKy should probably remove
shuffle : function( callback ) {
this.options.sortBy = 'shuffle';
this.$allAtoms = this._shuffleArray( this.$allAtoms );
this.$filteredAtoms = this._filter( this.$allAtoms );
return this.reLayout( callback );
},
// destroys widget, returns elements and container back (close) to original style
destroy : function() {
var atomUnstyle = $.extend( this.options.visibleStyle, {
position: 'relative',
top: 'auto',
left: 'auto'
});
if ( this.usingTransforms ) {
atomUnstyle[ isoTransform.transformProp ] = 'none';
}
this.$allAtoms
.css( atomUnstyle )
.removeClass( this.options.hiddenClass );
this.element
.css({
width: 'auto',
height: 'auto'
})
.unbind('.isotope')
.removeClass( this.options.containerClass )
.removeData('isotope');
$(window).unbind('.isotope');
},
// Removes all atoms from the widget and the DOM, then redraws the layout.
flush: function() {
this.$allAtoms.empty();
this.$filteredAtoms.empty();
this.element.children().empty();
this.reLayout();
},
// calculates number of rows or columns
// requires columnWidth or rowHeight to be set on namespaced object
// i.e. this.masonry.columnWidth = 200
_getSegments : function( namespace, isRows ) {
var measure = isRows ? 'rowHeight' : 'columnWidth',
size = isRows ? 'height' : 'width',
UCSize = isRows ? 'Height' : 'Width',
segments = isRows ? 'rows' : 'cols';
this[ namespace ][ measure ] = ( this.options[ namespace ] && this.options[ namespace ][ measure ] ) || this.$allAtoms[ 'outer' + UCSize ](true);
// if colW == 0, back out before divide by zero
if ( !this[ namespace ][ measure ] ) {
$.error( measure + ' calculated to be zero. Stopping Isotope plugin before divide by zero. Check that the width of first child inside the isotope container is not zero.');
return this;
}
this[ size ] = this.element[ size ]();
this[ namespace ][ segments ] = Math.floor( this[ size ] / this[ namespace ][ measure ] );
this[ namespace ][ segments ] = Math.max( this[ namespace ][ segments ], 1 );
return this;
},
// ====================== LAYOUTS ======================
// ====================== Masonry ======================
_masonryPlaceBrick : function( $brick, setCount, setY ) {
// here, `this` refers to a child element or "brick"
// get the minimum Y value from the columns
var minimumY = Math.min.apply( Math, setY ),
setHeight = minimumY + $brick.outerHeight(true),
i = setY.length,
shortCol = i,
setSpan = this.masonry.cols + 1 - i,
x, y ;
// Which column has the minY value, closest to the left
while (i--) {
if ( setY[i] === minimumY ) {
shortCol = i;
}
}
// position the brick
x = this.masonry.columnWidth * shortCol + this.posLeft;
y = minimumY;
this._pushPosition( $brick, x, y );
// apply setHeight to necessary columns
for ( i=0; i < setSpan; i++ ) {
this.masonry.colYs[ shortCol + i ] = setHeight;
}
},
_masonryLayout : function( $elems ) {
var instance = this;
$elems.each(function(){
var $this = $(this),
//how many columns does this brick span
colSpan = Math.ceil( $this.outerWidth(true) / instance.masonry.columnWidth );
colSpan = Math.min( colSpan, instance.masonry.cols );
if ( colSpan === 1 ) {
// if brick spans only one column, just like singleMode
instance._masonryPlaceBrick( $this, instance.masonry.cols, instance.masonry.colYs );
} else {
// brick spans more than one column
// how many different places could this brick fit horizontally
var groupCount = instance.masonry.cols + 1 - colSpan,
groupY = [],
groupColY,
i;
// for each group potential horizontal position
for ( i=0; i < groupCount; i++ ) {
// make an array of colY values for that one group
groupColY = instance.masonry.colYs.slice( i, i+colSpan );
// and get the max value of the array
groupY[i] = Math.max.apply( Math, groupColY );
}
instance._masonryPlaceBrick( $this, groupCount, groupY );
}
});
},
// reset
_masonryReset : function() {
// layout-specific props
this.masonry = {};
// FIXME shouldn't have to call this again
this._getSegments('masonry');
var i = this.masonry.cols;
this.masonry.colYs = [];
while (i--) {
this.masonry.colYs.push( this.posTop );
}
return this;
},
_masonryResize : function() {
var prevColCount = this.masonry.cols;
// get updated colCount
this._getSegments('masonry');
if ( this.masonry.cols !== prevColCount ) {
// if column count has changed, do a new column cound
this.reLayout();
}
return this;
},
_masonryGetContainerSize : function() {
var containerHeight = Math.max.apply( Math, this.masonry.colYs ) - this.posTop;
return { height: containerHeight };
},
// ====================== fitRows ======================
_fitRowsLayout : function( $elems ) {
this.width = this.element.width();
var instance = this;
return $elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true),
x, y;
if ( instance.fitRows.x !== 0 && atomW + instance.fitRows.x > instance.width ) {
// if this element cannot fit in the current row
instance.fitRows.x = 0;
instance.fitRows.y = instance.fitRows.height;
}
// position the atom
x = instance.fitRows.x + instance.posLeft;
y = instance.fitRows.y + instance.posTop;
instance._pushPosition( $this, x, y );
instance.fitRows.height = Math.max( instance.fitRows.y + atomH, instance.fitRows.height );
instance.fitRows.x += atomW;
});
},
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
return this;
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResize : function() {
return this.reLayout();
},
// ====================== cellsByRow ======================
_cellsByRowReset : function() {
this.cellsByRow = {};
this._getSegments('cellsByRow');
this.cellsByRow.rowHeight = this.options.cellsByRow.rowHeight || this.$allAtoms.outerHeight(true);
return this;
},
_cellsByRowLayout : function( $elems ) {
var instance = this,
cols = this.cellsByRow.cols;
this.cellsByRow.atomsLen = $elems.length;
$elems.each( function( i ){
var $this = $(this),
x = ( i % cols + 0.5 ) * instance.cellsByRow.columnWidth
- $this.outerWidth(true) / 2 + instance.posLeft,
y = ( ~~( i / cols ) + 0.5 ) * instance.cellsByRow.rowHeight
- $this.outerHeight(true) / 2 + instance.posTop;
instance._pushPosition( $this, x, y );
});
return this;
},
_cellsByRowGetContainerSize : function() {
return { height : Math.ceil( this.cellsByRow.atomsLen / this.cellsByRow.cols ) * this.cellsByRow.rowHeight + this.posTop };
},
_cellsByRowResize : function() {
var prevCols = this.cellsByRow.cols;
this._getSegments('cellsByRow');
// if column count has changed, do a new column cound
if ( this.cellsByRow.cols !== prevCols ) {
this.reLayout();
}
return this;
},
// ====================== straightDown ======================
_straightDownReset : function() {
this.straightDown = {
y : 0
};
return this;
},
_straightDownLayout : function( $elems ) {
var instance = this;
$elems.each( function( i ){
var $this = $(this),
y = instance.straightDown.y + instance.posTop;
instance._pushPosition( $this, instance.posLeft, y );
instance.straightDown.y += $this.outerHeight(true);
});
return this;
},
_straightDownGetContainerSize : function() {
return { height : this.straightDown.y + this.posTop };
},
_straightDownResize : function() {
this.reLayout();
return this;
},