forked from haltu/muuri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmuuri.js
5728 lines (4678 loc) · 148 KB
/
muuri.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
/*!
* Muuri v0.3.0
* https://github.com/haltu/muuri
* Copyright (c) 2015, Haltu Oy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (global, factory) {
var libName = 'Muuri';
var Velocity;
var Hammer;
if (typeof define === 'function' && define.amd) {
define(function (require) {
Velocity = require.defined && require.defined('velocity') ? require('velocity') : undefined;
Hammer = require.defined && require.defined('hammer') ? require('hammer') : undefined;
return factory(global, libName, Velocity, Hammer);
});
}
else if (typeof module === 'object' && module.exports) {
try {
Velocity = require('velocity-animate');
}
catch (e) {}
try {
Hammer = require('hammerjs');
}
catch (e) {}
module.exports = factory(global, libName, Velocity, Hammer);
}
else {
Velocity = global.Velocity || global.jQuery.Velocity;
Hammer = global.Hammer;
global[libName] = factory(global, libName, Velocity, Hammer);
}
}(this, function (global, libName, Velocity, Hammer, undefined) {
'use strict';
// Get references to all the stuff we are using from the global scope.
var document = global.document;
var Object = global.Object;
var Array = global.Array;
var Math = global.Math;
var Error = global.Error;
var Element = global.Element;
// Types.
var typeFunction = 'function';
var typeString = 'string';
var typeNumber = 'number';
// Keep track of Grid instances.
var gridInstances = {};
// Keep track of Item instances.
var itemInstances = {};
// Keep track of the drag sort groups.
var dragSortGroups = {};
// No operation function.
var noop = function () {};
// Unique id which is used for Grid instances and Item instances.
// Should be incremented every time when used.
var uuid = 0;
// Get the supported element.matches().
var elementMatches = getSupportedElementMatches();
// Get the supported transform style property.
var transform = getSupportedStyle('transform');
// Test if transformed elements leak fixed elements.
var transformLeaksFixed = doesTransformLeakFixed();
// Event names.
var evSynchronize = 'synchronize';
var evLayoutStart = 'layoutStart';
var evLayoutEnd = 'layoutEnd';
var evAdd = 'add';
var evRemove = 'remove';
var evShowStart = 'showStart';
var evShowEnd = 'showEnd';
var evHideStart = 'hideStart';
var evHideEnd = 'hideEnd';
var evFilter = 'filter';
var evSort = 'sort';
var evMove = 'move';
var evSend = 'send';
var evReceive = 'receive';
var evDragStart = 'dragStart';
var evDragMove = 'dragMove';
var evDragScroll = 'dragScroll';
var evDragEnd = 'dragEnd';
var evDragReleaseStart = 'dragReleaseStart';
var evDragReleaseEnd = 'dragReleaseEnd';
var evDestroy = 'destroy';
/**
* Grid
* ****
*/
/**
* Creates a new Grid instance.
*
* @public
* @class
* @param {(HTMLElement|String)} element
* @param {Object} [options]
* @param {(?HTMLElement[]|NodeList|String)} [options.items]
* @param {?Function} [options.showAnimation=null]
* @param {Number} [options.showDuration=300]
* @param {(Number[]|String)} [options.showEasing="ease"]
* @param {Object} [options.visibleStyles]
* @param {?Function} [options.hideAnimation=null]
* @param {Number} [options.hideDuration=300]
* @param {(Number[]|String)} [options.hideEasing="ease"]
* @param {Object} [options.hiddenStyles]
* @param {(Function|Object)} [options.layout]
* @param {Boolean} [options.layout.fillGaps=false]
* @param {Boolean} [options.layout.horizontal=false]
* @param {Boolean} [options.layout.alignRight=false]
* @param {Boolean} [options.layout.alignBottom=false]
* @param {(Boolean|Number)} [options.layoutOnResize=100]
* @param {Boolean} [options.layoutOnInit=true]
* @param {Number} [options.layoutDuration=300]
* @param {(Number[]|String)} [options.layoutEasing="ease"]
* @param {?Object} [options.sortData=null]
* @param {Boolean} [options.dragEnabled=false]
* @param {?HtmlElement} [options.dragContainer=null]
* @param {?Function} [options.dragStartPredicate]
* @param {Number} [options.dragStartPredicate.distance=0]
* @param {Number} [options.dragStartPredicate.delay=0]
* @param {(Boolean|String)} [options.dragStartPredicate.handle=false]
* @param {Boolean} [options.dragSort=true]
* @param {Number} [options.dragSortInterval=50]
* @param {(Function|Object)} [options.dragSortPredicate]
* @param {Number} [options.dragSortPredicate.threshold=50]
* @param {String} [options.dragSortPredicate.action="move"]
* @param {String} [options.dragSortPredicate.gaps=true]
* @param {?(Array|String)} [options.dragSortGroup=null]
* @param {?(Array|String)} [options.dragSortWith=null]
* @param {Number} [options.dragReleaseDuration=300]
* @param {(Number[]|String)} [options.dragReleaseEasing="ease"]
* @param {Object} [options.dragHammerSettings={touchAction: "none"}]
* @param {String} [options.containerClass="muuri"]
* @param {String} [options.itemClass="muuri-item"]
* @param {String} [options.itemVisibleClass="muuri-item-visible"]
* @param {String} [options.itemHiddenClass="muuri-item-hidden"]
* @param {String} [options.itemPositioningClass="muuri-item-positioning"]
* @param {String} [options.itemDraggingClass="muuri-item-dragging"]
* @param {String} [options.itemReleasingClass="muuri-item-releasing"]
*/
function Grid(element, options) {
var inst = this;
var settings;
var items;
var debouncedLayout;
var layoutOnResize;
// Allow passing element as selector string. Store element for instance.
element = inst._element = typeof element === typeString ? document.querySelectorAll(element)[0] : element;
// Throw an error if the container element is not body element or does not
// exist within the body element.
if (!document.body.contains(element)) {
throw new Error('Container element must be an existing DOM element');
}
// Create instance settings by merging the options with default options.
settings = inst._settings = mergeSettings(Grid.defaultOptions, options);
// Create instance id and store it to the grid instances collection.
inst._id = ++uuid;
gridInstances[inst._id] = inst;
// Destroyed flag.
inst._isDestroyed = false;
// Reference to the currently used Layout instance.
inst._layout = null;
// Create private Emitter instance.
inst._emitter = new Grid.Emitter();
// Setup instance's sort group.
inst._setSortGroups(settings.dragSortGroup);
// Setup instance's sort connections.
inst._sortConnections = settings.dragSortWith && settings.dragSortWith.length ? [].concat(settings.dragSortWith) : null;
// Setup show and hide animations for items.
inst._itemShowHandler = typeof settings.showAnimation === typeFunction ? settings.showAnimation(settings.showDuration, settings.showEasing, settings.visibleStyles) :
getItemVisibilityHandler('show', settings.showDuration, settings.showEasing, settings.visibleStyles);
inst._itemHideHandler = typeof settings.hideAnimation === typeFunction ? settings.hideAnimation(settings.hideDuration, settings.hideEasing, settings.hiddenStyles) :
getItemVisibilityHandler('hide', settings.hideDuration, settings.hideEasing, settings.hiddenStyles);
// Add container element's class name.
addClass(element, settings.containerClass);
// Create initial items.
inst._items = [];
items = settings.items;
if (typeof items === typeString) {
nodeListToArray(inst._element.children).forEach(function (itemElement) {
if (items === '*' || elementMatches(itemElement, items)) {
inst._items.push(new Grid.Item(inst, itemElement));
}
});
}
else if (Array.isArray(items) || isNodeList(items)) {
inst._items = nodeListToArray(items).map(function (itemElement) {
return new Grid.Item(inst, itemElement);
});
}
// Sanitize layoutOnResize option and bind debounced resize handler if the
// layoutOnResize option a valid number.
layoutOnResize = settings.layoutOnResize;
layoutOnResize = layoutOnResize === true ? 0 : typeof layoutOnResize === typeNumber ? layoutOnResize : -1;
if (layoutOnResize >= 0) {
debouncedLayout = debounce(function () {
inst.refreshItems().layout();
}, layoutOnResize);
inst._resizeHandler = function () {
debouncedLayout();
};
global.addEventListener('resize', inst._resizeHandler);
}
// Layout on init if necessary.
if (settings.layoutOnInit) {
inst.layout(true);
}
}
/**
* Grid - Public properties
* ************************
*/
/**
* @see Item
*/
Grid.Item = Item;
/**
* @see ItemDrag
*/
Grid.ItemDrag = ItemDrag;
/**
* @see ItemRelease
*/
Grid.ItemRelease = ItemRelease;
/**
* @see ItemMigrate
*/
Grid.ItemMigrate = ItemMigrate;
/**
* @see ItemAnimate
*/
Grid.ItemAnimate = ItemAnimate;
/**
* @see Layout
*/
Grid.Layout = Layout;
/**
* @see Emitter
*/
Grid.Emitter = Emitter;
/**
* Default options for Grid instance.
*
* @public
* @memberof Grid
*/
Grid.defaultOptions = {
// Item elements
items: '*',
// Default show animation
showDuration: 300,
showEasing: 'ease',
// Default hide animation
hideDuration: 300,
hideEasing: 'ease',
// Custom show/hide animations
showAnimation: null,
hideAnimation: null,
// Item's visible/hidden state styles
visibleStyles: {
opacity: 1,
scale: 1
},
hiddenStyles: {
opacity: 0,
scale: 0.5
},
// Layout
layout: {
fillGaps: false,
horizontal: false,
alignRight: false,
alignBottom: false
},
layoutOnResize: 100,
layoutOnInit: true,
layoutDuration: 300,
layoutEasing: 'ease',
// Sorting
sortData: null,
// Drag & Drop
dragEnabled: false,
dragContainer: null,
dragStartPredicate: {
distance: 0,
delay: 0,
handle: false
},
dragSort: true,
dragSortInterval: 100,
dragSortPredicate: {
threshold: 50,
action: 'move'
},
dragSortGroup: null,
dragSortWith: null,
dragReleaseDuration: 300,
dragReleaseEasing: 'ease',
dragHammerSettings: {
touchAction: 'none'
},
// Classnames
containerClass: 'muuri',
itemClass: 'muuri-item',
itemVisibleClass: 'muuri-item-shown',
itemHiddenClass: 'muuri-item-hidden',
itemPositioningClass: 'muuri-item-positioning',
itemDraggingClass: 'muuri-item-dragging',
itemReleasingClass: 'muuri-item-releasing'
};
/**
* Grid - Public prototype methods
* *******************************
*/
/**
* Bind an event listener.
*
* @public
* @memberof Grid.prototype
* @param {String} event
* @param {Function} listener
* @returns {Grid}
*/
Grid.prototype.on = function (event, listener) {
if (!this._isDestroyed) {
this._emitter.on(event, listener);
}
return this;
};
/**
* Bind an event listener that is triggered only once.
*
* @public
* @memberof Grid.prototype
* @param {String} event
* @param {Function} listener
* @returns {Grid}
*/
Grid.prototype.once = function (event, listener) {
if (!this._isDestroyed) {
this._emitter.once(event, listener);
}
return this;
};
/**
* Unbind an event listener.
*
* @public
* @memberof Grid.prototype
* @param {String} event
* @param {Function} listener
* @returns {Grid}
*/
Grid.prototype.off = function (event, listener) {
if (!this._isDestroyed) {
this._emitter.off(event, listener);
}
return this;
};
/**
* Get the container element.
*
* @public
* @memberof Grid.prototype
* @returns {HTMLElement}
*/
Grid.prototype.getElement = function () {
return this._element;
};
/**
* Get all items. Optionally you can provide specific targets (elements and
* indices) and filter the results based on the state of the items. Note that
* the returned array is not the same object used by the instance so modifying
* it will not affect instance's items. All items that are not found are
* omitted from the returned array.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} [targets]
* @param {GridItemState} [state]
* @returns {Item[]}
*/
Grid.prototype.getItems = function (targets, state) {
var inst = this;
var hasTargets = targets === 0 || (targets && typeof targets !== typeString);
var targetItems = !hasTargets ? null : isNodeList(targets) ? nodeListToArray(targets) : [].concat(targets);
var targetState = !hasTargets ? targets : state;
var ret = [];
var item;
var i;
// Return an empty array immediately if the instance is destroyed.
if (inst._isDestroyed) {
return ret;
}
// Sanitize target state.
targetState = typeof targetState === typeString ? targetState : null;
// If target state or target items are defined return filtered results.
if (targetState || targetItems) {
targetItems = targetItems || inst._items;
for (i = 0; i < targetItems.length; i++) {
item = hasTargets ? inst._getItem(targetItems[i]) : targetItems[i];
if (item && (!targetState || isItemInState(item, targetState))) {
ret[ret.length] = item;
}
}
return ret;
}
// Otherwise return all items.
else {
return ret.concat(inst._items);
}
};
/**
* Update the cached dimensions of the instance's items.
*
* @public
* @memberof Grid.prototype
* @param {(GridMultiItemQuery|GridItemState)} [items]
* @returns {Grid}
*/
Grid.prototype.refreshItems = function (items) {
var inst = this;
var targetItems;
var i;
if (!inst._isDestroyed) {
targetItems = inst.getItems(items || 'active');
for (i = 0; i < targetItems.length; i++) {
targetItems[i]._refreshDimensions();
}
}
return inst;
};
/**
* Update the sort data of the instance's items.
*
* @public
* @memberof Grid.prototype
* @param {(GridMultiItemQuery|GridItemState)} [items]
* @returns {Grid}
*/
Grid.prototype.refreshSortData = function (items) {
var inst = this;
var targetItems;
var i;
if (!inst._isDestroyed) {
targetItems = inst.getItems(items);
for (i = 0; i < targetItems.length; i++) {
targetItems[i]._refreshSortData();
}
}
return inst;
};
/**
* Synchronize the item elements to match the order of the items in the DOM.
* This comes handy if you need to keep the DOM structure matched with the
* order of the items. Note that if an item's element is not currently a child
* of the container element (if it is dragged for example) it is ignored and
* left untouched.
*
* @public
* @memberof Grid.prototype
* @returns {Grid}
*/
Grid.prototype.synchronize = function () {
var inst = this;
var container = inst._element;
var items = inst._items;
var fragment;
var element;
var i;
// Return immediately if instance is destroyed.
if (inst._isDestroyed) {
return inst;
}
// Append all elements in order to the container element.
if (items.length) {
for (i = 0; i < items.length; i++) {
element = items[i]._element;
if (element.parentNode === container) {
fragment = fragment || document.createDocumentFragment();
fragment.appendChild(element);
}
}
if (fragment) {
container.appendChild(fragment);
}
}
// Emit synchronize event.
inst._emit(evSynchronize);
return inst;
};
/**
* Calculate and apply item positions.
*
* @public
* @memberof Grid.prototype
* @param {Boolean} [instant=false]
* @param {LayoutCallback} [onFinish]
* @returns {Grid}
*/
Grid.prototype.layout = function (instant, onFinish) {
var inst = this;
var callback = typeof instant === typeFunction ? instant : onFinish;
var isInstant = instant === true;
var counter = 0;
var layout;
var items;
var isBorderBox;
var item;
var position;
var i;
// Return immediately if instance is destroyed.
if (inst._isDestroyed) {
return inst;
}
// The finish function, which will be used for checking if all the items
// have laid out yet. After all items have finished their animations call
// callback and emit layoutEnd event. Only emit layoutEnd event if there
// hasn't been a new layout call during this layout.
function tryFinish() {
if (--counter <= 0) {
if (typeof callback === typeFunction) {
callback(inst._layout !== layout, items.concat());
}
if (inst._layout === layout) {
inst._emit(evLayoutEnd, items.concat());
}
}
}
// Create a new layout and store the new layout instance into the grid
// instance.
layout = inst._layout = new Grid.Layout(inst);
items = layout.items.concat();
counter = items.length;
// Emit layoutStart event.
inst._emit(evLayoutStart, items.concat());
// If grid's width or height was modified, we need to update it's cached
// dimensions. Also keep in mind that grid's cached width/height should
// always equal to what elem.getBoundingClientRect() would return, so
// therefore we need to add the grid element's paddings and margins to the
// dimensions if it's box-sizing is border-box.
if (layout.setWidth || layout.setHeight) {
isBorderBox = getStyle(inst._element, 'box-sizing') === 'border-box';
// Set container element's height if needed.
if (layout.setHeight) {
setStyles(inst._element, {
height: (isBorderBox ? layout.height + inst._padding.top + inst._padding.bottom + inst._border.top + inst._border.bottom : layout.height) + 'px'
});
}
// Set container element's width if needed.
if (layout.setWidth) {
setStyles(inst._element, {
width: (isBorderBox ? layout.width + inst._padding.left + inst._padding.right + inst._border.left + inst._border.right : layout.width) + 'px'
});
}
}
// If there are no items let's finish quickly.
if (!items.length) {
tryFinish();
return inst;
}
// If there are items let's position them.
for (i = 0; i < items.length; i++) {
item = items[i];
position = layout.slots[item._id];
// Update item's position. We add the padding to the value here because
// we want the position to be relative to the container elment's
// content edge, not padding edge (which would be default behaviour for
// absolute positioned elements). This way we provide more control over
// the gutter spacing via CSS styles. Otherwise the padding would be
// kind of wasted.
item._left = position.left + inst._padding.left;
item._top = position.top + inst._padding.top;
// Layout non-dragged items.
if (item.isDragging()) {
tryFinish(true, item);
}
else {
item._layout(isInstant, tryFinish);
}
}
return inst;
};
/**
* Add new items by providing the elements you wish to add to the instance and
* optionally provide the index where you want the items to be inserted into.
* All elements that are not already children of the container element will be
* automatically appended to the container element. If an element has it's CSS
* display property set to "none" it will be marked as inactive during the
* initiation process. As long as the item is inactive it will not be part of
* the layout, but it will retain it's index. You can activate items at any
* point with grid.show() method. This method will automatically call
* grid.layout() if one or more of the added elements are visible. If only
* hidden items are added no layout will be called. All the new visible items
* are positioned without animation during their first layout.
*
* @public
* @memberof Grid.prototype
* @param {(HTMLElement|HTMLElement[])} elements
* @param {Object} [options]
* @param {Number} [options.index=-1]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Item[]}
*/
Grid.prototype.add = function (elements, options) {
var inst = this;
var targetElements = [].concat(elements);
var opts = options || {};
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var newItems = [];
var items = inst._items;
var needsLayout = false;
var elementIndex;
var item;
var i;
// Return immediately if the instance is destroyed.
if (inst._isDestroyed) {
return [];
}
// Filter out all elements that exist already in current instance.
for (i = 0; i < items.length; i++) {
elementIndex = targetElements.indexOf(items[i]._element);
if (elementIndex > -1) {
targetElements.splice(elementIndex, 1);
}
}
// Return early if there are no valid items.
if (!targetElements.length) {
return newItems;
}
// Create new items.
for (i = 0; i < targetElements.length; i++) {
item = new Grid.Item(inst, targetElements[i]);
newItems[newItems.length] = item;
// If the item to be added is active, we need to do a layout. Also, we
// need to mark the item with the skipNextLayoutAnimation flag to make it
// position instantly (without animation) during the next layout. Without
// the hack the item would animate to it's new position from the northwest
// corner of the grid, which feels a bit buggy (imho).
if (item._isActive) {
needsLayout = true;
item._skipNextLayoutAnimation = true;
}
}
// Add the new items to the items collection to correct index.
insertItemsToArray(items, newItems, opts.index);
// Emit add event.
inst._emit(evAdd, newItems.concat());
// If layout is needed.
if (needsLayout && layout) {
inst.layout(layout === 'instant', typeof layout === typeFunction ? layout : undefined);
}
// Return new items.
return newItems;
};
/**
* Remove items from the instance.
*
* @public
* @memberof Grid.prototype
* @param {(GridMultiItemQuery|GridItemState)} items
* @param {Object} [options]
* @param {Boolean} [options.removeElements=false]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Item[]}
*/
Grid.prototype.remove = function (items, options) {
var inst = this;
var opts = options || {};
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var needsLayout = false;
var targetItems;
var item;
var i;
// Return immediately if the instance is destroyed.
if (inst._isDestroyed) {
return [];
}
// Remove the individual items.
targetItems = inst.getItems(items);
for (i = 0; i < targetItems.length; i++) {
item = targetItems[i];
if (item._isActive) {
needsLayout = true;
}
item._destroy(opts.removeElements);
}
// Emit remove event.
inst._emit(evRemove, targetItems.concat());
// If layout is needed.
if (needsLayout && layout) {
inst.layout(layout === 'instant', typeof layout === typeFunction ? layout : undefined);
}
return targetItems;
};
/**
* Show instance items.
*
* @public
* @memberof Grid.prototype
* @param {(GridMultiItemQuery|GridItemState)} items
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {ShowCallback} [options.onFinish]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.show = function (items, options) {
return this._isDestroyed ? this : gridShowHideHandler(this, 'show', items, options);
};
/**
* Hide instance items.
*
* @public
* @memberof Grid.prototype
* @param {(GridMultiItemQuery|GridItemState)} items
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {HideCallback} [options.onFinish]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.hide = function (items, options) {
return this._isDestroyed ? this : gridShowHideHandler(this, 'hide', items, options);
};
/**
* Filter items. Expects at least one argument, a predicate, which should be
* either a function or a string. The predicate callback is executed for every
* item in the instance. If the return value of the predicate is truthy the
* item in question will be shown and otherwise hidden. The predicate callback
* receives the item instance as it's argument. If the predicate is a string
* it is considered to be a selector and it is checked against every item
* element in the instance with the native element.matches() method. All the
* matching items will be shown and others hidden.
*
* @public
* @memberof Grid.prototype
* @param {(Function|String)} predicate
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {FilterCallback} [options.onFinish]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.filter = function (predicate, options) {
var inst = this;
var items = inst._items;
var predicateType = typeof predicate;
var isPredicateString = predicateType === typeString;
var isPredicateFn = predicateType === typeFunction;
var opts = options || {};
var isInstant = opts.instant === true;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var onFinish = typeof opts.onFinish === typeFunction ? opts.onFinish : null;
var itemsToShow = [];
var itemsToHide = [];
var tryFinishCounter = -1;
var tryFinish;
var item;
var i;
// Return immediately if there are no items or if the instance id destroyed.
if (inst._isDestroyed || !items.length) {
return inst;
}
// Create finisher function.
tryFinish = !onFinish ? noop : function () {
if (++tryFinishCounter) {
onFinish(itemsToShow.concat(), itemsToHide.concat());
}
};
// Check which items need to be shown and which hidden.
if (isPredicateFn || isPredicateString) {
for (i = 0; i < items.length; i++) {
item = items[i];
if (isPredicateFn ? predicate(item) : elementMatches(item._element, predicate)) {
itemsToShow.push(item);
}
else {
itemsToHide.push(item);
}
}
}
// Show items that need to be shown.
if (itemsToShow.length) {
inst.show(itemsToShow, {
instant: isInstant,
onFinish: tryFinish,
layout: false
});
}
else {
tryFinish();
}
// Hide items that need to be hidden.
if (itemsToHide.length) {
inst.hide(itemsToHide, {
instant: isInstant,
onFinish: tryFinish,
layout: false
});
}
else {
tryFinish();
}
// If there are any items to filter.
if (itemsToShow.length || itemsToHide.length) {
// Emit filter event.
inst._emit(evFilter, itemsToShow.concat(), itemsToHide.concat());
// If layout is needed.
if (layout) {
inst.layout(layout === 'instant', typeof layout === typeFunction ? layout : undefined);
}
}
return inst;
};
/**
* Sort items. There are three ways to sort the items. The first is simply by
* providing a function as the comparer which works identically to native
* array sort. Alternatively you can sort by the sort data you have provided
* in the instance's options. Just provide the sort data key(s) as a string
* (separated by space) and the items will be sorted based on the provided