forked from s-yadav/angulargrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangulargrid.js
706 lines (586 loc) · 25 KB
/
angulargrid.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
/*
angularGrid.js v 0.6.5
Author: Sudhanshu Yadav
Copyright (c) 2015-2016 Sudhanshu Yadav - ignitersworld.com , released under the MIT license.
Demo on: http://ignitersworld.com/lab/angulargrid/
Documentation and download on https://github.com/s-yadav/angulargrid
*/
/* module to create pinterest like responsive masonry grid system for angular */
;(function (root, factory) {
if (typeof module !== 'undefined' && module.exports) {
// CommonJS
module.exports = factory(require('angular'), root);
} else if (typeof define === 'function' && define.amd) {
// AMD
define(['angular'], function (angular) {
return factory(angular, root);
});
} else {
// Global Variables
factory(root.angular, root);
}
}(this, function (angular, window, undefined) {
"use strict";
//defaults for plugin
var defaults = {
gridWidth: 300, //minumum width of a grid, this may increase to take whole space of container
gutterSize: 10, //spacing between two grid,
gridNo: 'auto', // grid number, by default calculate auto matically
direction: 'ltor', //direction of grid item
refreshOnImgLoad: true, // to make a refresh on image load inside container
cssGrid: false,
performantScroll: false,
pageSize: 'auto', //decide based on screen size
scrollContainer: 'body',
infiniteScrollDelay: 3000,
infiniteScrollDistance: 100,
};
var $ = angular.element;
var camelCaseToHyphenCase = function(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};
//css for the clones
var cloneCss = {
visibility: 'hidden',
opacity: 0,
top: 0,
left: 0,
width: ''
};
var single = (function() {
var $elm = $(window);
return function(elm) {
$elm[0] = elm;
return $elm;
};
}());
//function to check if image is loaded
function imageLoaded(img) {
return img.complete && (typeof img.naturalWidth === 'undefined' || img.naturalWidth !== 0);
}
//function to covert domlist to array
function domToAry(list) {
return Array.prototype.slice.call(list);
}
//add required css
$(document.head).append('<style>' +
'.ag-no-transition{' +
'-webkit-transition: none !important;' +
'transition: none !important;' +
'} ' +
'.angular-grid{position : relative;} ' +
'.angular-grid > *{opacity : 0} ' +
'.angular-grid > .angular-grid-item{opacity : 1}' + '</style>');
return angular.module('angularGrid', [])
.directive('angularGrid', ['$timeout', '$window', '$q', 'angularGridInstance',
function($timeout, $window, $q, angularGridInstance) {
return {
restrict: 'A',
scope: {
model: '=angularGrid',
/** deprecated options ***/
dep_gridWidth: '=gridWidth',
dep_gutterSize: '=gutterSize',
dep_refreshOnImgLoad: '=refreshOnImgLoad',
dep_direction: '=direction',
dep_cssGrid: '=cssGrid',
dep_options: '=angularGridOptions',
dep_gridNo: '=gridNo',
dep_agId: '@angularGridId',
/** deprecated options end***/
gridNo: '=agGridNo',
gridWidth: '=agGridWidth',
gutterSize: '=agGutterSize',
refreshOnImgLoad: '=agRefreshOnImgLoad',
direction: '=agDirection',
cssGrid: '=agCssGrid',
options: '=agOptions',
agId: '@',
pageSize: '=agPageSize',
performantScroll: '=agPerformantScroll',
scrollContainer: '@agScrollContainer',
infiniteScroll: '&agInfiniteScroll',
infiniteScrollDistance: '=agInfiniteScrollDistance',
infiniteScrollDelay: '=agInfiniteScrollDelay',
reflowedCB: '&agReflowed'
},
link: function(scope, element, attrs) {
var domElm = element[0],
win = $($window),
agId = scope.agId || scope.dep_agId, // angularGridId is deprecated
listElms,
reflowCount = 0, //to keep tack of times reflowgrid been called
timeoutPromise;
element.addClass('angular-grid');
//get the user input options
var options;
//check deprecated options
['gridWidth', 'gutterSize', 'refreshOnImgLoad', 'direction', 'options', 'cssGrid','gridNo', 'agId'].forEach(function(key) {
var depKey = camelCaseToHyphenCase(key);
var correctKey = 'ag-' + camelCaseToHyphenCase(key);
if (key == 'options') depKey = "angular-grid-options";
if (key == 'agId') {
depKey = "angular-grid-id";
correctKey = "ag-id";
}
if (scope['dep_' + key] !== undefined) {
if (console && console.warn) console.warn(depKey + ' is deprecated. Use ' + correctKey + ' instead in template.');
}
});
function getOptions() {
options = {};
Object.keys(defaults).forEach(function(key) {
if (scope[key] !== undefined) {
options[key] = scope[key];
} else if (scope['dep_' + key] !== undefined) {
options[key] = scope['dep_' + key];
}
});
options = angular.extend({}, defaults, options, scope.options || scope.dep_options);
if (options.cssGrid) options.gutterSize = 0;
if (options.pageSize == 'auto') {
options.pageSize = window.offsetWidth >= 768 ? 2 : 3;
}
}
getOptions();
/********
code to allow performant scroll
*****/
var scrollNs = {}; //namespace for performantScroll
function findPos(obj, withRespectTo) {
withRespectTo = withRespectTo || document.body;
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
obj = obj.offsetParent;
} while (obj && obj != withRespectTo);
}
return {
left: curleft,
top: curtop
};
}
function getScrollContainerInfo() {
var container = $(document.querySelector(options.scrollContainer)),
contElm = container[0];
var $elm = options.scrollContainer === 'body' ? win : container;
return {
height: $elm[0].innerHeight || $elm[0].offsetHeight,
scrollHeight: contElm.scrollHeight,
startFrom: findPos(domElm, contElm).top,
$elm: $elm
};
}
//this method check what all elements should be present on dom at specific page
function calculatePageInfo(listElmPosInfo, scrollBodyHeight, colNo) {
scrollNs.pageInfo = [{
from: 0
}];
var elmInfo, from, to,
pageSize = options.pageSize,
scrollContHeight = scrollNs.scrollContInfo.height,
pageHeight = scrollContHeight * pageSize,
totalPages = Math.ceil(scrollBodyHeight / pageHeight),
pageNo = 0;
for (pageNo = 0; pageNo < totalPages; pageNo++) {
for (var idx = 0, ln = listElmPosInfo.length; idx < ln; idx++) {
elmInfo = listElmPosInfo[idx];
from = pageNo ? pageHeight * pageNo : 0;
to = pageHeight * (pageNo + 1);
if (elmInfo.bottom < from || elmInfo.top > to) {
if (elmInfo.top > to) break;
} else {
if (!scrollNs.pageInfo[pageNo]) scrollNs.pageInfo[pageNo] = {
from: idx
};
scrollNs.pageInfo[pageNo].to = idx;
}
}
}
scrollNs.pageInfo = scrollNs.pageInfo.map(function(page, idx) {
var fromPage = Math.max(idx - 1, 0),
toPage = Math.min(idx + 1, scrollNs.pageInfo.length - 1);
return {
from: scrollNs.pageInfo[fromPage].from,
to: scrollNs.pageInfo[toPage].to
};
});
}
//unbind/bind watchers
function bindWatchersOnVisible(visibleELm) {
var itemData, $item, i, ln;
//unbind watchers from all element
for (i = 0, ln = listElms.length; i < ln; i++) {
$item = single(listElms[i]);
itemData = $item.data();
if (itemData.$scope) {
$item.data('_agOldWatchers', itemData.$scope.$$watchers);
itemData.$scope.$$watchers = [];
}
}
//bind watchers on all visible element
for (i = 0, ln = visibleELm.length; i < ln; i++) {
itemData = single(visibleELm[i]).data();
if (itemData.$scope) {
itemData.$scope.$$watchers = itemData._agOldWatchers || [];
//trigger digest on each child scope
itemData.$scope.$digest();
}
}
}
function refreshDomElm(scrollTop) {
scrollNs.lastScrollPosition = scrollTop;
var filteredElm;
if (scrollNs.isBusy) return;
var currentPage = 0,
pageSize = options.pageSize;
if (scrollTop > scrollNs.scrollContInfo.startFrom + scrollNs.scrollContInfo.height * pageSize) {
currentPage = Math.floor((scrollTop - scrollNs.scrollContInfo.startFrom) / (scrollNs.scrollContInfo.height * pageSize));
}
if (currentPage == scrollNs.lastPage) return;
scrollNs.lastPage = currentPage;
var curPageInfo = scrollNs.pageInfo[currentPage];
if (curPageInfo) {
element.children().detach();
filteredElm = Array.prototype.slice.call(listElms, curPageInfo.from, curPageInfo.to + 1);
bindWatchersOnVisible(filteredElm);
element.append(filteredElm);
}
}
/********
code to allow performant scroll end
*****/
/***** code for infiniteScroll start ******/
function reEnableInfiniteScroll() {
clearTimeout(scrollNs.infiniteScrollTimeout);
scrollNs.isLoading = false;
}
function infiniteScroll(scrollTop) {
if (scrollNs.isLoading || !scope.model.length) return;
var scrollHeight = scrollNs.scrollContInfo.scrollHeight,
contHeight = scrollNs.scrollContInfo.height;
if (scrollTop >= (scrollHeight - contHeight * (1 + options.infiniteScrollDistance / 100))) {
scrollNs.isLoading = true;
scope.infiniteScroll();
scrollNs.infiniteScrollTimeout = setTimeout(reEnableInfiniteScroll, options.infiniteScrollDelay);
}
}
/***** code for infiniteScroll end ******/
//scroll event on scroll container element to refresh dom depending on scroll positions
function scrollHandler() {
var scrollTop = this.scrollTop || this.scrollY;
if (options.performantScroll) refreshDomElm(scrollTop);
if (scope.infiniteScroll) infiniteScroll(scrollTop);
}
setTimeout(function() {
scrollNs.scrollContInfo = getScrollContainerInfo();
scrollNs.scrollContInfo.$elm.on('scroll', scrollHandler);
}, 0);
//function to get column width and number of columns
function getColWidth() {
var contWidth = domElm.offsetWidth,
clone; // a clone to calculate width without transition
if (options.cssGrid) {
clone = $(listElms[0]).clone();
clone.css(cloneCss).addClass('ag-no-transition ag-clone');
element.append(clone);
var width = clone[0].offsetWidth;
clone.remove();
return {
no: width ? Math.floor((contWidth + 12) / width) : 0,
width: width
};
}
var colWidth = options.gridNo == 'auto' ? options.gridWidth : Math.floor(contWidth / options.gridNo) - options.gutterSize,
cols = options.gridNo == 'auto' ? Math.floor((contWidth + options.gutterSize) / (colWidth + options.gutterSize)) : options.gridNo,
remainingSpace = ((contWidth + options.gutterSize) % (colWidth + options.gutterSize));
colWidth = colWidth + Math.floor(remainingSpace / cols);
return {
no: cols,
width: colWidth
};
}
//method check for image loaded inside a container and trigger callback
function afterImageLoad(container, options) {
var beforeLoad = options.beforeLoad || angular.noop,
onLoad = options.onLoad || angular.noop,
isLoaded = options.isLoaded || angular.noop,
onFullLoad = options.onFullLoad || angular.noop,
ignoreCheck = options.ignoreCheck || angular.noop,
allImg = container.find('img'),
loadedImgPromises = [];
domToAry(allImg).forEach(function(img) {
if(!img.src) return;
beforeLoad(img);
if (!imageLoaded(img) && !ignoreCheck(img)) {
loadedImgPromises.push($q(function(resolve, reject) {
img.onload = function() {
onLoad(img);
resolve();
};
img.onerror = reject;
}));
} else {
isLoaded(img);
}
});
if (loadedImgPromises.length) {
$q.all(loadedImgPromises).then(onFullLoad, onFullLoad);
} else {
setTimeout(function() {
onFullLoad();
}, 0);
}
}
//function to reflow grids
function reflowGrids() {
//return if there are no elements
if(!(listElms && listElms.length )) return;
reflowCount++;
//claclulate width of all element
var colInfo = getColWidth(),
colWidth = colInfo.width,
cols = colInfo.no,
i;
if (!cols) return;
//initialize listRowBottom
var lastRowBottom = [];
for (i = 0; i < cols; i++) {
lastRowBottom.push(0);
}
//if image actual width and actual height is defined update image size so that it dosent cause reflow on image load
domToAry(listElms).forEach(function(item) {
var $item = single(item);
domToAry($item.find('img')).forEach(function(img) {
var $img = $(img);
//if image is already loaded don't do anything
if ($img.hasClass('img-loaded')) {
$img.css('height', '');
return;
}
//set the item width and no transition state so image width can be calculated properly
$item.addClass('ag-no-transition');
$item.css('width', colWidth + 'px');
var actualWidth = $img.attr('actual-width') || $img.attr('data-actual-width'),
actualHeight = $img.attr('actual-height') || $img.attr('data-actual-height');
if (actualWidth && actualHeight) {
$img.css('height', (actualHeight * img.width / actualWidth) + 'px');
}
});
$item.removeClass('ag-no-transition');
});
//get all list items new height
var clones = listElms.clone();
clones.addClass('ag-no-transition ag-clone');
var clonesCssObj = angular.extend({}, cloneCss);
clonesCssObj.width = colWidth + 'px';
clones.css(clonesCssObj);
element.append(clones);
//For cloned element again we have to check if image loaded (IOS only)
(function(reflowIndx) {
afterImageLoad(clones, {
ignoreCheck: function(img) {
return !single(img).hasClass('img-loaded');
},
onFullLoad: function() {
//if its older reflow don't do any thing
if (reflowIndx < reflowCount) {
clones.remove();
return;
}
var listElmHeights = [],
listElmPosInfo = [],
item, i, ln;
//find height with clones
for (i = 0, ln = clones.length; i < ln; i++) {
listElmHeights.push(clones[i].offsetHeight);
}
//set new positions
for (i = 0, ln = listElms.length; i < ln; i++) {
item = single(listElms[i]);
var height = listElmHeights[i],
top = Math.min.apply(Math, lastRowBottom),
col = lastRowBottom.indexOf(top);
//update lastRowBottom value
lastRowBottom[col] = top + height + options.gutterSize;
//set top and left of list items
var posX = col * (colWidth + options.gutterSize);
var cssObj = {
position: 'absolute',
top: top + 'px'
};
if (options.direction == 'rtol') {
cssObj.right = posX + 'px';
} else {
cssObj.left = posX + 'px';
}
cssObj.width = colWidth + 'px';
//add position info of each grids
listElmPosInfo.push({
top: top,
bottom: top + height
});
item.css(cssObj).addClass('angular-grid-item');
}
//set the height of container
var contHeight = Math.max.apply(Math, lastRowBottom);
element.css('height', contHeight + 'px');
clones.remove();
//update the scroll container info
if (options.performantScroll || scope.infiniteScroll) {
scrollNs.scrollContInfo = getScrollContainerInfo();
}
//if performantScroll is enabled calculate the page info, and reflect dom elements to reflect visible pages
if (options.performantScroll) {
scrollNs.lastPage = null;
calculatePageInfo(listElmPosInfo, contHeight, cols);
scrollNs.isBusy = false;
refreshDomElm(scrollNs.lastScrollPosition || 0);
}
//re enable infiniteScroll
reEnableInfiniteScroll();
scope.reflowedCB({
$event: {
id: scope.agId || null
}
});
}
});
}(reflowCount));
}
//function to handle asynchronous image loading
function handleImage() {
var reflowPending = false;
domToAry(listElms).forEach(function(listItem) {
var $listItem = $(listItem),
allImg = $listItem.find('img');
if (!allImg.length) {
return;
}
//add image loading class on list item
$listItem.addClass('img-loading');
afterImageLoad($listItem, {
beforeLoad: function(img) {
single(img).addClass('img-loading');
},
isLoaded: function(img) {
single(img).removeClass('img-loading').addClass('img-loaded');
},
onLoad: function(img) {
if (!reflowPending && options.refreshOnImgLoad) {
reflowPending = true;
$timeout(function() {
reflowGrids();
reflowPending = false;
}, 100);
}
single(img).removeClass('img-loading').addClass('img-loaded');
},
onFullLoad: function() {
$listItem.removeClass('img-loading').addClass('img-loaded');
}
});
});
}
//function to get list elements excluding clones
function getListElms() {
return $(domToAry(element.children()).filter(function(elm) {
return !single(elm).hasClass('ag-clone');
}));
}
//function to check for ng animation
function ngCheckAnim() {
var leavingElm = domToAry(listElms).filter(function(elm) {
return single(elm).hasClass('ng-leave');
});
return $q(function(resolve) {
if (!leavingElm.length) {
resolve();
} else {
single(leavingElm[0]).one('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd', function() {
$timeout(function() {
listElms = getListElms();
resolve();
});
});
}
});
}
//watch on modal key
function watch() {
scrollNs.isBusy = true;
$timeout(function() {
listElms = getListElms();
ngCheckAnim().then(function() {
//handle images
handleImage();
$timeout(function() {
//to handle scroll appearance
reflowGrids();
});
});
});
}
scope.$watch('model', watch, true);
//watch option for changes
function watchOptions() {
getOptions();
if (listElms) reflowGrids();
}
scope.$watch('options', watchOptions, true);
Object.keys(defaults).forEach(function(key) {
if (scope[key] !== undefined) scope.$watch(key, watchOptions);
});
//listen window resize event and reflow grids after a timeout
var lastDomWidth = domElm.offsetWidth;
function windowResizeCallback() {
scrollNs.isBusy = true;
var contWidth = domElm.offsetWidth;
if (lastDomWidth == contWidth) return;
lastDomWidth = contWidth;
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
timeoutPromise = $timeout(function() {
//caclulate container info
if (options.performantScroll) {
element.children().detach();
element.append(listElms);
}
reflowGrids();
}, 100);
}
win.on('resize', windowResizeCallback);
//add instance to factory if id is assigned
if (agId) {
angularGridInstance[agId] = {
refresh: function() {
watch();
},
handleScroll: function(scrollTop) {
if (options.performantScroll) refreshDomElm(scrollTop);
if (scope.infiniteScroll) infiniteScroll(scrollTop);
}
};
}
//destroy on refrences and events on scope destroy
scope.$on('$destroy', function() {
if (agId) delete angularGridInstance[agId];
win.off('resize', windowResizeCallback);
clearTimeout(scrollNs.infiniteScrollTimeout);
if (scrollNs.scrollContInfo) scrollNs.scrollContInfo.$elm.off('scroll', scrollHandler);
});
}
};
}
])
//a factory to store angulargrid instances which can be injected to controllers or directive
.factory('angularGridInstance', function() {
var angularGridInstance = {};
return angularGridInstance;
})
.name;
}));