-
-
Notifications
You must be signed in to change notification settings - Fork 644
/
Copy pathGrid.js
1780 lines (1566 loc) · 49.8 KB
/
Grid.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
/**
* Copyright (c) 2015-present, Haltu Oy
* Released under the MIT license
* https://github.com/haltu/muuri/blob/master/LICENSE.md
*/
import {
ACTION_MOVE,
ACTION_SWAP,
EVENT_SYNCHRONIZE,
EVENT_LAYOUT_START,
EVENT_LAYOUT_ABORT,
EVENT_LAYOUT_END,
EVENT_ADD,
EVENT_REMOVE,
EVENT_SHOW_START,
EVENT_SHOW_END,
EVENT_HIDE_START,
EVENT_HIDE_END,
EVENT_FILTER,
EVENT_SORT,
EVENT_MOVE,
EVENT_DESTROY,
GRID_INSTANCES,
ITEM_ELEMENT_MAP,
MAX_SAFE_FLOAT32_INTEGER,
} from '../constants';
import Item from '../Item/Item';
import ItemDrag from '../Item/ItemDrag';
import ItemDragPlaceholder from '../Item/ItemDragPlaceholder';
import ItemLayout from '../Item/ItemLayout';
import ItemMigrate from '../Item/ItemMigrate';
import ItemDragRelease from '../Item/ItemDragRelease';
import ItemVisibility from '../Item/ItemVisibility';
import Emitter from '../Emitter/Emitter';
import Animator from '../Animator/Animator';
import Packer from '../Packer/Packer';
import Dragger from '../Dragger/Dragger';
import AutoScroller from '../AutoScroller/AutoScroller';
import addClass from '../utils/addClass';
import arrayInsert from '../utils/arrayInsert';
import arrayMove from '../utils/arrayMove';
import arraySwap from '../utils/arraySwap';
import createUid from '../utils/createUid';
import debounce from '../utils/debounce';
import elementMatches from '../utils/elementMatches';
import getPrefixedPropName from '../utils/getPrefixedPropName';
import getStyle from '../utils/getStyle';
import getStyleAsFloat from '../utils/getStyleAsFloat';
import isFunction from '../utils/isFunction';
import isNodeList from '../utils/isNodeList';
import isPlainObject from '../utils/isPlainObject';
import noop from '../utils/noop';
import removeClass from '../utils/removeClass';
import setStyles from '../utils/setStyles';
import toArray from '../utils/toArray';
var NUMBER_TYPE = 'number';
var STRING_TYPE = 'string';
var INSTANT_LAYOUT = 'instant';
var layoutId = 0;
/**
* Creates a new Grid instance.
*
* @class
* @param {(HTMLElement|String)} element
* @param {Object} [options]
* @param {(String|HTMLElement[]|NodeList|HTMLCollection)} [options.items="*"]
* @param {Number} [options.showDuration=300]
* @param {String} [options.showEasing="ease"]
* @param {Object} [options.visibleStyles={opacity: "1", transform: "scale(1)"}]
* @param {Number} [options.hideDuration=300]
* @param {String} [options.hideEasing="ease"]
* @param {Object} [options.hiddenStyles={opacity: "0", transform: "scale(0.5)"}]
* @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} [options.layout.rounding=false]
* @param {(Boolean|Number)} [options.layoutOnResize=150]
* @param {Boolean} [options.layoutOnInit=true]
* @param {Number} [options.layoutDuration=300]
* @param {String} [options.layoutEasing="ease"]
* @param {?Object} [options.sortData=null]
* @param {Boolean} [options.dragEnabled=false]
* @param {?String} [options.dragHandle=null]
* @param {?HtmlElement} [options.dragContainer=null]
* @param {?Function} [options.dragStartPredicate]
* @param {Number} [options.dragStartPredicate.distance=0]
* @param {Number} [options.dragStartPredicate.delay=0]
* @param {String} [options.dragAxis="xy"]
* @param {(Boolean|Function)} [options.dragSort=true]
* @param {Object} [options.dragSortHeuristics]
* @param {Number} [options.dragSortHeuristics.sortInterval=100]
* @param {Number} [options.dragSortHeuristics.minDragDistance=10]
* @param {Number} [options.dragSortHeuristics.minBounceBackAngle=1]
* @param {(Function|Object)} [options.dragSortPredicate]
* @param {Number} [options.dragSortPredicate.threshold=50]
* @param {String} [options.dragSortPredicate.action="move"]
* @param {String} [options.dragSortPredicate.migrateAction="move"]
* @param {Object} [options.dragRelease]
* @param {Number} [options.dragRelease.duration=300]
* @param {String} [options.dragRelease.easing="ease"]
* @param {Boolean} [options.dragRelease.useDragContainer=true]
* @param {Object} [options.dragCssProps]
* @param {Object} [options.dragPlaceholder]
* @param {Boolean} [options.dragPlaceholder.enabled=false]
* @param {?Function} [options.dragPlaceholder.createElement=null]
* @param {?Function} [options.dragPlaceholder.onCreate=null]
* @param {?Function} [options.dragPlaceholder.onRemove=null]
* @param {Object} [options.dragAutoScroll]
* @param {(Function|Array)} [options.dragAutoScroll.targets=[]]
* @param {?Function} [options.dragAutoScroll.handle=null]
* @param {Number} [options.dragAutoScroll.threshold=50]
* @param {Number} [options.dragAutoScroll.safeZone=0.2]
* @param {(Function|Number)} [options.dragAutoScroll.speed]
* @param {Boolean} [options.dragAutoScroll.sortDuringScroll=true]
* @param {Boolean} [options.dragAutoScroll.smoothStop=false]
* @param {?Function} [options.dragAutoScroll.onStart=null]
* @param {?Function} [options.dragAutoScroll.onStop=null]
* @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"]
* @param {String} [options.itemPlaceholderClass="muuri-item-placeholder"]
*/
function Grid(element, options) {
// Allow passing element as selector string
if (typeof element === STRING_TYPE) {
element = document.querySelector(element);
}
// Throw an error if the container element is not body element or does not
// exist within the body element.
var isElementInDom = element.getRootNode
? element.getRootNode({ composed: true }) === document
: document.body.contains(element);
if (!isElementInDom || element === document.documentElement) {
throw new Error('Container element must be an existing DOM element.');
}
// Create instance settings by merging the options with default options.
var settings = mergeSettings(Grid.defaultOptions, options);
settings.visibleStyles = normalizeStyles(settings.visibleStyles);
settings.hiddenStyles = normalizeStyles(settings.hiddenStyles);
if (!isFunction(settings.dragSort)) {
settings.dragSort = !!settings.dragSort;
}
this._id = createUid();
this._element = element;
this._settings = settings;
this._isDestroyed = false;
this._items = [];
this._layout = {
id: 0,
items: [],
slots: [],
};
this._isLayoutFinished = true;
this._nextLayoutData = null;
this._emitter = new Emitter();
this._onLayoutDataReceived = this._onLayoutDataReceived.bind(this);
// Store grid instance to the grid instances collection.
GRID_INSTANCES[this._id] = this;
// Add container element's class name.
addClass(element, settings.containerClass);
// If layoutOnResize option is a valid number sanitize it and bind the resize
// handler.
bindLayoutOnResize(this, settings.layoutOnResize);
// Add initial items.
this.add(getInitialGridElements(element, settings.items), { layout: false });
// Layout on init if necessary.
if (settings.layoutOnInit) {
this.layout(true);
}
}
/**
* Public properties
* *****************
*/
/**
* @public
* @static
* @see Item
*/
Grid.Item = Item;
/**
* @public
* @static
* @see ItemLayout
*/
Grid.ItemLayout = ItemLayout;
/**
* @public
* @static
* @see ItemVisibility
*/
Grid.ItemVisibility = ItemVisibility;
/**
* @public
* @static
* @see ItemMigrate
*/
Grid.ItemMigrate = ItemMigrate;
/**
* @public
* @static
* @see ItemDrag
*/
Grid.ItemDrag = ItemDrag;
/**
* @public
* @static
* @see ItemDragRelease
*/
Grid.ItemDragRelease = ItemDragRelease;
/**
* @public
* @static
* @see ItemDragPlaceholder
*/
Grid.ItemDragPlaceholder = ItemDragPlaceholder;
/**
* @public
* @static
* @see Emitter
*/
Grid.Emitter = Emitter;
/**
* @public
* @static
* @see Animator
*/
Grid.Animator = Animator;
/**
* @public
* @static
* @see Dragger
*/
Grid.Dragger = Dragger;
/**
* @public
* @static
* @see Packer
*/
Grid.Packer = Packer;
/**
* @public
* @static
* @see AutoScroller
*/
Grid.AutoScroller = AutoScroller;
/**
* The default Packer instance used by default for all layouts.
*
* @public
* @static
* @type {Packer}
*/
Grid.defaultPacker = new Packer(2);
/**
* Default options for Grid instance.
*
* @public
* @static
* @type {Object}
*/
Grid.defaultOptions = {
// Initial item elements
items: '*',
// Default show animation
showDuration: 300,
showEasing: 'ease',
// Default hide animation
hideDuration: 300,
hideEasing: 'ease',
// Item's visible/hidden state styles
visibleStyles: {
opacity: '1',
transform: 'scale(1)',
},
hiddenStyles: {
opacity: '0',
transform: 'scale(0.5)',
},
// Layout
layout: {
fillGaps: false,
horizontal: false,
alignRight: false,
alignBottom: false,
rounding: false,
},
layoutOnResize: 150,
layoutOnInit: true,
layoutDuration: 300,
layoutEasing: 'ease',
// Sorting
sortData: null,
// Drag & Drop
dragEnabled: false,
dragContainer: null,
dragHandle: null,
dragStartPredicate: {
distance: 0,
delay: 0,
},
dragAxis: 'xy',
dragSort: true,
dragSortHeuristics: {
sortInterval: 100,
minDragDistance: 10,
minBounceBackAngle: 1,
},
dragSortPredicate: {
threshold: 50,
action: ACTION_MOVE,
migrateAction: ACTION_MOVE,
},
dragRelease: {
duration: 300,
easing: 'ease',
useDragContainer: true,
},
dragCssProps: {
touchAction: 'none',
userSelect: 'none',
userDrag: 'none',
tapHighlightColor: 'rgba(0, 0, 0, 0)',
touchCallout: 'none',
contentZooming: 'none',
},
dragPlaceholder: {
enabled: false,
createElement: null,
onCreate: null,
onRemove: null,
},
dragAutoScroll: {
targets: [],
handle: null,
threshold: 50,
safeZone: 0.2,
speed: AutoScroller.smoothSpeed(1000, 2000, 2500),
sortDuringScroll: true,
smoothStop: false,
onStart: null,
onStop: null,
},
// 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',
itemPlaceholderClass: 'muuri-item-placeholder',
};
/**
* Public prototype methods
* ************************
*/
/**
* Bind an event listener.
*
* @public
* @param {String} event
* @param {Function} listener
* @returns {Grid}
*/
Grid.prototype.on = function (event, listener) {
this._emitter.on(event, listener);
return this;
};
/**
* Unbind an event listener.
*
* @public
* @param {String} event
* @param {Function} listener
* @returns {Grid}
*/
Grid.prototype.off = function (event, listener) {
this._emitter.off(event, listener);
return this;
};
/**
* Get the container element.
*
* @public
* @returns {HTMLElement}
*/
Grid.prototype.getElement = function () {
return this._element;
};
/**
* Get instance's item by element or by index. Target can also be an Item
* instance in which case the function returns the item if it exists within
* related Grid instance. If nothing is found with the provided target, null
* is returned.
*
* @private
* @param {(HtmlElement|Number|Item)} [target]
* @returns {?Item}
*/
Grid.prototype.getItem = function (target) {
// If no target is specified or the instance is destroyed, return null.
if (this._isDestroyed || (!target && target !== 0)) {
return null;
}
// If target is number return the item in that index. If the number is lower
// than zero look for the item starting from the end of the items array. For
// example -1 for the last item, -2 for the second last item, etc.
if (typeof target === NUMBER_TYPE) {
return this._items[target > -1 ? target : this._items.length + target] || null;
}
// If the target is an instance of Item return it if it is attached to this
// Grid instance, otherwise return null.
if (target instanceof Item) {
return target._gridId === this._id ? target : null;
}
// In other cases let's assume that the target is an element, so let's try
// to find an item that matches the element and return it. If item is not
// found return null.
if (ITEM_ELEMENT_MAP) {
var item = ITEM_ELEMENT_MAP.get(target);
return item && item._gridId === this._id ? item : null;
} else {
for (var i = 0; i < this._items.length; i++) {
if (this._items[i]._element === target) {
return this._items[i];
}
}
}
return null;
};
/**
* Get all items. Optionally you can provide specific targets (elements,
* indices and item instances). All items that are not found are omitted from
* the returned array.
*
* @public
* @param {(HtmlElement|Number|Item|Array)} [targets]
* @returns {Item[]}
*/
Grid.prototype.getItems = function (targets) {
// Return all items immediately if no targets were provided or if the
// instance is destroyed.
if (this._isDestroyed || targets === undefined) {
return this._items.slice(0);
}
var items = [];
var i, item;
if (Array.isArray(targets) || isNodeList(targets)) {
for (i = 0; i < targets.length; i++) {
item = this.getItem(targets[i]);
if (item) items.push(item);
}
} else {
item = this.getItem(targets);
if (item) items.push(item);
}
return items;
};
/**
* Update the cached dimensions of the instance's items. By default all the
* items are refreshed, but you can also provide an array of target items as the
* first argument if you want to refresh specific items. Note that all hidden
* items are not refreshed by default since their "display" property is "none"
* and their dimensions are therefore not readable from the DOM. However, if you
* do want to force update hidden item dimensions too you can provide `true`
* as the second argument, which makes the elements temporarily visible while
* their dimensions are being read.
*
* @public
* @param {Item[]} [items]
* @param {Boolean} [force=false]
* @returns {Grid}
*/
Grid.prototype.refreshItems = function (items, force) {
if (this._isDestroyed) return this;
var targets = items || this._items;
var i, item, style, hiddenItemStyles;
if (force === true) {
hiddenItemStyles = [];
for (i = 0; i < targets.length; i++) {
item = targets[i];
if (!item.isVisible() && !item.isHiding()) {
style = item.getElement().style;
style.visibility = 'hidden';
style.display = '';
hiddenItemStyles.push(style);
}
}
}
for (i = 0; i < targets.length; i++) {
targets[i]._refreshDimensions(force);
}
if (force === true) {
for (i = 0; i < hiddenItemStyles.length; i++) {
style = hiddenItemStyles[i];
style.visibility = '';
style.display = 'none';
}
hiddenItemStyles.length = 0;
}
return this;
};
/**
* Update the sort data of the instance's items. By default all the items are
* refreshed, but you can also provide an array of target items if you want to
* refresh specific items.
*
* @public
* @param {Item[]} [items]
* @returns {Grid}
*/
Grid.prototype.refreshSortData = function (items) {
if (this._isDestroyed) return this;
var targets = items || this._items;
for (var i = 0; i < targets.length; i++) {
targets[i]._refreshSortData();
}
return this;
};
/**
* 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
* @returns {Grid}
*/
Grid.prototype.synchronize = function () {
if (this._isDestroyed) return this;
var items = this._items;
if (!items.length) return this;
var fragment;
var element;
for (var i = 0; i < items.length; i++) {
element = items[i]._element;
if (element.parentNode === this._element) {
fragment = fragment || document.createDocumentFragment();
fragment.appendChild(element);
}
}
if (!fragment) return this;
this._element.appendChild(fragment);
this._emit(EVENT_SYNCHRONIZE);
return this;
};
/**
* Calculate and apply item positions.
*
* @public
* @param {Boolean} [instant=false]
* @param {Function} [onFinish]
* @returns {Grid}
*/
Grid.prototype.layout = function (instant, onFinish) {
if (this._isDestroyed) return this;
// Cancel unfinished layout algorithm if possible.
var unfinishedLayout = this._nextLayoutData;
if (unfinishedLayout && isFunction(unfinishedLayout.cancel)) {
unfinishedLayout.cancel();
}
// Compute layout id (let's stay in Float32 range).
layoutId = (layoutId % MAX_SAFE_FLOAT32_INTEGER) + 1;
var nextLayoutId = layoutId;
// Store data for next layout.
this._nextLayoutData = {
id: nextLayoutId,
instant: instant,
onFinish: onFinish,
cancel: null,
};
// Collect layout items (all active grid items).
var items = this._items;
var layoutItems = [];
for (var i = 0; i < items.length; i++) {
if (items[i]._isActive) layoutItems.push(items[i]);
}
// Compute new layout.
this._refreshDimensions();
var gridWidth = this._width - this._borderLeft - this._borderRight;
var gridHeight = this._height - this._borderTop - this._borderBottom;
var layoutSettings = this._settings.layout;
var cancelLayout;
if (isFunction(layoutSettings)) {
cancelLayout = layoutSettings(
this,
nextLayoutId,
layoutItems,
gridWidth,
gridHeight,
this._onLayoutDataReceived
);
} else {
Grid.defaultPacker.setOptions(layoutSettings);
cancelLayout = Grid.defaultPacker.createLayout(
this,
nextLayoutId,
layoutItems,
gridWidth,
gridHeight,
this._onLayoutDataReceived
);
}
// Store layout cancel method if available.
if (
isFunction(cancelLayout) &&
this._nextLayoutData &&
this._nextLayoutData.id === nextLayoutId
) {
this._nextLayoutData.cancel = cancelLayout;
}
return this;
};
/**
* 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
* @param {(HTMLElement|HTMLElement[])} elements
* @param {Object} [options]
* @param {Number} [options.index=-1]
* @param {Boolean} [options.active]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Item[]}
*/
Grid.prototype.add = function (elements, options) {
if (this._isDestroyed || !elements) return [];
var newItems = toArray(elements);
if (!newItems.length) return newItems;
var opts = options || {};
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var items = this._items;
var needsLayout = false;
var fragment;
var element;
var item;
var i;
// Collect all the elements that are not child of the grid element into a
// document fragment.
for (i = 0; i < newItems.length; i++) {
element = newItems[i];
if (element.parentNode !== this._element) {
fragment = fragment || document.createDocumentFragment();
fragment.appendChild(element);
}
}
// If we have a fragment, let's append it to the grid element. We could just
// not do this and the `new Item()` instantiation would handle this for us,
// but this way we can add the elements into the DOM a bit faster.
if (fragment) {
this._element.appendChild(fragment);
}
// Map provided elements into new grid items.
for (i = 0; i < newItems.length; i++) {
element = newItems[i];
item = newItems[i] = new Item(this, element, opts.active);
// If the item to be added is active, we need to do a layout. Also, we
// need to mark the item with the skipNextAnimation 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._layout._skipNextAnimation = true;
}
}
// Set up the items' initial dimensions and sort data. This needs to be done
// in a separate loop to avoid layout thrashing.
for (i = 0; i < newItems.length; i++) {
item = newItems[i];
item._refreshDimensions();
item._refreshSortData();
}
// Add the new items to the items collection to correct index.
arrayInsert(items, newItems, opts.index);
// Emit add event.
if (this._hasListeners(EVENT_ADD)) {
this._emit(EVENT_ADD, newItems.slice(0));
}
// If layout is needed.
if (needsLayout && layout) {
this.layout(layout === INSTANT_LAYOUT, isFunction(layout) ? layout : undefined);
}
return newItems;
};
/**
* Remove items from the instance.
*
* @public
* @param {Item[]} items
* @param {Object} [options]
* @param {Boolean} [options.removeElements=false]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Item[]}
*/
Grid.prototype.remove = function (items, options) {
if (this._isDestroyed || !items.length) return [];
var opts = options || {};
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var needsLayout = false;
var allItems = this.getItems();
var targetItems = [];
var indices = [];
var index;
var item;
var i;
// Remove the individual items.
for (i = 0; i < items.length; i++) {
item = items[i];
if (item._isDestroyed) continue;
index = this._items.indexOf(item);
if (index === -1) continue;
if (item._isActive) needsLayout = true;
targetItems.push(item);
indices.push(allItems.indexOf(item));
item._destroy(opts.removeElements);
this._items.splice(index, 1);
}
// Emit remove event.
if (this._hasListeners(EVENT_REMOVE)) {
this._emit(EVENT_REMOVE, targetItems.slice(0), indices);
}
// If layout is needed.
if (needsLayout && layout) {
this.layout(layout === INSTANT_LAYOUT, isFunction(layout) ? layout : undefined);
}
return targetItems;
};
/**
* Show specific instance items.
*
* @public
* @param {Item[]} items
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {Boolean} [options.syncWithLayout=true]
* @param {Function} [options.onFinish]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.show = function (items, options) {
if (!this._isDestroyed && items.length) {
this._setItemsVisibility(items, true, options);
}
return this;
};
/**
* Hide specific instance items.
*
* @public
* @param {Item[]} items
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {Boolean} [options.syncWithLayout=true]
* @param {Function} [options.onFinish]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.hide = function (items, options) {
if (!this._isDestroyed && items.length) {
this._setItemsVisibility(items, false, options);
}
return this;
};
/**
* 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
* @param {(Function|String)} predicate
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {Boolean} [options.syncWithLayout=true]
* @param {FilterCallback} [options.onFinish]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.filter = function (predicate, options) {
if (this._isDestroyed || !this._items.length) return this;
var itemsToShow = [];
var itemsToHide = [];
var isPredicateString = typeof predicate === STRING_TYPE;
var isPredicateFn = isFunction(predicate);
var opts = options || {};
var isInstant = opts.instant === true;
var syncWithLayout = opts.syncWithLayout;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var onFinish = isFunction(opts.onFinish) ? opts.onFinish : null;
var tryFinishCounter = -1;
var tryFinish = noop;
var item;
var i;
// If we have onFinish callback, let's create proper tryFinish callback.
if (onFinish) {
tryFinish = function () {
++tryFinishCounter && onFinish(itemsToShow.slice(0), itemsToHide.slice(0));
};
}
// Check which items need to be shown and which hidden.
if (isPredicateFn || isPredicateString) {
for (i = 0; i < this._items.length; i++) {
item = this._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) {
this.show(itemsToShow, {
instant: isInstant,
syncWithLayout: syncWithLayout,
onFinish: tryFinish,
layout: false,
});
} else {
tryFinish();
}
// Hide items that need to be hidden.
if (itemsToHide.length) {
this.hide(itemsToHide, {
instant: isInstant,
syncWithLayout: syncWithLayout,
onFinish: tryFinish,
layout: false,
});
} else {
tryFinish();
}
// If there are any items to filter.
if (itemsToShow.length || itemsToHide.length) {
// Emit filter event.
if (this._hasListeners(EVENT_FILTER)) {
this._emit(EVENT_FILTER, itemsToShow.slice(0), itemsToHide.slice(0));
}
// If layout is needed.
if (layout) {
this.layout(layout === INSTANT_LAYOUT, isFunction(layout) ? layout : undefined);
}
}
return this;
};
/**
* 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
* sort data keys. Lastly you have the opportunity to provide a presorted
* array of items which will be used to sync the internal items array in the
* same order.
*
* @public
* @param {(Function|String|Item[])} comparer
* @param {Object} [options]
* @param {Boolean} [options.descending=false]
* @param {(Boolean|Function|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.sort = (function () {
var sortComparer;
var isDescending;
var origItems;
var indexMap;
function defaultComparer(a, b) {
var result = 0;
var criteriaName;
var criteriaOrder;
var valA;