muuri.js
160 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
/**
* Muuri v0.6.3
* https://github.com/haltu/muuri
* Copyright (c) 2015-present, Haltu Oy
* Released under the MIT license
* https://github.com/haltu/muuri/blob/master/LICENSE.md
* @license MIT
*
* Muuri Packer
* Copyright (c) 2016-present, Niklas Rämö <inramo@gmail.com>
* @license MIT
*
* Muuri Ticker / Muuri Emitter / Muuri Queue
* Copyright (c) 2018-present, Niklas Rämö <inramo@gmail.com>
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('hammerjs')) :
typeof define === 'function' && define.amd ? define(['hammerjs'], factory) :
(global.Muuri = factory(global.Hammer));
}(this, (function (Hammer) { 'use strict';
Hammer = Hammer && Hammer.hasOwnProperty('default') ? Hammer['default'] : Hammer;
var namespace = 'Muuri';
var gridInstances = {};
var eventSynchronize = 'synchronize';
var eventLayoutStart = 'layoutStart';
var eventLayoutEnd = 'layoutEnd';
var eventAdd = 'add';
var eventRemove = 'remove';
var eventShowStart = 'showStart';
var eventShowEnd = 'showEnd';
var eventHideStart = 'hideStart';
var eventHideEnd = 'hideEnd';
var eventFilter = 'filter';
var eventSort = 'sort';
var eventMove = 'move';
var eventSend = 'send';
var eventBeforeSend = 'beforeSend';
var eventReceive = 'receive';
var eventBeforeReceive = 'beforeReceive';
var eventDragInit = 'dragInit';
var eventDragStart = 'dragStart';
var eventDragMove = 'dragMove';
var eventDragScroll = 'dragScroll';
var eventDragEnd = 'dragEnd';
var eventDragReleaseStart = 'dragReleaseStart';
var eventDragReleaseEnd = 'dragReleaseEnd';
var eventDestroy = 'destroy';
/**
* Event emitter constructor.
*
* @class
*/
function Emitter() {
this._events = {};
this._queue = [];
this._processCount = 0;
this._isDestroyed = false;
}
/**
* Public prototype methods
* ************************
*/
/**
* Bind an event listener.
*
* @public
* @memberof Emitter.prototype
* @param {String} event
* @param {Function} listener
* @returns {Emitter}
*/
Emitter.prototype.on = function(event, listener) {
if (this._isDestroyed) return this;
// Get listeners queue and create it if it does not exist.
var listeners = this._events[event];
if (!listeners) listeners = this._events[event] = [];
// Add the listener to the queue.
listeners.push(listener);
return this;
};
/**
* Bind an event listener that is triggered only once.
*
* @public
* @memberof Emitter.prototype
* @param {String} event
* @param {Function} listener
* @returns {Emitter}
*/
Emitter.prototype.once = function(event, listener) {
if (this._isDestroyed) return this;
var callback = function() {
this.off(event, callback);
listener.apply(null, arguments);
}.bind(this);
return this.on(event, callback);
};
/**
* Unbind all event listeners that match the provided listener function.
*
* @public
* @memberof Emitter.prototype
* @param {String} event
* @param {Function} [listener]
* @returns {Emitter}
*/
Emitter.prototype.off = function(event, listener) {
if (this._isDestroyed) return this;
// Get listeners and return immediately if none is found.
var listeners = this._events[event];
if (!listeners || !listeners.length) return this;
// If no specific listener is provided remove all listeners.
if (!listener) {
listeners.length = 0;
return this;
}
// Remove all matching listeners.
var i = listeners.length;
while (i--) {
if (listener === listeners[i]) listeners.splice(i, 1);
}
return this;
};
/**
* Emit all listeners in a specified event with the provided arguments.
*
* @public
* @memberof Emitter.prototype
* @param {String} event
* @param {*} [arg1]
* @param {*} [arg2]
* @param {*} [arg3]
* @returns {Emitter}
*/
Emitter.prototype.emit = function(event, arg1, arg2, arg3) {
if (this._isDestroyed) return this;
// Get event listeners and quite early if there's none.
var listeners = this._events[event];
if (!listeners || !listeners.length) return this;
var queue = this._queue;
var queueLength = queue.length;
var argsLength = arguments.length - 1;
var queueNewLength;
var i;
// Add the current listeners to the callback queue before we process them.
// This is necessary to guarantee that all of the listeners are called in
// correct order even if new event listeners are removed/added during
// processing and/or events are emitted during processing.
for (i = 0; i < listeners.length; i++) {
queue.push(listeners[i]);
}
// Get queue's new length.
queueNewLength = queue.length;
// Increment queue counter. This is needed for the scenarios where emit is
// triggered while the queue is already processing. We need to keep track of
// how many "queue processors" there are active so that we can safely reset
// the queue in the end when the last queue processor is finished.
++this._processCount;
// Process the queue (the specific part of it for this emit).
for (i = queueLength; i < queueNewLength; i++) {
// prettier-ignore
argsLength === 0 ? queue[i]() :
argsLength === 1 ? queue[i](arg1) :
argsLength === 2 ? queue[i](arg1, arg2) :
queue[i](arg1, arg2, arg3);
// Let's always make sure after the callback that the emitter is still
// alive (not destroyed). We want to stop processing asap when the emitter
// is destroyed.
if (this._isDestroyed) return this;
}
// Decrement queue counter.
--this._processCount;
// If there are no more queues processing and there were no new items were
// added to the queue during processing let's reset the queue.
if (!this._processCount && queueNewLength === queue.length) queue.length = 0;
return this;
};
/**
* Destroy emitter instance. Basically just removes all bound listeners.
*
* @public
* @memberof Emitter.prototype
* @returns {Emitter}
*/
Emitter.prototype.destroy = function() {
if (this._isDestroyed) return this;
var events = this._events;
var event;
// Flag as destroyed.
this._isDestroyed = true;
// Reset queue (if queue is currently processing this will also stop that).
this._queue.length = this._processCount = 0;
// Remove all listeners.
for (event in events) {
if (events[event]) {
events[event].length = 0;
events[event] = undefined;
}
}
return this;
};
// Set up the default export values.
var isTransformSupported = false;
var transformStyle = 'transform';
var transformProp = 'transform';
// Find the supported transform prop and style names.
var style = 'transform';
var styleCap = 'Transform';
['', 'Webkit', 'Moz', 'O', 'ms'].forEach(function(prefix) {
if (isTransformSupported) return;
var propName = prefix ? prefix + styleCap : style;
if (document.documentElement.style[propName] !== undefined) {
prefix = prefix.toLowerCase();
transformStyle = prefix ? '-' + prefix + '-' + style : style;
transformProp = propName;
isTransformSupported = true;
}
});
var stylesCache = typeof WeakMap === 'function' ? new WeakMap() : null;
/**
* Returns the computed value of an element's style property as a string.
*
* @param {HTMLElement} element
* @param {String} style
* @returns {String}
*/
function getStyle(element, style) {
var styles = stylesCache && stylesCache.get(element);
if (!styles) {
styles = window.getComputedStyle(element, null);
stylesCache && stylesCache.set(element, styles);
}
return styles.getPropertyValue(style === 'transform' ? transformStyle : style);
}
/**
* Transforms a camel case style property to kebab case style property.
*
* @param {String} string
* @returns {String}
*/
function getStyleName(string) {
return string.replace(/([A-Z])/g, '-$1').toLowerCase();
}
/**
* Get current values of the provided styles definition object.
*
* @param {HTMLElement} element
* @param {Object} styles
* @return {Object}
*/
function getCurrentStyles(element, styles) {
var current = {};
for (var prop in styles) {
current[prop] = getStyle(element, getStyleName(prop));
}
return current;
}
/**
* Set inline styles to an element.
*
* @param {HTMLElement} element
* @param {Object} styles
*/
function setStyles(element, styles) {
for (var prop in styles) {
element.style[prop === 'transform' ? transformProp : prop] = styles[prop];
}
}
/**
* Item animation handler powered by Web Animations API.
*
* @class
* @param {Item} item
* @param {HTMLElement} element
*/
function ItemAnimate(item, element) {
this._item = item;
this._element = element;
this._animation = null;
this._propsTo = null;
this._callback = null;
this._keyframes = [];
this._options = {};
this._isDestroyed = false;
this._onFinish = this._onFinish.bind(this);
}
/**
* Public prototype methods
* ************************
*/
/**
* Start instance's animation. Automatically stops current animation if it is
* running.
*
* @public
* @memberof ItemAnimate.prototype
* @param {Object} propsFrom
* @param {Object} propsTo
* @param {Object} [options]
* @param {Number} [options.duration=300]
* @param {String} [options.easing='ease']
* @param {Function} [options.onFinish]
*/
ItemAnimate.prototype.start = function(propsFrom, propsTo, options) {
if (this._isDestroyed) return;
var opts = options || 0;
var callback = typeof opts.onFinish === 'function' ? opts.onFinish : null;
var shouldStop = false;
var propName;
// If we have an ongoing animation.
if (this._animation) {
// Check if we should stop the current animation. Here basically just test
// that is the new animation animating to the same props with same values
// as the current animation. Note that this is not currently checking the
// scenario where the current animation has matching props and values to
// the new animation and also has some extra props.
for (propName in propsTo) {
if (propsTo[propName] !== this._propsTo[propName]) {
shouldStop = true;
break;
}
}
// Let's cancel the ongoing animation if needed.
if (shouldStop) {
this._animation.cancel();
}
// Otherwise let's just change the callback and quit early.
else {
this._callback = callback;
return;
}
}
// Store callback.
this._callback = callback;
// Store target props (copy to guard against mutation).
this._propsTo = {};
for (propName in propsTo) {
this._propsTo[propName] = propsTo[propName];
}
// Start the animation.
this._keyframes[0] = propsFrom;
this._keyframes[1] = propsTo;
this._options.duration = opts.duration || 300;
this._options.easing = opts.easing || 'ease';
this._animation = this._element.animate&&this._element.animate(this._keyframes, this._options);
// Bind animation finish callback.
if(this._element.animate){
this._animation.onfinish = this._onFinish;
}else{
setTimeout(this._onFinish, 500);
}
// Set the end styles.
setStyles(this._element, propsTo);
};
/**
* Stop instance's current animation if running.
*
* @public
* @memberof ItemAnimate.prototype
* @param {Object} [currentStyles]
*/
ItemAnimate.prototype.stop = function(currentStyles) {
if (this._isDestroyed || !this._animation) return;
setStyles(this._element, currentStyles || getCurrentStyles(this._element, this._propsTo));
this._animation.cancel();
this._animation = this._propsTo = this._callback = null;
};
/**
* Check if the item is being animated currently.
*
* @public
* @memberof ItemAnimate.prototype
* @return {Boolean}
*/
ItemAnimate.prototype.isAnimating = function() {
return !!this._animation;
};
/**
* Destroy the instance and stop current animation if it is running.
*
* @public
* @memberof ItemAnimate.prototype
*/
ItemAnimate.prototype.destroy = function() {
if (this._isDestroyed) return;
this.stop();
this._item = this._element = this._options = this._keyframes = null;
this._isDestroyed = true;
};
/**
* Private prototype methods
* *************************
*/
/**
* Animation end handler.
*
* @private
* @memberof ItemAnimate.prototype
*/
ItemAnimate.prototype._onFinish = function() {
var callback = this._callback;
this._animation = this._propsTo = this._callback = null;
callback && callback();
};
var raf = (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
rafFallback
).bind(window);
function rafFallback(cb) {
return window.setTimeout(cb, 16);
}
/**
* A ticker system for handling DOM reads and writes in an efficient way.
* Contains a read queue and a write queue that are processed on the next
* animation frame when needed.
*
* @class
*/
function Ticker() {
this._nextTick = null;
this._queue = [];
this._reads = {};
this._writes = {};
this._batch = [];
this._batchReads = {};
this._batchWrites = {};
this._flush = this._flush.bind(this);
}
Ticker.prototype.add = function(id, readCallback, writeCallback, isImportant) {
// First, let's check if an item has been added to the queues with the same id
// and if so -> remove it.
var currentIndex = this._queue.indexOf(id);
if (currentIndex > -1) this._queue[currentIndex] = undefined;
// Add all important callbacks to the beginning of the queue and other
// callbacks to the end of the queue.
isImportant ? this._queue.unshift(id) : this._queue.push(id);
// Store callbacks.
this._reads[id] = readCallback;
this._writes[id] = writeCallback;
// Finally, let's kick-start the next tick if it is not running yet.
if (!this._nextTick) this._nextTick = raf(this._flush);
};
Ticker.prototype.cancel = function(id) {
var currentIndex = this._queue.indexOf(id);
if (currentIndex > -1) {
this._queue[currentIndex] = undefined;
this._reads[id] = undefined;
this._writes[id] = undefined;
}
};
Ticker.prototype._flush = function() {
var queue = this._queue;
var reads = this._reads;
var writes = this._writes;
var batch = this._batch;
var batchReads = this._batchReads;
var batchWrites = this._batchWrites;
var length = queue.length;
var id;
var i;
// Reset ticker.
this._nextTick = null;
// Setup queues and callback placeholders.
for (i = 0; i < length; i++) {
id = queue[i];
if (!id) continue;
batch.push(id);
batchReads[id] = reads[id];
reads[id] = undefined;
batchWrites[id] = writes[id];
writes[id] = undefined;
}
// Reset queue.
queue.length = 0;
// Process read callbacks.
for (i = 0; i < length; i++) {
id = batch[i];
if (batchReads[id]) {
batchReads[id]();
batchReads[id] = undefined;
}
}
// Process write callbacks.
for (i = 0; i < length; i++) {
id = batch[i];
if (batchWrites[id]) {
batchWrites[id]();
batchWrites[id] = undefined;
}
}
// Reset batch.
batch.length = 0;
// Restart the ticker if needed.
if (!this._nextTick && queue.length) {
this._nextTick = raf(this._flush);
}
};
var ticker = new Ticker();
var proto = Element.prototype;
var matches =
proto.matches ||
proto.matchesSelector ||
proto.webkitMatchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector ||
proto.oMatchesSelector;
/**
* Check if element matches a CSS selector.
*
* @param {*} val
* @returns {Boolean}
*/
function elementMatches(el, selector) {
return matches.call(el, selector);
}
/**
* Add class to an element.
*
* @param {HTMLElement} element
* @param {String} className
*/
function addClassModern(element, className) {
element.classList.add(className);
}
/**
* Add class to an element (legacy version, for IE9 support).
*
* @param {HTMLElement} element
* @param {String} className
*/
function addClassLegacy(element, className) {
if (!elementMatches(element, '.' + className)) {
element.className += ' ' + className;
}
}
var addClass = ('classList' in Element.prototype ? addClassModern : addClassLegacy);
/**
* Normalize array index. Basically this function makes sure that the provided
* array index is within the bounds of the provided array and also transforms
* negative index to the matching positive index.
*
* @param {Array} array
* @param {Number} index
* @param {Boolean} isMigration
*/
function normalizeArrayIndex(array, index, isMigration) {
var length = array.length;
var maxIndex = Math.max(0, isMigration ? length : length - 1);
return index > maxIndex ? maxIndex : index < 0 ? Math.max(maxIndex + index + 1, 0) : index;
}
/**
* Move array item to another index.
*
* @param {Array} array
* @param {Number} fromIndex
* - Index (positive or negative) of the item that will be moved.
* @param {Number} toIndex
* - Index (positive or negative) where the item should be moved to.
*/
function arrayMove(array, fromIndex, toIndex) {
// Make sure the array has two or more items.
if (array.length < 2) return;
// Normalize the indices.
var from = normalizeArrayIndex(array, fromIndex);
var to = normalizeArrayIndex(array, toIndex);
// Add target item to the new position.
if (from !== to) {
array.splice(to, 0, array.splice(from, 1)[0]);
}
}
/**
* Swap array items.
*
* @param {Array} array
* @param {Number} index
* - Index (positive or negative) of the item that will be swapped.
* @param {Number} withIndex
* - Index (positive or negative) of the other item that will be swapped.
*/
function arraySwap(array, index, withIndex) {
// Make sure the array has two or more items.
if (array.length < 2) return;
// Normalize the indices.
var indexA = normalizeArrayIndex(array, index);
var indexB = normalizeArrayIndex(array, withIndex);
var temp;
// Swap the items.
if (indexA !== indexB) {
temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
}
}
var actionCancel = 'cancel';
var actionFinish = 'finish';
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. The returned function accepts one argument which, when
* being "finish", calls the debounce function immediately if it is currently
* waiting to be called, and when being "cancel" cancels the currently queued
* function call.
*
* @param {Function} fn
* @param {Number} wait
* @returns {Function}
*/
function debounce(fn, wait) {
var timeout;
if (wait > 0) {
return function(action) {
if (timeout !== undefined) {
timeout = window.clearTimeout(timeout);
if (action === actionFinish) fn();
}
if (action !== actionCancel && action !== actionFinish) {
timeout = window.setTimeout(function() {
timeout = undefined;
fn();
}, wait);
}
};
}
return function(action) {
if (action !== actionCancel) fn();
};
}
/**
* Returns true if element is transformed, false if not. In practice the
* element's display value must be anything else than "none" or "inline" as
* well as have a valid transform value applied in order to be counted as a
* transformed element.
*
* Borrowed from Mezr (v0.6.1):
* https://github.com/niklasramo/mezr/blob/0.6.1/mezr.js#L661
*
* @param {HTMLElement} element
* @returns {Boolean}
*/
function isTransformed(element) {
var transform = getStyle(element, 'transform');
if (!transform || transform === 'none') return false;
var display = getStyle(element, 'display');
if (display === 'inline' || display === 'none') return false;
return true;
}
/**
* Returns an absolute positioned element's containing block, which is
* considered to be the closest ancestor element that the target element's
* positioning is relative to. Disclaimer: this only works as intended for
* absolute positioned elements.
*
* @param {HTMLElement} element
* @param {Boolean} [includeSelf=false]
* - When this is set to true the containing block checking is started from
* the provided element. Otherwise the checking is started from the
* provided element's parent element.
* @returns {(Document|Element)}
*/
function getContainingBlock(element, includeSelf) {
// As long as the containing block is an element, static and not
// transformed, try to get the element's parent element and fallback to
// document. https://github.com/niklasramo/mezr/blob/0.6.1/mezr.js#L339
var ret = (includeSelf ? element : element.parentElement) || document;
while (ret && ret !== document && getStyle(ret, 'position') === 'static' && !isTransformed(ret)) {
ret = ret.parentElement || document;
}
return ret;
}
/**
* Returns the computed value of an element's style property transformed into
* a float value.
*
* @param {HTMLElement} el
* @param {String} style
* @returns {Number}
*/
function getStyleAsFloat(el, style) {
return parseFloat(getStyle(el, style)) || 0;
}
var offsetA = {};
var offsetB = {};
var offsetDiff = {};
/**
* Returns the element's document offset, which in practice means the vertical
* and horizontal distance between the element's northwest corner and the
* document's northwest corner. Note that this function always returns the same
* object so be sure to read the data from it instead using it as a reference.
*
* @param {(Document|Element|Window)} element
* @param {Object} [offsetData]
* - Optional data object where the offset data will be inserted to. If not
* provided a new object will be created for the return data.
* @returns {Object}
*/
function getOffset(element, offsetData) {
var ret = offsetData || {};
var rect;
// Set up return data.
ret.left = 0;
ret.top = 0;
// Document's offsets are always 0.
if (element === document) return ret;
// Add viewport scroll left/top to the respective offsets.
ret.left = window.pageXOffset || 0;
ret.top = window.pageYOffset || 0;
// Window's offsets are the viewport scroll left/top values.
if (element.self === window.self) return ret;
// Add element's client rects to the offsets.
rect = element.getBoundingClientRect();
ret.left += rect.left;
ret.top += rect.top;
// Exclude element's borders from the offset.
ret.left += getStyleAsFloat(element, 'border-left-width');
ret.top += getStyleAsFloat(element, 'border-top-width');
return ret;
}
/**
* Calculate the offset difference two elements.
*
* @param {HTMLElement} elemA
* @param {HTMLElement} elemB
* @param {Boolean} [compareContainingBlocks=false]
* - When this is set to true the containing blocks of the provided elements
* will be used for calculating the difference. Otherwise the provided
* elements will be compared directly.
* @returns {Object}
*/
function getOffsetDiff(elemA, elemB, compareContainingBlocks) {
offsetDiff.left = 0;
offsetDiff.top = 0;
// If elements are same let's return early.
if (elemA === elemB) return offsetDiff;
// Compare containing blocks if necessary.
if (compareContainingBlocks) {
elemA = getContainingBlock(elemA, true);
elemB = getContainingBlock(elemB, true);
// If containing blocks are identical, let's return early.
if (elemA === elemB) return offsetDiff;
}
// Finally, let's calculate the offset diff.
getOffset(elemA, offsetA);
getOffset(elemB, offsetB);
offsetDiff.left = offsetB.left - offsetA.left;
offsetDiff.top = offsetB.top - offsetA.top;
return offsetDiff;
}
var translateData = {};
/**
* Returns the element's computed translateX and translateY values as a floats.
* The returned object is always the same object and updated every time this
* function is called.
*
* @param {HTMLElement} element
* @returns {Object}
*/
function getTranslate(element) {
translateData.x = 0;
translateData.y = 0;
var transform = getStyle(element, 'transform');
if (!transform) return translateData;
var matrixData = transform.replace('matrix(', '').split(',');
translateData.x = parseFloat(matrixData[4]) || 0;
translateData.y = parseFloat(matrixData[5]) || 0;
return translateData;
}
/**
* Transform translateX and translateY value into CSS transform style
* property's value.
*
* @param {Number} x
* @param {Number} y
* @returns {String}
*/
function getTranslateString(x, y) {
return 'translateX(' + x + 'px) translateY(' + y + 'px)';
}
var tempArray = [];
/**
* Insert an item or an array of items to array to a specified index. Mutates
* the array. The index can be negative in which case the items will be added
* to the end of the array.
*
* @param {Array} array
* @param {*} items
* @param {Number} [index=-1]
*/
function arrayInsert(array, items, index) {
var startIndex = typeof index === 'number' ? index : -1;
if (startIndex < 0) startIndex = array.length - startIndex + 1;
array.splice.apply(array, tempArray.concat(startIndex, 0, items));
tempArray.length = 0;
}
var objectType = '[object Object]';
var toString = Object.prototype.toString;
/**
* Check if a value is a plain object.
*
* @param {*} val
* @returns {Boolean}
*/
function isPlainObject(val) {
return typeof val === 'object' && toString.call(val) === objectType;
}
/**
* Remove class from an element.
*
* @param {HTMLElement} element
* @param {String} className
*/
function removeClassModern(element, className) {
element.classList.remove(className);
}
/**
* Remove class from an element (legacy version, for IE9 support).
*
* @param {HTMLElement} element
* @param {String} className
*/
function removeClassLegacy(element, className) {
if (elementMatches(element, '.' + className)) {
element.className = (' ' + element.className + ' ').replace(' ' + className + ' ', ' ').trim();
}
}
var removeClass = ('classList' in Element.prototype ? removeClassModern : removeClassLegacy);
// To provide consistently correct dragging experience we need to know if
// transformed elements leak fixed elements or not.
var hasTransformLeak = checkTransformLeak();
// Drag start predicate states.
var startPredicateInactive = 0;
var startPredicatePending = 1;
var startPredicateResolved = 2;
var startPredicateRejected = 3;
/**
* Bind Hammer touch interaction to an item.
*
* @class
* @param {Item} item
*/
function ItemDrag(item) {
if (!Hammer) {
throw new Error('[' + namespace + '] required dependency Hammer is not defined.');
}
// If we don't have a valid transform leak test result yet, let's run the
// test on first ItemDrag init. The test needs body element to be ready and
// here we can be sure that it is ready.
if (hasTransformLeak === null) {
hasTransformLeak = checkTransformLeak();
}
var drag = this;
var element = item._element;
var grid = item.getGrid();
var settings = grid._settings;
var hammer;
// Start predicate private data.
var startPredicate =
typeof settings.dragStartPredicate === 'function'
? settings.dragStartPredicate
: ItemDrag.defaultStartPredicate;
var startPredicateState = startPredicateInactive;
var startPredicateResult;
// Protected data.
this._item = item;
this._gridId = grid._id;
this._hammer = hammer = new Hammer.Manager(element);
this._isDestroyed = false;
this._isMigrating = false;
// Setup item's initial drag data.
this._reset();
// Bind some methods that needs binding.
this._onScroll = this._onScroll.bind(this);
this._prepareMove = this._prepareMove.bind(this);
this._applyMove = this._applyMove.bind(this);
this._prepareScroll = this._prepareScroll.bind(this);
this._applyScroll = this._applyScroll.bind(this);
this._checkOverlap = this._checkOverlap.bind(this);
// Create a private drag start resolver that can be used to resolve the drag
// start predicate asynchronously.
this._forceResolveStartPredicate = function(event) {
if (!this._isDestroyed && startPredicateState === startPredicatePending) {
startPredicateState = startPredicateResolved;
this._onStart(event);
}
};
// Create debounce overlap checker function.
this._checkOverlapDebounce = debounce(this._checkOverlap, settings.dragSortInterval);
// Add drag recognizer to hammer.
hammer.add(
new Hammer.Pan({
event: 'drag',
pointers: 1,
threshold: 0,
direction: Hammer.DIRECTION_ALL
})
);
// Add drag init recognizer to hammer.
hammer.add(
new Hammer.Press({
event: 'draginit',
pointers: 1,
threshold: 1000,
time: 0
})
);
// Configure the hammer instance.
if (isPlainObject(settings.dragHammerSettings)) {
hammer.set(settings.dragHammerSettings);
}
// Bind drag events.
hammer
.on('draginit dragstart dragmove', function(e) {
// Let's activate drag start predicate state.
if (startPredicateState === startPredicateInactive) {
startPredicateState = startPredicatePending;
}
// If predicate is pending try to resolve it.
if (startPredicateState === startPredicatePending) {
startPredicateResult = startPredicate(drag._item, e);
if (startPredicateResult === true) {
startPredicateState = startPredicateResolved;
drag._onStart(e);
} else if (startPredicateResult === false) {
startPredicateState = startPredicateRejected;
}
}
// Otherwise if predicate is resolved and drag is active, move the item.
else if (startPredicateState === startPredicateResolved && drag._isActive) {
drag._onMove(e);
}
})
.on('dragend dragcancel draginitup', function(e) {
// Check if the start predicate was resolved during drag.
var isResolved = startPredicateState === startPredicateResolved;
// Do final predicate check to allow user to unbind stuff for the current
// drag procedure within the predicate callback. The return value of this
// check will have no effect to the state of the predicate.
startPredicate(drag._item, e);
// Reset start predicate state.
startPredicateState = startPredicateInactive;
// If predicate is resolved and dragging is active, call the end handler.
if (isResolved && drag._isActive) drag._onEnd(e);
});
// Prevent native link/image dragging for the item and it's ancestors.
element.addEventListener('dragstart', preventDefault, false);
}
/**
* Public static methods
* *********************
*/
/**
* Default drag start predicate handler that handles anchor elements
* gracefully. The return value of this function defines if the drag is
* started, rejected or pending. When true is returned the dragging is started
* and when false is returned the dragging is rejected. If nothing is returned
* the predicate will be called again on the next drag movement.
*
* @public
* @memberof ItemDrag
* @param {Item} item
* @param {Object} event
* @param {Object} [options]
* - An optional options object which can be used to pass the predicate
* it's options manually. By default the predicate retrieves the options
* from the grid's settings.
* @returns {Boolean}
*/
ItemDrag.defaultStartPredicate = function(item, event, options) {
var drag = item._drag;
var predicate = drag._startPredicateData || drag._setupStartPredicate(options);
// Final event logic. At this stage return value does not matter anymore,
// the predicate is either resolved or it's not and there's nothing to do
// about it. Here we just reset data and if the item element is a link
// we follow it (if there has only been slight movement).
if (event.isFinal) {
drag._finishStartPredicate(event);
return;
}
// Find and store the handle element so we can check later on if the
// cursor is within the handle. If we have a handle selector let's find
// the corresponding element. Otherwise let's use the item element as the
// handle.
if (!predicate.handleElement) {
predicate.handleElement = drag._getStartPredicateHandle(event);
if (!predicate.handleElement) return false;
}
// If delay is defined let's keep track of the latest event and initiate
// delay if it has not been done yet.
if (predicate.delay) {
predicate.event = event;
if (!predicate.delayTimer) {
predicate.delayTimer = window.setTimeout(function() {
predicate.delay = 0;
if (drag._resolveStartPredicate(predicate.event)) {
drag._forceResolveStartPredicate(predicate.event);
drag._resetStartPredicate();
}
}, predicate.delay);
}
}
return drag._resolveStartPredicate(event);
};
/**
* Default drag sort predicate.
*
* @public
* @memberof ItemDrag
* @param {Item} item
* @param {Object} [options]
* @param {Number} [options.threshold=50]
* @param {String} [options.action='move']
* @returns {(Boolean|DragSortCommand)}
* - Returns false if no valid index was found. Otherwise returns drag sort
* command.
*/
ItemDrag.defaultSortPredicate = (function() {
var itemRect = {};
var targetRect = {};
var returnData = {};
var rootGridArray = [];
function getTargetGrid(item, rootGrid, threshold) {
var target = null;
var dragSort = rootGrid._settings.dragSort;
var bestScore = -1;
var gridScore;
var grids;
var grid;
var i;
// Get potential target grids.
if (dragSort === true) {
rootGridArray[0] = rootGrid;
grids = rootGridArray;
} else {
grids = dragSort.call(rootGrid, item);
}
// Return immediately if there are no grids.
if (!Array.isArray(grids)) return target;
// Loop through the grids and get the best match.
for (i = 0; i < grids.length; i++) {
grid = grids[i];
// Filter out all destroyed grids.
if (grid._isDestroyed) continue;
// We need to update the grid's offsets and dimensions since they might
// have changed (e.g during scrolling).
grid._updateBoundingRect();
// Check how much dragged element overlaps the container element.
targetRect.width = grid._width;
targetRect.height = grid._height;
targetRect.left = grid._left;
targetRect.top = grid._top;
gridScore = getRectOverlapScore(itemRect, targetRect);
// Check if this grid is the best match so far.
if (gridScore > threshold && gridScore > bestScore) {
bestScore = gridScore;
target = grid;
}
}
// Always reset root grid array.
rootGridArray.length = 0;
return target;
}
return function(item, options) {
var drag = item._drag;
var rootGrid = drag._getGrid();
// Get drag sort predicate settings.
var sortThreshold = options && typeof options.threshold === 'number' ? options.threshold : 50;
var sortAction = options && options.action === 'swap' ? 'swap' : 'move';
// Populate item rect data.
itemRect.width = item._width;
itemRect.height = item._height;
itemRect.left = drag._elementClientX;
itemRect.top = drag._elementClientY;
// Calculate the target grid.
var grid = getTargetGrid(item, rootGrid, sortThreshold);
// Return early if we found no grid container element that overlaps the
// dragged item enough.
if (!grid) return false;
var gridOffsetLeft = 0;
var gridOffsetTop = 0;
var matchScore = -1;
var matchIndex;
var hasValidTargets;
var target;
var score;
var i;
// If item is moved within it's originating grid adjust item's left and
// top props. Otherwise if item is moved to/within another grid get the
// container element's offset (from the element's content edge).
if (grid === rootGrid) {
itemRect.left = drag._gridX + item._marginLeft;
itemRect.top = drag._gridY + item._marginTop;
} else {
grid._updateBorders(1, 0, 1, 0);
gridOffsetLeft = grid._left + grid._borderLeft;
gridOffsetTop = grid._top + grid._borderTop;
}
// Loop through the target grid items and try to find the best match.
for (i = 0; i < grid._items.length; i++) {
target = grid._items[i];
// If the target item is not active or the target item is the dragged
// item let's skip to the next item.
if (!target._isActive || target === item) {
continue;
}
// Mark the grid as having valid target items.
hasValidTargets = true;
// Calculate the target's overlap score with the dragged item.
targetRect.width = target._width;
targetRect.height = target._height;
targetRect.left = target._left + target._marginLeft + gridOffsetLeft;
targetRect.top = target._top + target._marginTop + gridOffsetTop;
score = getRectOverlapScore(itemRect, targetRect);
// Update best match index and score if the target's overlap score with
// the dragged item is higher than the current best match score.
if (score > matchScore) {
matchIndex = i;
matchScore = score;
}
}
// If there is no valid match and the item is being moved into another
// grid.
if (matchScore < sortThreshold && item.getGrid() !== grid) {
matchIndex = hasValidTargets ? -1 : 0;
matchScore = Infinity;
}
// Check if the best match overlaps enough to justify a placement switch.
if (matchScore >= sortThreshold) {
returnData.grid = grid;
returnData.index = matchIndex;
returnData.action = sortAction;
return returnData;
}
return false;
};
})();
/**
* Public prototype methods
* ************************
*/
/**
* Abort dragging and reset drag data.
*
* @public
* @memberof ItemDrag.prototype
* @returns {ItemDrag}
*/
ItemDrag.prototype.stop = function() {
var item = this._item;
var element = item._element;
var grid = this._getGrid();
if (!this._isActive) return this;
// If the item is being dropped into another grid, finish it up and return
// immediately.
if (this._isMigrating) {
this._finishMigration();
return this;
}
// Cancel raf loop actions.
this._cancelAsyncUpdates();
// Remove scroll listeners.
this._unbindScrollListeners();
// Cancel overlap check.
this._checkOverlapDebounce('cancel');
// Append item element to the container if it's not it's child. Also make
// sure the translate values are adjusted to account for the DOM shift.
if (element.parentNode !== grid._element) {
grid._element.appendChild(element);
element.style[transformProp] = getTranslateString(this._gridX, this._gridY);
}
// Remove dragging class.
removeClass(element, grid._settings.itemDraggingClass);
// Reset drag data.
this._reset();
return this;
};
/**
* Destroy instance.
*
* @public
* @memberof ItemDrag.prototype
* @returns {ItemDrag}
*/
ItemDrag.prototype.destroy = function() {
if (this._isDestroyed) return this;
this.stop();
this._hammer.destroy();
this._item._element.removeEventListener('dragstart', preventDefault, false);
this._isDestroyed = true;
return this;
};
/**
* Private prototype methods
* *************************
*/
/**
* Get Grid instance.
*
* @private
* @memberof ItemDrag.prototype
* @returns {?Grid}
*/
ItemDrag.prototype._getGrid = function() {
return gridInstances[this._gridId] || null;
};
/**
* Setup/reset drag data.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._reset = function() {
// Is item being dragged?
this._isActive = false;
// The dragged item's container element.
this._container = null;
// The dragged item's containing block.
this._containingBlock = null;
// Hammer event data.
this._lastEvent = null;
this._lastScrollEvent = null;
// All the elements which need to be listened for scroll events during
// dragging.
this._scrollers = [];
// The current translateX/translateY position.
this._left = 0;
this._top = 0;
// Dragged element's current position within the grid.
this._gridX = 0;
this._gridY = 0;
// Dragged element's current offset from window's northwest corner. Does
// not account for element's margins.
this._elementClientX = 0;
this._elementClientY = 0;
// Offset difference between the dragged element's temporary drag
// container and it's original container.
this._containerDiffX = 0;
this._containerDiffY = 0;
};
/**
* Bind drag scroll handlers to all scrollable ancestor elements of the
* dragged element and the drag container element.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._bindScrollListeners = function() {
var gridContainer = this._getGrid()._element;
var dragContainer = this._container;
var scrollers = this._scrollers;
var containerScrollers;
var i;
// Get dragged element's scrolling parents.
scrollers.length = 0;
getScrollParents(this._item._element, scrollers);
// If drag container is defined and it's not the same element as grid
// container then we need to add the grid container and it's scroll parents
// to the elements which are going to be listener for scroll events.
if (dragContainer !== gridContainer) {
containerScrollers = [];
getScrollParents(gridContainer, containerScrollers);
containerScrollers.push(gridContainer);
for (i = 0; i < containerScrollers.length; i++) {
if (scrollers.indexOf(containerScrollers[i]) < 0) {
scrollers.push(containerScrollers[i]);
}
}
}
// Bind scroll listeners.
for (i = 0; i < scrollers.length; i++) {
scrollers[i].addEventListener('scroll', this._onScroll);
}
};
/**
* Unbind currently bound drag scroll handlers from all scrollable ancestor
* elements of the dragged element and the drag container element.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._unbindScrollListeners = function() {
var scrollers = this._scrollers;
var i;
for (i = 0; i < scrollers.length; i++) {
scrollers[i].removeEventListener('scroll', this._onScroll);
}
scrollers.length = 0;
};
/**
* Setup default start predicate.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} [options]
* @returns {Object}
*/
ItemDrag.prototype._setupStartPredicate = function(options) {
var config = options || this._getGrid()._settings.dragStartPredicate || 0;
return (this._startPredicateData = {
distance: Math.abs(config.distance) || 0,
delay: Math.max(config.delay, 0) || 0,
handle: typeof config.handle === 'string' ? config.handle : false
});
};
/**
* Setup default start predicate handle.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
* @returns {?HTMLElement}
*/
ItemDrag.prototype._getStartPredicateHandle = function(event) {
var predicate = this._startPredicateData;
var element = this._item._element;
var handleElement = element;
// No handle, no hassle -> let's use the item element as the handle.
if (!predicate.handle) return handleElement;
// If there is a specific predicate handle defined, let's try to get it.
handleElement = (event.changedPointers[0] || 0).target;
while (handleElement && !elementMatches(handleElement, predicate.handle)) {
handleElement = handleElement !== element ? handleElement.parentElement : null;
}
return handleElement || null;
};
/**
* Unbind currently bound drag scroll handlers from all scrollable ancestor
* elements of the dragged element and the drag container element.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
* @returns {Boolean}
*/
ItemDrag.prototype._resolveStartPredicate = function(event) {
var predicate = this._startPredicateData;
var pointer = event.changedPointers[0];
var pageX = (pointer && pointer.pageX) || 0;
var pageY = (pointer && pointer.pageY) || 0;
var handleRect;
var handleLeft;
var handleTop;
var handleWidth;
var handleHeight;
// If the moved distance is smaller than the threshold distance or there is
// some delay left, ignore this predicate cycle.
if (event.distance < predicate.distance || predicate.delay) return;
// Get handle rect data.
handleRect = predicate.handleElement.getBoundingClientRect();
handleLeft = handleRect.left + (window.pageXOffset || 0);
handleTop = handleRect.top + (window.pageYOffset || 0);
handleWidth = handleRect.width;
handleHeight = handleRect.height;
// Reset predicate data.
this._resetStartPredicate();
// If the cursor is still within the handle let's start the drag.
return (
handleWidth &&
handleHeight &&
pageX >= handleLeft &&
pageX < handleLeft + handleWidth &&
pageY >= handleTop &&
pageY < handleTop + handleHeight
);
};
/**
* Finalize start predicate.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
*/
ItemDrag.prototype._finishStartPredicate = function(event) {
var element = this._item._element;
// Reset predicate.
this._resetStartPredicate();
// If the gesture can be interpreted as click let's try to open the element's
// href url (if it is an anchor element).
if (isClick(event)) openAnchorHref(element);
};
/**
* Reset for default drag start predicate function.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._resetStartPredicate = function() {
var predicate = this._startPredicateData;
if (predicate) {
if (predicate.delayTimer) {
predicate.delayTimer = window.clearTimeout(predicate.delayTimer);
}
this._startPredicateData = null;
}
};
/**
* Check (during drag) if an item is overlapping other items and based on
* the configuration layout the items.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._checkOverlap = function() {
if (!this._isActive) return;
var item = this._item;
var settings = this._getGrid()._settings;
var result;
var currentGrid;
var currentIndex;
var targetGrid;
var targetIndex;
var sortAction;
var isMigration;
// Get overlap check result.
if (typeof settings.dragSortPredicate === 'function') {
result = settings.dragSortPredicate(item, this._lastEvent);
} else {
result = ItemDrag.defaultSortPredicate(item, settings.dragSortPredicate);
}
// Let's make sure the result object has a valid index before going further.
if (!result || typeof result.index !== 'number') return;
currentGrid = item.getGrid();
targetGrid = result.grid || currentGrid;
isMigration = currentGrid !== targetGrid;
currentIndex = currentGrid._items.indexOf(item);
targetIndex = normalizeArrayIndex(targetGrid._items, result.index, isMigration);
sortAction = result.action === 'swap' ? 'swap' : 'move';
// If the item was moved within it's current grid.
if (!isMigration) {
// Make sure the target index is not the current index.
if (currentIndex !== targetIndex) {
// Do the sort.
(sortAction === 'swap' ? arraySwap : arrayMove)(
currentGrid._items,
currentIndex,
targetIndex
);
// Emit move event.
if (currentGrid._hasListeners(eventMove)) {
currentGrid._emit(eventMove, {
item: item,
fromIndex: currentIndex,
toIndex: targetIndex,
action: sortAction
});
}
// Layout the grid.
currentGrid.layout();
}
}
// If the item was moved to another grid.
else {
// Emit beforeSend event.
if (currentGrid._hasListeners(eventBeforeSend)) {
currentGrid._emit(eventBeforeSend, {
item: item,
fromGrid: currentGrid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Emit beforeReceive event.
if (targetGrid._hasListeners(eventBeforeReceive)) {
targetGrid._emit(eventBeforeReceive, {
item: item,
fromGrid: currentGrid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Update item's grid id reference.
item._gridId = targetGrid._id;
// Update drag instance's migrating indicator.
this._isMigrating = item._gridId !== this._gridId;
// Move item instance from current grid to target grid.
currentGrid._items.splice(currentIndex, 1);
arrayInsert(targetGrid._items, item, targetIndex);
// Set sort data as null, which is an indicator for the item comparison
// function that the sort data of this specific item should be fetched
// lazily.
item._sortData = null;
// Emit send event.
if (currentGrid._hasListeners(eventSend)) {
currentGrid._emit(eventSend, {
item: item,
fromGrid: currentGrid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Emit receive event.
if (targetGrid._hasListeners(eventReceive)) {
targetGrid._emit(eventReceive, {
item: item,
fromGrid: currentGrid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Layout both grids.
currentGrid.layout();
targetGrid.layout();
}
};
/**
* If item is dragged into another grid, finish the migration process
* gracefully.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._finishMigration = function() {
var item = this._item;
var release = item._release;
var element = item._element;
var isActive = item._isActive;
var targetGrid = item.getGrid();
var targetGridElement = targetGrid._element;
var targetSettings = targetGrid._settings;
var targetContainer = targetSettings.dragContainer || targetGridElement;
var currentSettings = this._getGrid()._settings;
var currentContainer = element.parentNode;
var translate;
var offsetDiff;
// Destroy current drag. Note that we need to set the migrating flag to
// false first, because otherwise we create an infinite loop between this
// and the drag.stop() method.
this._isMigrating = false;
this.destroy();
// Remove current classnames.
removeClass(element, currentSettings.itemClass);
removeClass(element, currentSettings.itemVisibleClass);
removeClass(element, currentSettings.itemHiddenClass);
// Add new classnames.
addClass(element, targetSettings.itemClass);
addClass(element, isActive ? targetSettings.itemVisibleClass : targetSettings.itemHiddenClass);
// Move the item inside the target container if it's different than the
// current container.
if (targetContainer !== currentContainer) {
targetContainer.appendChild(element);
offsetDiff = getOffsetDiff(currentContainer, targetContainer, true);
translate = getTranslate(element);
translate.x -= offsetDiff.left;
translate.y -= offsetDiff.top;
}
// Update item's cached dimensions and sort data.
item._refreshDimensions();
item._refreshSortData();
// Calculate the offset difference between target's drag container (if any)
// and actual grid container element. We save it later for the release
// process.
offsetDiff = getOffsetDiff(targetContainer, targetGridElement, true);
release._containerDiffX = offsetDiff.left;
release._containerDiffY = offsetDiff.top;
// Recreate item's drag handler.
item._drag = targetSettings.dragEnabled ? new ItemDrag(item) : null;
// Adjust the position of the item element if it was moved from a container
// to another.
if (targetContainer !== currentContainer) {
element.style[transformProp] = getTranslateString(translate.x, translate.y);
}
// Update child element's styles to reflect the current visibility state.
item._child.removeAttribute('style');
setStyles(item._child, isActive ? targetSettings.visibleStyles : targetSettings.hiddenStyles);
// Start the release.
release.start();
};
/**
* Cancel move/scroll event ticker action.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._cancelAsyncUpdates = function() {
var id = this._item._id;
ticker.cancel(id + 'move');
ticker.cancel(id + 'scroll');
};
/**
* Drag start handler.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
*/
ItemDrag.prototype._onStart = function(event) {
var item = this._item;
// If item is not active, don't start the drag.
if (!item._isActive) return;
var element = item._element;
var grid = this._getGrid();
var settings = grid._settings;
var release = item._release;
var migrate = item._migrate;
var gridContainer = grid._element;
var dragContainer = settings.dragContainer || gridContainer;
var containingBlock = getContainingBlock(dragContainer, true);
var translate = getTranslate(element);
var currentLeft = translate.x;
var currentTop = translate.y;
var elementRect = element.getBoundingClientRect();
var hasDragContainer = dragContainer !== gridContainer;
var offsetDiff;
// If grid container is not the drag container, we need to calculate the
// offset difference between grid container and drag container's containing
// element.
if (hasDragContainer) {
offsetDiff = getOffsetDiff(containingBlock, gridContainer);
}
// Stop current positioning animation.
if (item.isPositioning()) {
item._layout.stop(true, { transform: getTranslateString(currentLeft, currentTop) });
}
// Stop current migration animation.
if (migrate._isActive) {
currentLeft -= migrate._containerDiffX;
currentTop -= migrate._containerDiffY;
migrate.stop(true, { transform: getTranslateString(currentLeft, currentTop) });
}
// If item is being released reset release data.
if (item.isReleasing()) release._reset();
// Setup drag data.
this._isActive = true;
this._lastEvent = event;
this._container = dragContainer;
this._containingBlock = containingBlock;
this._elementClientX = elementRect.left;
this._elementClientY = elementRect.top;
this._left = this._gridX = currentLeft;
this._top = this._gridY = currentTop;
// Emit dragInit event.
grid._emit(eventDragInit, item, event);
// If a specific drag container is set and it is different from the
// grid's container element we need to cast some extra spells.
if (hasDragContainer) {
// Store the container offset diffs to drag data.
this._containerDiffX = offsetDiff.left;
this._containerDiffY = offsetDiff.top;
// If the dragged element is a child of the drag container all we need to
// do is setup the relative drag position data.
if (element.parentNode === dragContainer) {
this._gridX = currentLeft - this._containerDiffX;
this._gridY = currentTop - this._containerDiffY;
}
// Otherwise we need to append the element inside the correct container,
// setup the actual drag position data and adjust the element's translate
// values to account for the DOM position shift.
else {
this._left = currentLeft + this._containerDiffX;
this._top = currentTop + this._containerDiffY;
dragContainer.appendChild(element);
element.style[transformProp] = getTranslateString(this._left, this._top);
}
}
// Set drag class and bind scrollers.
addClass(element, settings.itemDraggingClass);
this._bindScrollListeners();
// Emit dragStart event.
grid._emit(eventDragStart, item, event);
};
/**
* Drag move handler.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
*/
ItemDrag.prototype._onMove = function(event) {
var item = this._item;
// If item is not active, reset drag.
if (!item._isActive) {
this.stop();
return;
}
var settings = this._getGrid()._settings;
var axis = settings.dragAxis;
var xDiff = event.deltaX - this._lastEvent.deltaX;
var yDiff = event.deltaY - this._lastEvent.deltaY;
// Update last event.
this._lastEvent = event;
// Update horizontal position data.
if (axis !== 'y') {
this._left += xDiff;
this._gridX += xDiff;
this._elementClientX += xDiff;
}
// Update vertical position data.
if (axis !== 'x') {
this._top += yDiff;
this._gridY += yDiff;
this._elementClientY += yDiff;
}
// Do move prepare/apply handling in the next tick.
ticker.add(item._id + 'move', this._prepareMove, this._applyMove, true);
};
/**
* Prepare dragged item for moving.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._prepareMove = function() {
// Do nothing if item is not active.
if (!this._item._isActive) return;
// If drag sort is enabled -> check overlap.
if (this._getGrid()._settings.dragSort) this._checkOverlapDebounce();
};
/**
* Apply movement to dragged item.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._applyMove = function() {
var item = this._item;
// Do nothing if item is not active.
if (!item._isActive) return;
// Update element's translateX/Y values.
item._element.style[transformProp] = getTranslateString(this._left, this._top);
// Emit dragMove event.
this._getGrid()._emit(eventDragMove, item, this._lastEvent);
};
/**
* Drag scroll handler.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
*/
ItemDrag.prototype._onScroll = function(event) {
var item = this._item;
// If item is not active, reset drag.
if (!item._isActive) {
this.stop();
return;
}
// Update last scroll event.
this._lastScrollEvent = event;
// Do scroll prepare/apply handling in the next tick.
ticker.add(item._id + 'scroll', this._prepareScroll, this._applyScroll, true);
};
/**
* Prepare dragged item for scrolling.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._prepareScroll = function() {
var item = this._item;
// If item is not active do nothing.
if (!item._isActive) return;
var element = item._element;
var grid = this._getGrid();
var settings = grid._settings;
var axis = settings.dragAxis;
var gridContainer = grid._element;
var offsetDiff;
// Calculate element's rect and x/y diff.
var rect = element.getBoundingClientRect();
var xDiff = this._elementClientX - rect.left;
var yDiff = this._elementClientY - rect.top;
// Update container diff.
if (this._container !== gridContainer) {
offsetDiff = getOffsetDiff(this._containingBlock, gridContainer);
this._containerDiffX = offsetDiff.left;
this._containerDiffY = offsetDiff.top;
}
// Update horizontal position data.
if (axis !== 'y') {
this._left += xDiff;
this._gridX = this._left - this._containerDiffX;
}
// Update vertical position data.
if (axis !== 'x') {
this._top += yDiff;
this._gridY = this._top - this._containerDiffY;
}
// Overlap handling.
if (settings.dragSort) this._checkOverlapDebounce();
};
/**
* Apply scroll to dragged item.
*
* @private
* @memberof ItemDrag.prototype
*/
ItemDrag.prototype._applyScroll = function() {
var item = this._item;
// If item is not active do nothing.
if (!item._isActive) return;
// Update element's translateX/Y values.
item._element.style[transformProp] = getTranslateString(this._left, this._top);
// Emit dragScroll event.
this._getGrid()._emit(eventDragScroll, item, this._lastScrollEvent);
};
/**
* Drag end handler.
*
* @private
* @memberof ItemDrag.prototype
* @param {Object} event
*/
ItemDrag.prototype._onEnd = function(event) {
var item = this._item;
var element = item._element;
var grid = this._getGrid();
var settings = grid._settings;
var release = item._release;
// If item is not active, reset drag.
if (!item._isActive) {
this.stop();
return;
}
// Cancel ticker actions.
this._cancelAsyncUpdates();
// Finish currently queued overlap check.
settings.dragSort && this._checkOverlapDebounce('finish');
// Remove scroll listeners.
this._unbindScrollListeners();
// Setup release data.
release._containerDiffX = this._containerDiffX;
release._containerDiffY = this._containerDiffY;
// Reset drag data.
this._reset();
// Remove drag class name from element.
removeClass(element, settings.itemDraggingClass);
// Emit dragEnd event.
grid._emit(eventDragEnd, item, event);
// Finish up the migration process or start the release process.
this._isMigrating ? this._finishMigration() : release.start();
};
/**
* Private helpers
* ***************
*/
/**
* Prevent default.
*
* @param {Object} e
*/
function preventDefault(e) {
if (e.preventDefault) e.preventDefault();
}
/**
* Calculate how many percent the intersection area of two rectangles is from
* the maximum potential intersection area between the rectangles.
*
* @param {Rectangle} a
* @param {Rectangle} b
* @returns {Number}
* - A number between 0-100.
*/
function getRectOverlapScore(a, b) {
// Return 0 immediately if the rectangles do not overlap.
if (
a.left + a.width <= b.left ||
b.left + b.width <= a.left ||
a.top + a.height <= b.top ||
b.top + b.height <= a.top
) {
return 0;
}
// Calculate intersection area's width, height, max height and max width.
var width = Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left);
var height = Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top);
var maxWidth = Math.min(a.width, b.width);
var maxHeight = Math.min(a.height, b.height);
return ((width * height) / (maxWidth * maxHeight)) * 100;
}
/**
* Get element's scroll parents.
*
* @param {HTMLElement} element
* @param {Array} [data]
* @returns {HTMLElement[]}
*/
function getScrollParents(element, data) {
var ret = data || [];
var parent = element.parentNode;
//
// If transformed elements leak fixed elements.
//
if (hasTransformLeak) {
// If the element is fixed it can not have any scroll parents.
if (getStyle(element, 'position') === 'fixed') return ret;
// Find scroll parents.
while (parent && parent !== document && parent !== document.documentElement) {
if (isScrollable(parent)) ret.push(parent);
parent = getStyle(parent, 'position') === 'fixed' ? null : parent.parentNode;
}
// If parent is not fixed element, add window object as the last scroll
// parent.
parent !== null && ret.push(window);
return ret;
}
//
// If fixed elements behave as defined in the W3C specification.
//
// Find scroll parents.
while (parent && parent !== document) {
// If the currently looped element is fixed ignore all parents that are
// not transformed.
if (getStyle(element, 'position') === 'fixed' && !isTransformed(parent)) {
parent = parent.parentNode;
continue;
}
// Add the parent element to return items if it is scrollable.
if (isScrollable(parent)) ret.push(parent);
// Update element and parent references.
element = parent;
parent = parent.parentNode;
}
// If the last item is the root element, replace it with window. The root
// element scroll is propagated to the window.
if (ret[ret.length - 1] === document.documentElement) {
ret[ret.length - 1] = window;
}
// Otherwise add window as the last scroll parent.
else {
ret.push(window);
}
return ret;
}
/**
* Check if an element is scrollable.
*
* @param {HTMLElement} element
* @returns {Boolean}
*/
function isScrollable(element) {
var overflow = getStyle(element, 'overflow');
if (overflow === 'auto' || overflow === 'scroll') return true;
overflow = getStyle(element, 'overflow-x');
if (overflow === 'auto' || overflow === 'scroll') return true;
overflow = getStyle(element, 'overflow-y');
if (overflow === 'auto' || overflow === 'scroll') return true;
return false;
}
/**
* Check if drag gesture can be interpreted as a click, based on final drag
* event data.
*
* @param {Object} element
* @returns {Boolean}
*/
function isClick(event) {
return Math.abs(event.deltaX) < 2 && Math.abs(event.deltaY) < 2 && event.deltaTime < 200;
}
/**
* Check if an element is an anchor element and open the href url if possible.
*
* @param {HTMLElement} element
*/
function openAnchorHref(element) {
// Make sure the element is anchor element.
if (element.tagName.toLowerCase() !== 'a') return;
// Get href and make sure it exists.
var href = element.getAttribute('href');
if (!href) return;
// Finally let's navigate to the link href.
var target = element.getAttribute('target');
if (target && target !== '_self') {
window.open(href, target);
} else {
window.location.href = href;
}
}
/**
* Detects if transformed elements leak fixed elements. According W3C
* transform rendering spec a transformed element should contain even fixed
* elements. Meaning that fixed elements are positioned relative to the
* closest transformed ancestor element instead of window. However, not every
* browser follows the spec (IE and older Firefox). So we need to test it.
* https://www.w3.org/TR/css3-2d-transforms/#transform-rendering
*
* Borrowed from Mezr (v0.6.1):
* https://github.com/niklasramo/mezr/blob/0.6.1/mezr.js#L607
*/
function checkTransformLeak() {
// No transforms -> definitely leaks.
if (!isTransformSupported) return true;
// No body available -> can't check it.
if (!document.body) return null;
// Do the test.
var elems = [0, 1].map(function(elem, isInner) {
elem = document.createElement('div');
elem.style.position = isInner ? 'fixed' : 'absolute';
elem.style.display = 'block';
elem.style.visibility = 'hidden';
elem.style.left = isInner ? '0px' : '1px';
elem.style[transformProp] = 'none';
return elem;
});
var outer = document.body.appendChild(elems[0]);
var inner = outer.appendChild(elems[1]);
var left = inner.getBoundingClientRect().left;
outer.style[transformProp] = 'scale(1)';
var ret = left === inner.getBoundingClientRect().left;
document.body.removeChild(outer);
return ret;
}
/**
* Queue constructor.
*
* @class
*/
function Queue() {
this._queue = [];
this._isDestroyed = false;
}
/**
* Public prototype methods
* ************************
*/
/**
* Add callback to the queue.
*
* @public
* @memberof Queue.prototype
* @param {Function} callback
* @returns {Queue}
*/
Queue.prototype.add = function(callback) {
if (this._isDestroyed) return this;
this._queue.push(callback);
return this;
};
/**
* Process queue callbacks and reset the queue.
*
* @public
* @memberof Queue.prototype
* @param {*} arg1
* @param {*} arg2
* @returns {Queue}
*/
Queue.prototype.flush = function(arg1, arg2) {
if (this._isDestroyed) return this;
var queue = this._queue;
var length = queue.length;
var i;
// Quit early if the queue is empty.
if (!length) return this;
var singleCallback = length === 1;
var snapshot = singleCallback ? queue[0] : queue.slice(0);
// Reset queue.
queue.length = 0;
// If we only have a single callback let's just call it.
if (singleCallback) {
snapshot(arg1, arg2);
return this;
}
// If we have multiple callbacks, let's process them.
for (i = 0; i < length; i++) {
snapshot[i](arg1, arg2);
if (this._isDestroyed) break;
}
return this;
};
/**
* Destroy Queue instance.
*
* @public
* @memberof Queue.prototype
* @returns {Queue}
*/
Queue.prototype.destroy = function() {
if (this._isDestroyed) return this;
this._isDestroyed = true;
this._queue.length = 0;
return this;
};
/**
* Layout manager for Item instance.
*
* @class
* @param {Item} item
*/
function ItemLayout(item) {
this._item = item;
this._isActive = false;
this._isDestroyed = false;
this._isInterrupted = false;
this._currentStyles = {};
this._targetStyles = {};
this._currentLeft = 0;
this._currentTop = 0;
this._offsetLeft = 0;
this._offsetTop = 0;
this._skipNextAnimation = false;
this._animateOptions = {
onFinish: this._finish.bind(this)
};
this._queue = new Queue();
// Bind animation handlers and finish method.
this._setupAnimation = this._setupAnimation.bind(this);
this._startAnimation = this._startAnimation.bind(this);
}
/**
* Public prototype methods
* ************************
*/
/**
* Start item layout based on it's current data.
*
* @public
* @memberof ItemLayout.prototype
* @param {Boolean} [instant=false]
* @param {Function} [onFinish]
* @returns {ItemLayout}
*/
ItemLayout.prototype.start = function(instant, onFinish) {
if (this._isDestroyed) return;
var item = this._item;
var element = item._element;
var migrate = item._migrate;
var release = item._release;
var gridSettings = item.getGrid()._settings;
var isPositioning = this._isActive;
var isJustReleased = release._isActive && release._isPositioningStarted === false;
var animDuration = isJustReleased
? gridSettings.dragReleaseDuration
: gridSettings.layoutDuration;
var animEasing = isJustReleased ? gridSettings.dragReleaseEasing : gridSettings.layoutEasing;
var animEnabled = !instant && !this._skipNextAnimation && animDuration > 0;
var offsetLeft;
var offsetTop;
var isAnimating;
// If the item is currently positioning process current layout callback
// queue with interrupted flag on.
if (isPositioning) this._queue.flush(true, item);
// Mark release positioning as started.
if (isJustReleased) release._isPositioningStarted = true;
// Push the callback to the callback queue.
if (typeof onFinish === 'function') this._queue.add(onFinish);
// Get item container's left offset.
offsetLeft = release._isActive
? release._containerDiffX
: migrate._isActive
? migrate._containerDiffX
: 0;
// Get item container's top offset.
offsetTop = release._isActive
? release._containerDiffY
: migrate._isActive
? migrate._containerDiffY
: 0;
// Get target styles.
this._targetStyles.transform = getTranslateString(item._left + offsetLeft, item._top + offsetTop);
// If no animations are needed, easy peasy!
if (!animEnabled) {
isPositioning && ticker.cancel(item._id);
isAnimating = item._animate.isAnimating();
this.stop(false, this._targetStyles);
!isAnimating && setStyles(element, this._targetStyles);
this._skipNextAnimation = false;
return this._finish();
}
// Set item active and store some data for the animation that is about to be
// triggered.
this._isActive = true;
this._animateOptions.easing = animEasing;
this._animateOptions.duration = animDuration;
this._isInterrupted = isPositioning;
this._offsetLeft = offsetLeft;
this._offsetTop = offsetTop;
// Start the item's layout animation in the next tick.
ticker.add(item._id, this._setupAnimation, this._startAnimation);
return this;
};
/**
* Stop item's position animation if it is currently animating.
*
* @public
* @memberof ItemLayout.prototype
* @param {Boolean} [processCallbackQueue=false]
* @param {Object} [targetStyles]
* @returns {ItemLayout}
*/
ItemLayout.prototype.stop = function(processCallbackQueue, targetStyles) {
if (this._isDestroyed || !this._isActive) return this;
var item = this._item;
// Cancel animation init.
ticker.cancel(item._id);
// Stop animation.
item._animate.stop(targetStyles);
// Remove positioning class.
removeClass(item._element, item.getGrid()._settings.itemPositioningClass);
// Reset active state.
this._isActive = false;
// Process callback queue if needed.
if (processCallbackQueue) this._queue.flush(true, item);
return this;
};
/**
* Destroy the instance and stop current animation if it is running.
*
* @public
* @memberof ItemLayout.prototype
* @returns {ItemLayout}
*/
ItemLayout.prototype.destroy = function() {
if (this._isDestroyed) return this;
this.stop(true, {});
this._queue.destroy();
this._item = this._currentStyles = this._targetStyles = this._animateOptions = null;
this._isDestroyed = true;
return this;
};
/**
* Private prototype methods
* *************************
*/
/**
* Finish item layout procedure.
*
* @private
* @memberof ItemLayout.prototype
*/
ItemLayout.prototype._finish = function() {
if (this._isDestroyed) return;
var item = this._item;
var migrate = item._migrate;
var release = item._release;
// Mark the item as inactive and remove positioning classes.
if (this._isActive) {
this._isActive = false;
removeClass(item._element, item.getGrid()._settings.itemPositioningClass);
}
// Finish up release and migration.
if (release._isActive) release.stop();
if (migrate._isActive) migrate.stop();
// Process the callback queue.
this._queue.flush(false, item);
};
/**
* Prepare item for layout animation.
*
* @private
* @memberof ItemLayout.prototype
*/
ItemLayout.prototype._setupAnimation = function() {
var element = this._item._element;
var translate = getTranslate(element);
this._currentLeft = translate.x - this._offsetLeft;
this._currentTop = translate.y - this._offsetTop;
};
/**
* Start layout animation.
*
* @private
* @memberof ItemLayout.prototype
*/
ItemLayout.prototype._startAnimation = function() {
var item = this._item;
var element = item._element;
var grid = item.getGrid();
var settings = grid._settings;
// If the item is already in correct position let's quit early.
if (item._left === this._currentLeft && item._top === this._currentTop) {
this._isInterrupted && this.stop(false, this._targetStyles);
this._isActive = false;
this._finish();
return;
}
// Set item's positioning class if needed.
!this._isInterrupted && addClass(element, settings.itemPositioningClass);
// Get current styles for animation.
this._currentStyles.transform = getTranslateString(
this._currentLeft + this._offsetLeft,
this._currentTop + this._offsetTop
);
// Animate.
item._animate.start(this._currentStyles, this._targetStyles, this._animateOptions);
};
var tempStyles = {};
/**
* The migrate process handler constructor.
*
* @class
* @param {Item} item
*/
function ItemMigrate(item) {
// Private props.
this._item = item;
this._isActive = false;
this._isDestroyed = false;
this._container = false;
this._containerDiffX = 0;
this._containerDiffY = 0;
}
/**
* Public prototype methods
* ************************
*/
/**
* Start the migrate process of an item.
*
* @public
* @memberof ItemMigrate.prototype
* @param {Grid} targetGrid
* @param {GridSingleItemQuery} position
* @param {HTMLElement} [container]
* @returns {ItemMigrate}
*/
ItemMigrate.prototype.start = function(targetGrid, position, container) {
if (this._isDestroyed) return this;
var item = this._item;
var element = item._element;
var isVisible = item.isVisible();
var grid = item.getGrid();
var settings = grid._settings;
var targetSettings = targetGrid._settings;
var targetElement = targetGrid._element;
var targetItems = targetGrid._items;
var currentIndex = grid._items.indexOf(item);
var targetContainer = container || document.body;
var targetIndex;
var targetItem;
var currentContainer;
var offsetDiff;
var containerDiff;
var translate;
var translateX;
var translateY;
// Get target index.
if (typeof position === 'number') {
targetIndex = normalizeArrayIndex(targetItems, position, true);
} else {
targetItem = targetGrid._getItem(position);
/** @todo Consider throwing an error here instead of silently failing. */
if (!targetItem) return this;
targetIndex = targetItems.indexOf(targetItem);
}
// Get current translateX and translateY values if needed.
if (item.isPositioning() || this._isActive || item.isReleasing()) {
translate = getTranslate(element);
translateX = translate.x;
translateY = translate.y;
}
// Abort current positioning.
if (item.isPositioning()) {
item._layout.stop(true, { transform: getTranslateString(translateX, translateY) });
}
// Abort current migration.
if (this._isActive) {
translateX -= this._containerDiffX;
translateY -= this._containerDiffY;
this.stop(true, { transform: getTranslateString(translateX, translateY) });
}
// Abort current release.
if (item.isReleasing()) {
translateX -= item._release._containerDiffX;
translateY -= item._release._containerDiffY;
item._release.stop(true, { transform: getTranslateString(translateX, translateY) });
}
// Stop current visibility animations.
item._visibility._stopAnimation();
// Destroy current drag.
if (item._drag) item._drag.destroy();
// Process current visibility animation queue.
item._visibility._queue.flush(true, item);
// Emit beforeSend event.
if (grid._hasListeners(eventBeforeSend)) {
grid._emit(eventBeforeSend, {
item: item,
fromGrid: grid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Emit beforeReceive event.
if (targetGrid._hasListeners(eventBeforeReceive)) {
targetGrid._emit(eventBeforeReceive, {
item: item,
fromGrid: grid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Remove current classnames.
removeClass(element, settings.itemClass);
removeClass(element, settings.itemVisibleClass);
removeClass(element, settings.itemHiddenClass);
// Add new classnames.
addClass(element, targetSettings.itemClass);
addClass(element, isVisible ? targetSettings.itemVisibleClass : targetSettings.itemHiddenClass);
// Move item instance from current grid to target grid.
grid._items.splice(currentIndex, 1);
arrayInsert(targetItems, item, targetIndex);
// Update item's grid id reference.
item._gridId = targetGrid._id;
// Get current container.
currentContainer = element.parentNode;
// Move the item inside the target container if it's different than the
// current container.
if (targetContainer !== currentContainer) {
targetContainer.appendChild(element);
offsetDiff = getOffsetDiff(targetContainer, currentContainer, true);
if (!translate) {
translate = getTranslate(element);
translateX = translate.x;
translateY = translate.y;
}
element.style[transformProp] = getTranslateString(
translateX + offsetDiff.left,
translateY + offsetDiff.top
);
}
// Update child element's styles to reflect the current visibility state.
item._child.removeAttribute('style');
setStyles(item._child, isVisible ? targetSettings.visibleStyles : targetSettings.hiddenStyles);
// Update display style.
element.style.display = isVisible ? 'block' : 'hidden';
// Get offset diff for the migration data.
containerDiff = getOffsetDiff(targetContainer, targetElement, true);
// Update item's cached dimensions and sort data.
item._refreshDimensions();
item._refreshSortData();
// Create new drag handler.
item._drag = targetSettings.dragEnabled ? new ItemDrag(item) : null;
// Setup migration data.
this._isActive = true;
this._container = targetContainer;
this._containerDiffX = containerDiff.left;
this._containerDiffY = containerDiff.top;
// Emit send event.
if (grid._hasListeners(eventSend)) {
grid._emit(eventSend, {
item: item,
fromGrid: grid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
// Emit receive event.
if (targetGrid._hasListeners(eventReceive)) {
targetGrid._emit(eventReceive, {
item: item,
fromGrid: grid,
fromIndex: currentIndex,
toGrid: targetGrid,
toIndex: targetIndex
});
}
return this;
};
/**
* End the migrate process of an item. This method can be used to abort an
* ongoing migrate process (animation) or finish the migrate process.
*
* @public
* @memberof ItemMigrate.prototype
* @param {Boolean} [abort=false]
* - Should the migration be aborted?
* @param {Object} [currentStyles]
* - Optional current translateX and translateY styles.
* @returns {ItemMigrate}
*/
ItemMigrate.prototype.stop = function(abort, currentStyles) {
if (this._isDestroyed || !this._isActive) return this;
var item = this._item;
var element = item._element;
var grid = item.getGrid();
var gridElement = grid._element;
var translate;
if (this._container !== gridElement) {
if (!currentStyles) {
if (abort) {
translate = getTranslate(element);
tempStyles.transform = getTranslateString(
translate.x - this._containerDiffX,
translate.y - this._containerDiffY
);
} else {
tempStyles.transform = getTranslateString(item._left, item._top);
}
currentStyles = tempStyles;
}
gridElement.appendChild(element);
setStyles(element, currentStyles);
}
this._isActive = false;
this._container = null;
this._containerDiffX = 0;
this._containerDiffY = 0;
return this;
};
/**
* Destroy instance.
*
* @public
* @memberof ItemMigrate.prototype
* @returns {ItemMigrate}
*/
ItemMigrate.prototype.destroy = function() {
if (this._isDestroyed) return this;
this.stop(true);
this._item = null;
this._isDestroyed = true;
return this;
};
var tempStyles$1 = {};
/**
* The release process handler constructor. Although this might seem as proper
* fit for the drag process this needs to be separated into it's own logic
* because there might be a scenario where drag is disabled, but the release
* process still needs to be implemented (dragging from a grid to another).
*
* @class
* @param {Item} item
*/
function ItemRelease(item) {
this._item = item;
this._isActive = false;
this._isDestroyed = false;
this._isPositioningStarted = false;
this._containerDiffX = 0;
this._containerDiffY = 0;
}
/**
* Public prototype methods
* ************************
*/
/**
* Start the release process of an item.
*
* @public
* @memberof ItemRelease.prototype
* @returns {ItemRelease}
*/
ItemRelease.prototype.start = function() {
if (this._isDestroyed || this._isActive) return this;
var item = this._item;
var grid = item.getGrid();
// Flag release as active.
this._isActive = true;
// Add release class name to the released element.
addClass(item._element, grid._settings.itemReleasingClass);
// Emit dragReleaseStart event.
grid._emit(eventDragReleaseStart, item);
// Position the released item.
item._layout.start(false);
return this;
};
/**
* End the release process of an item. This method can be used to abort an
* ongoing release process (animation) or finish the release process.
*
* @public
* @memberof ItemRelease.prototype
* @param {Boolean} [abort=false]
* - Should the release be aborted? When true, the release end event won't be
* emitted. Set to true only when you need to abort the release process
* while the item is animating to it's position.
* @param {Object} [currentStyles]
* - Optional current translateX and translateY styles.
* @returns {ItemRelease}
*/
ItemRelease.prototype.stop = function(abort, currentStyles) {
if (this._isDestroyed || !this._isActive) return this;
var item = this._item;
var element = item._element;
var grid = item.getGrid();
var container = grid._element;
var translate;
// Reset data and remove releasing class name from the element.
this._reset();
// If the released element is outside the grid's container element put it
// back there and adjust position accordingly.
if (element.parentNode !== container) {
if (!currentStyles) {
if (abort) {
translate = getTranslate(element);
tempStyles$1.transform = getTranslateString(
translate.x - this._containerDiffX,
translate.y - this._containerDiffY
);
} else {
tempStyles$1.transform = getTranslateString(item._left, item._top);
}
currentStyles = tempStyles$1;
}
container.appendChild(element);
setStyles(element, currentStyles);
}
// Emit dragReleaseEnd event.
if (!abort) grid._emit(eventDragReleaseEnd, item);
return this;
};
/**
* Destroy instance.
*
* @public
* @memberof ItemRelease.prototype
* @returns {ItemRelease}
*/
ItemRelease.prototype.destroy = function() {
if (this._isDestroyed) return this;
this.stop(true);
this._item = null;
this._isDestroyed = true;
return this;
};
/**
* Private prototype methods
* *************************
*/
/**
* Reset public data and remove releasing class.
*
* @private
* @memberof ItemRelease.prototype
*/
ItemRelease.prototype._reset = function() {
if (this._isDestroyed) return;
var item = this._item;
this._isActive = false;
this._isPositioningStarted = false;
this._containerDiffX = 0;
this._containerDiffY = 0;
removeClass(item._element, item.getGrid()._settings.itemReleasingClass);
};
/**
* Visibility manager for Item instance.
*
* @class
* @param {Item} item
*/
function ItemVisibility(item) {
var isActive = item._isActive;
var element = item._element;
var settings = item.getGrid()._settings;
this._item = item;
this._isDestroyed = false;
// Set up visibility states.
this._isHidden = !isActive;
this._isHiding = false;
this._isShowing = false;
// Callback queue.
this._queue = new Queue();
// Bind show/hide finishers.
this._finishShow = this._finishShow.bind(this);
this._finishHide = this._finishHide.bind(this);
// Force item to be either visible or hidden on init.
element.style.display = isActive ? 'block' : 'none';
// Set visible/hidden class.
addClass(element, isActive ? settings.itemVisibleClass : settings.itemHiddenClass);
// Set initial styles for the child element.
setStyles(item._child, isActive ? settings.visibleStyles : settings.hiddenStyles);
}
/**
* Public prototype methods
* ************************
*/
/**
* Show item.
*
* @public
* @memberof ItemVisibility.prototype
* @param {Boolean} instant
* @param {Function} [onFinish]
* @returns {ItemVisibility}
*/
ItemVisibility.prototype.show = function(instant, onFinish) {
if (this._isDestroyed) return this;
var item = this._item;
var element = item._element;
var queue = this._queue;
var callback = typeof onFinish === 'function' ? onFinish : null;
var grid = item.getGrid();
var settings = grid._settings;
// If item is visible call the callback and be done with it.
if (!this._isShowing && !this._isHidden) {
callback && callback(false, item);
return this;
}
// If item is showing and does not need to be shown instantly, let's just
// push callback to the callback queue and be done with it.
if (this._isShowing && !instant) {
callback && queue.add(callback);
return this;
}
// If the item is hiding or hidden process the current visibility callback
// queue with the interrupted flag active, update classes and set display
// to block if necessary.
if (!this._isShowing) {
queue.flush(true, item);
removeClass(element, settings.itemHiddenClass);
addClass(element, settings.itemVisibleClass);
if (!this._isHiding) element.style.display = 'block';
}
// Push callback to the callback queue.
callback && queue.add(callback);
// Update visibility states.
item._isActive = this._isShowing = true;
this._isHiding = this._isHidden = false;
// Finally let's start show animation.
this._startAnimation(true, instant, this._finishShow);
return this;
};
/**
* Hide item.
*
* @public
* @memberof ItemVisibility.prototype
* @param {Boolean} instant
* @param {Function} [onFinish]
* @returns {ItemVisibility}
*/
ItemVisibility.prototype.hide = function(instant, onFinish) {
if (this._isDestroyed) return this;
var item = this._item;
var element = item._element;
var queue = this._queue;
var callback = typeof onFinish === 'function' ? onFinish : null;
var grid = item.getGrid();
var settings = grid._settings;
// If item is already hidden call the callback and be done with it.
if (!this._isHiding && this._isHidden) {
callback && callback(false, item);
return this;
}
// If item is hiding and does not need to be hidden instantly, let's just
// push callback to the callback queue and be done with it.
if (this._isHiding && !instant) {
callback && queue.add(callback);
return this;
}
// If the item is showing or visible process the current visibility callback
// queue with the interrupted flag active, update classes and set display
// to block if necessary.
if (!this._isHiding) {
queue.flush(true, item);
addClass(element, settings.itemHiddenClass);
removeClass(element, settings.itemVisibleClass);
}
// Push callback to the callback queue.
callback && queue.add(callback);
// Update visibility states.
this._isHidden = this._isHiding = true;
item._isActive = this._isShowing = false;
// Finally let's start hide animation.
this._startAnimation(false, instant, this._finishHide);
return this;
};
/**
* Destroy the instance and stop current animation if it is running.
*
* @public
* @memberof ItemVisibility.prototype
* @returns {ItemVisibility}
*/
ItemVisibility.prototype.destroy = function() {
if (this._isDestroyed) return this;
var item = this._item;
var element = item._element;
var grid = item.getGrid();
var queue = this._queue;
var settings = grid._settings;
// Stop visibility animation.
this._stopAnimation({});
// Fire all uncompleted callbacks with interrupted flag and destroy the queue.
queue.flush(true, item).destroy();
// Remove visible/hidden classes.
removeClass(element, settings.itemVisibleClass);
removeClass(element, settings.itemHiddenClass);
// Reset state.
this._item = null;
this._isHiding = this._isShowing = false;
this._isDestroyed = this._isHidden = true;
return this;
};
/**
* Private prototype methods
* *************************
*/
/**
* Start visibility animation.
*
* @private
* @memberof ItemVisibility.prototype
* @param {Boolean} toVisible
* @param {Boolean} [instant]
* @param {Function} [onFinish]
*/
ItemVisibility.prototype._startAnimation = function(toVisible, instant, onFinish) {
if (this._isDestroyed) return;
var item = this._item;
var settings = item.getGrid()._settings;
var targetStyles = toVisible ? settings.visibleStyles : settings.hiddenStyles;
var duration = parseInt(toVisible ? settings.showDuration : settings.hideDuration) || 0;
var easing = (toVisible ? settings.showEasing : settings.hideEasing) || 'ease';
var isInstant = instant || duration <= 0;
var currentStyles;
// No target styles? Let's quit early.
if (!targetStyles) {
onFinish && onFinish();
return;
}
// Let's reset item's visibility ticker.
ticker.cancel(item._id + 'visibility');
// If we need to apply the styles instantly without animation.
if (isInstant) {
if (item._animateChild.isAnimating()) {
item._animateChild.stop(targetStyles);
} else {
setStyles(item._child, targetStyles);
}
onFinish && onFinish();
return;
}
// Animate.
ticker.add(
item._id + 'visibility',
function() {
currentStyles = getCurrentStyles(item._child, targetStyles);
},
function() {
item._animateChild.start(currentStyles, targetStyles, {
duration: duration,
easing: easing,
onFinish: onFinish
});
}
);
};
/**
* Stop visibility animation.
*
* @private
* @memberof ItemVisibility.prototype
* @param {Object} [targetStyles]
*/
ItemVisibility.prototype._stopAnimation = function(targetStyles) {
if (this._isDestroyed) return;
var item = this._item;
ticker.cancel(item._id);
item._animateChild.stop(targetStyles);
};
/**
* Finish show procedure.
*
* @private
* @memberof ItemVisibility.prototype
*/
ItemVisibility.prototype._finishShow = function() {
if (this._isHidden) return;
this._isShowing = false;
this._queue.flush(false, this._item);
};
/**
* Finish hide procedure.
*
* @private
* @memberof ItemVisibility.prototype
*/
var finishStyles = {};
ItemVisibility.prototype._finishHide = function() {
if (!this._isHidden) return;
var item = this._item;
this._isHiding = false;
finishStyles.transform = getTranslateString(0, 0);
item._layout.stop(true, finishStyles);
item._element.style.display = 'none';
this._queue.flush(false, item);
};
var id = 0;
/**
* Returns a unique numeric id (increments a base value on every call).
* @returns {Number}
*/
function createUid() {
return ++id;
}
/**
* Creates a new Item instance for a Grid instance.
*
* @class
* @param {Grid} grid
* @param {HTMLElement} element
* @param {Boolean} [isActive]
*/
function Item(grid, element, isActive) {
var settings = grid._settings;
// Create instance id.
this._id = createUid();
// Reference to connected Grid instance's id.
this._gridId = grid._id;
// Destroyed flag.
this._isDestroyed = false;
// Set up initial positions.
this._left = 0;
this._top = 0;
// The elements.
this._element = element;
this._child = element.children[0];
// If the provided item element is not a direct child of the grid container
// element, append it to the grid container.
if (element.parentNode !== grid._element) {
grid._element.appendChild(element);
}
// Set item class.
addClass(element, settings.itemClass);
// If isActive is not defined, let's try to auto-detect it.
if (typeof isActive !== 'boolean') {
isActive = getStyle(element, 'display') !== 'none';
}
// Set up active state (defines if the item is considered part of the layout
// or not).
this._isActive = isActive;
// Set element's initial position styles.
element.style.left = '0';
element.style.top = '0';
element.style[transformProp] = getTranslateString(0, 0);
// Initiate item's animation controllers.
this._animate = new ItemAnimate(this, element);
this._animateChild = new ItemAnimate(this, this._child);
// Setup visibility handler.
this._visibility = new ItemVisibility(this);
// Set up layout handler.
this._layout = new ItemLayout(this);
// Set up migration handler data.
this._migrate = new ItemMigrate(this);
// Set up release handler
this._release = new ItemRelease(this);
// Set up drag handler.
this._drag = settings.dragEnabled ? new ItemDrag(this) : null;
// Set up the initial dimensions and sort data.
this._refreshDimensions();
this._refreshSortData();
}
/**
* Public prototype methods
* ************************
*/
/**
* Get the instance grid reference.
*
* @public
* @memberof Item.prototype
* @returns {Grid}
*/
Item.prototype.getGrid = function() {
return gridInstances[this._gridId];
};
/**
* Get the instance element.
*
* @public
* @memberof Item.prototype
* @returns {HTMLElement}
*/
Item.prototype.getElement = function() {
return this._element;
};
/**
* Get instance element's cached width.
*
* @public
* @memberof Item.prototype
* @returns {Number}
*/
Item.prototype.getWidth = function() {
return this._width;
};
/**
* Get instance element's cached height.
*
* @public
* @memberof Item.prototype
* @returns {Number}
*/
Item.prototype.getHeight = function() {
return this._height;
};
/**
* Get instance element's cached margins.
*
* @public
* @memberof Item.prototype
* @returns {Object}
* - The returned object contains left, right, top and bottom properties
* which indicate the item element's cached margins.
*/
Item.prototype.getMargin = function() {
return {
left: this._marginLeft,
right: this._marginRight,
top: this._marginTop,
bottom: this._marginBottom
};
};
/**
* Get instance element's cached position.
*
* @public
* @memberof Item.prototype
* @returns {Object}
* - The returned object contains left and top properties which indicate the
* item element's cached position in the grid.
*/
Item.prototype.getPosition = function() {
return {
left: this._left,
top: this._top
};
};
/**
* Is the item active?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isActive = function() {
return this._isActive;
};
/**
* Is the item visible?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isVisible = function() {
return !!this._visibility && !this._visibility._isHidden;
};
/**
* Is the item being animated to visible?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isShowing = function() {
return !!(this._visibility && this._visibility._isShowing);
};
/**
* Is the item being animated to hidden?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isHiding = function() {
return !!(this._visibility && this._visibility._isHiding);
};
/**
* Is the item positioning?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isPositioning = function() {
return !!(this._layout && this._layout._isActive);
};
/**
* Is the item being dragged?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isDragging = function() {
return !!(this._drag && this._drag._isActive);
};
/**
* Is the item being released?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isReleasing = function() {
return !!(this._release && this._release._isActive);
};
/**
* Is the item destroyed?
*
* @public
* @memberof Item.prototype
* @returns {Boolean}
*/
Item.prototype.isDestroyed = function() {
return this._isDestroyed;
};
/**
* Private prototype methods
* *************************
*/
/**
* Recalculate item's dimensions.
*
* @private
* @memberof Item.prototype
*/
Item.prototype._refreshDimensions = function() {
if (this._isDestroyed || this._visibility._isHidden) return;
var element = this._element;
var rect = element.getBoundingClientRect();
// Calculate width and height.
this._width = rect.width;
this._height = rect.height;
// Calculate margins (ignore negative margins).
this._marginLeft = Math.max(0, getStyleAsFloat(element, 'margin-left'));
this._marginRight = Math.max(0, getStyleAsFloat(element, 'margin-right'));
this._marginTop = Math.max(0, getStyleAsFloat(element, 'margin-top'));
this._marginBottom = Math.max(0, getStyleAsFloat(element, 'margin-bottom'));
};
/**
* Fetch and store item's sort data.
*
* @private
* @memberof Item.prototype
*/
Item.prototype._refreshSortData = function() {
if (this._isDestroyed) return;
var data = (this._sortData = {});
var getters = this.getGrid()._settings.sortData;
var prop;
for (prop in getters) {
data[prop] = getters[prop](this, this._element);
}
};
/**
* Destroy item instance.
*
* @private
* @memberof Item.prototype
* @param {Boolean} [removeElement=false]
*/
Item.prototype._destroy = function(removeElement) {
if (this._isDestroyed) return;
var element = this._element;
var grid = this.getGrid();
var settings = grid._settings;
var index = grid._items.indexOf(this);
// Destroy handlers.
this._release.destroy();
this._migrate.destroy();
this._layout.destroy();
this._visibility.destroy();
this._animate.destroy();
this._animateChild.destroy();
this._drag && this._drag.destroy();
// Remove all inline styles.
element.removeAttribute('style');
this._child.removeAttribute('style');
// Remove item class.
removeClass(element, settings.itemClass);
// Remove item from Grid instance if it still exists there.
index > -1 && grid._items.splice(index, 1);
// Remove element from DOM.
removeElement && element.parentNode.removeChild(element);
// Reset state.
this._isActive = false;
this._isDestroyed = true;
};
/**
* This is the default layout algorithm for Muuri. Based on MAXRECTS approach
* as described by Jukka Jylänki in his survey: "A Thousand Ways to Pack the
* Bin - A Practical Approach to Two-Dimensional Rectangle Bin Packing.".
*
* @class
*/
function Packer() {
this._layout = {
slots: [],
slotSizes: [],
setWidth: false,
setHeight: false,
width: false,
height: false
};
this._freeSlots = [];
this._newSlots = [];
this._rectItem = {};
this._rectStore = [];
this._rectId = 0;
// Bind sort handlers.
this._sortRectsLeftTop = this._sortRectsLeftTop.bind(this);
this._sortRectsTopLeft = this._sortRectsTopLeft.bind(this);
}
/**
* @public
* @memberof Packer.prototype
* @param {Item[]} items
* @param {Number} width
* @param {Number} height
* @param {Object} [options]
* @param {Boolean} [options.fillGaps=false]
* @param {Boolean} [options.horizontal=false]
* @param {Boolean} [options.alignRight=false]
* @param {Boolean} [options.alignBottom=false]
* @returns {LayoutData}
*/
Packer.prototype.getLayout = function(items, width, height, options) {
var layout = this._layout;
var fillGaps = !!(options && options.fillGaps);
var isHorizontal = !!(options && options.horizontal);
var alignRight = !!(options && options.alignRight);
var alignBottom = !!(options && options.alignBottom);
var rounding = !!(options && options.rounding);
var i;
// Reset layout data.
layout.slots.length = layout.slotSizes.length = 0;
layout.width = isHorizontal ? 0 : rounding ? Math.round(width) : width;
layout.height = !isHorizontal ? 0 : rounding ? Math.round(height) : height;
layout.setWidth = isHorizontal;
layout.setHeight = !isHorizontal;
// No need to go further if items do not exist.
if (!items.length) return layout;
// Find slots for items.
for (i = 0; i < items.length; i++) {
this._addSlot(items[i], isHorizontal, fillGaps, rounding);
}
// If the alignment is set to right we need to adjust the results.
if (alignRight) {
for (i = 0; i < layout.slots.length; i = i + 2) {
layout.slots[i] = layout.width - (layout.slots[i] + layout.slotSizes[i]);
}
}
// If the alignment is set to bottom we need to adjust the results.
if (alignBottom) {
for (i = 1; i < layout.slots.length; i = i + 2) {
layout.slots[i] = layout.height - (layout.slots[i] + layout.slotSizes[i]);
}
}
// Reset slots arrays and rect id.
this._freeSlots.length = 0;
this._newSlots.length = 0;
this._rectId = 0;
return layout;
};
/**
* Calculate position for the layout item. Returns the left and top position
* of the item in pixels.
*
* @private
* @memberof Packer.prototype
* @param {Item} item
* @param {Boolean} isHorizontal
* @param {Boolean} fillGaps
* @param {Boolean} rounding
* @returns {Array}
*/
Packer.prototype._addSlot = (function() {
var leeway = 0.001;
var itemSlot = {};
return function(item, isHorizontal, fillGaps, rounding) {
var layout = this._layout;
var freeSlots = this._freeSlots;
var newSlots = this._newSlots;
var rect;
var rectId;
var potentialSlots;
var ignoreCurrentSlots;
var i;
var ii;
// Reset new slots.
newSlots.length = 0;
// Set item slot initial data.
itemSlot.left = null;
itemSlot.top = null;
itemSlot.width = item._width + item._marginLeft + item._marginRight;
itemSlot.height = item._height + item._marginTop + item._marginBottom;
// Round item slot width and height if needed.
if (rounding) {
itemSlot.width = Math.round(itemSlot.width);
itemSlot.height = Math.round(itemSlot.height);
}
// Try to find a slot for the item.
for (i = 0; i < freeSlots.length; i++) {
rectId = freeSlots[i];
if (!rectId) continue;
rect = this._getRect(rectId);
if (itemSlot.width <= rect.width + leeway && itemSlot.height <= rect.height + leeway) {
itemSlot.left = rect.left;
itemSlot.top = rect.top;
break;
}
}
// If no slot was found for the item.
if (itemSlot.left === null) {
// Position the item in to the bottom left (vertical mode) or top right
// (horizontal mode) of the grid.
itemSlot.left = !isHorizontal ? 0 : layout.width;
itemSlot.top = !isHorizontal ? layout.height : 0;
// If gaps don't needs filling do not add any current slots to the new
// slots array.
if (!fillGaps) {
ignoreCurrentSlots = true;
}
}
// In vertical mode, if the item's bottom overlaps the grid's bottom.
if (!isHorizontal && itemSlot.top + itemSlot.height > layout.height) {
// If item is not aligned to the left edge, create a new slot.
if (itemSlot.left > 0) {
newSlots.push(this._addRect(0, layout.height, itemSlot.left, Infinity));
}
// If item is not aligned to the right edge, create a new slot.
if (itemSlot.left + itemSlot.width < layout.width) {
newSlots.push(
this._addRect(
itemSlot.left + itemSlot.width,
layout.height,
layout.width - itemSlot.left - itemSlot.width,
Infinity
)
);
}
// Update grid height.
layout.height = itemSlot.top + itemSlot.height;
}
// In horizontal mode, if the item's right overlaps the grid's right edge.
if (isHorizontal && itemSlot.left + itemSlot.width > layout.width) {
// If item is not aligned to the top, create a new slot.
if (itemSlot.top > 0) {
newSlots.push(this._addRect(layout.width, 0, Infinity, itemSlot.top));
}
// If item is not aligned to the bottom, create a new slot.
if (itemSlot.top + itemSlot.height < layout.height) {
newSlots.push(
this._addRect(
layout.width,
itemSlot.top + itemSlot.height,
Infinity,
layout.height - itemSlot.top - itemSlot.height
)
);
}
// Update grid width.
layout.width = itemSlot.left + itemSlot.width;
}
// Clean up the current slots making sure there are no old slots that
// overlap with the item. If an old slot overlaps with the item, split it
// into smaller slots if necessary.
for (i = fillGaps ? 0 : ignoreCurrentSlots ? freeSlots.length : i; i < freeSlots.length; i++) {
rectId = freeSlots[i];
if (!rectId) continue;
rect = this._getRect(rectId);
potentialSlots = this._splitRect(rect, itemSlot);
for (ii = 0; ii < potentialSlots.length; ii++) {
rectId = potentialSlots[ii];
rect = this._getRect(rectId);
// Let's make sure here that we have a big enough slot
// (width/height > 0.49px) and also let's make sure that the slot is
// within the boundaries of the grid.
if (
rect.width > 0.49 &&
rect.height > 0.49 &&
((!isHorizontal && rect.top < layout.height) ||
(isHorizontal && rect.left < layout.width))
) {
newSlots.push(rectId);
}
}
}
// Sanitize new slots.
if (newSlots.length) {
this._purgeRects(newSlots).sort(
isHorizontal ? this._sortRectsLeftTop : this._sortRectsTopLeft
);
}
// Update layout width/height.
if (isHorizontal) {
layout.width = Math.max(layout.width, itemSlot.left + itemSlot.width);
} else {
layout.height = Math.max(layout.height, itemSlot.top + itemSlot.height);
}
// Add item slot data to layout slots (and store the slot size for later
// usage too).
layout.slots.push(itemSlot.left, itemSlot.top);
layout.slotSizes.push(itemSlot.width, itemSlot.height);
// Free/new slots switcheroo!
this._freeSlots = newSlots;
this._newSlots = freeSlots;
};
})();
/**
* Add a new rectangle to the rectangle store. Returns the id of the new
* rectangle.
*
* @private
* @memberof Packer.prototype
* @param {Number} left
* @param {Number} top
* @param {Number} width
* @param {Number} height
* @returns {RectId}
*/
Packer.prototype._addRect = function(left, top, width, height) {
var rectId = ++this._rectId;
var rectStore = this._rectStore;
rectStore[rectId] = left || 0;
rectStore[++this._rectId] = top || 0;
rectStore[++this._rectId] = width || 0;
rectStore[++this._rectId] = height || 0;
return rectId;
};
/**
* Get rectangle data from the rectangle store by id. Optionally you can
* provide a target object where the rectangle data will be written in. By
* default an internal object is reused as a target object.
*
* @private
* @memberof Packer.prototype
* @param {RectId} id
* @param {Object} [target]
* @returns {Object}
*/
Packer.prototype._getRect = function(id, target) {
var rectItem = target ? target : this._rectItem;
var rectStore = this._rectStore;
rectItem.left = rectStore[id] || 0;
rectItem.top = rectStore[++id] || 0;
rectItem.width = rectStore[++id] || 0;
rectItem.height = rectStore[++id] || 0;
return rectItem;
};
/**
* Punch a hole into a rectangle and split the remaining area into smaller
* rectangles (4 at max).
*
* @private
* @memberof Packer.prototype
* @param {Rectangle} rect
* @param {Rectangle} hole
* @returns {RectId[]}
*/
Packer.prototype._splitRect = (function() {
var results = [];
return function(rect, hole) {
// Reset old results.
results.length = 0;
// If the rect does not overlap with the hole add rect to the return data
// as is.
if (!this._doRectsOverlap(rect, hole)) {
results.push(this._addRect(rect.left, rect.top, rect.width, rect.height));
return results;
}
// Left split.
if (rect.left < hole.left) {
results.push(this._addRect(rect.left, rect.top, hole.left - rect.left, rect.height));
}
// Right split.
if (rect.left + rect.width > hole.left + hole.width) {
results.push(
this._addRect(
hole.left + hole.width,
rect.top,
rect.left + rect.width - (hole.left + hole.width),
rect.height
)
);
}
// Top split.
if (rect.top < hole.top) {
results.push(this._addRect(rect.left, rect.top, rect.width, hole.top - rect.top));
}
// Bottom split.
if (rect.top + rect.height > hole.top + hole.height) {
results.push(
this._addRect(
rect.left,
hole.top + hole.height,
rect.width,
rect.top + rect.height - (hole.top + hole.height)
)
);
}
return results;
};
})();
/**
* Check if two rectangles overlap.
*
* @private
* @memberof Packer.prototype
* @param {Rectangle} a
* @param {Rectangle} b
* @returns {Boolean}
*/
Packer.prototype._doRectsOverlap = function(a, b) {
return !(
a.left + a.width <= b.left ||
b.left + b.width <= a.left ||
a.top + a.height <= b.top ||
b.top + b.height <= a.top
);
};
/**
* Check if a rectangle is fully within another rectangle.
*
* @private
* @memberof Packer.prototype
* @param {Rectangle} a
* @param {Rectangle} b
* @returns {Boolean}
*/
Packer.prototype._isRectWithinRect = function(a, b) {
return (
a.left >= b.left &&
a.top >= b.top &&
a.left + a.width <= b.left + b.width &&
a.top + a.height <= b.top + b.height
);
};
/**
* Loops through an array of rectangle ids and resets all that are fully
* within another rectangle in the array. Resetting in this case means that
* the rectangle id value is replaced with zero.
*
* @private
* @memberof Packer.prototype
* @param {RectId[]} rectIds
* @returns {RectId[]}
*/
Packer.prototype._purgeRects = (function() {
var rectA = {};
var rectB = {};
return function(rectIds) {
var i = rectIds.length;
var ii;
while (i--) {
ii = rectIds.length;
if (!rectIds[i]) continue;
this._getRect(rectIds[i], rectA);
while (ii--) {
if (!rectIds[ii] || i === ii) continue;
if (this._isRectWithinRect(rectA, this._getRect(rectIds[ii], rectB))) {
rectIds[i] = 0;
break;
}
}
}
return rectIds;
};
})();
/**
* Sort rectangles with top-left gravity.
*
* @private
* @memberof Packer.prototype
* @param {RectId} aId
* @param {RectId} bId
* @returns {Number}
*/
Packer.prototype._sortRectsTopLeft = (function() {
var rectA = {};
var rectB = {};
return function(aId, bId) {
this._getRect(aId, rectA);
this._getRect(bId, rectB);
// prettier-ignore
return rectA.top < rectB.top ? -1 :
rectA.top > rectB.top ? 1 :
rectA.left < rectB.left ? -1 :
rectA.left > rectB.left ? 1 : 0;
};
})();
/**
* Sort rectangles with left-top gravity.
*
* @private
* @memberof Packer.prototype
* @param {RectId} aId
* @param {RectId} bId
* @returns {Number}
*/
Packer.prototype._sortRectsLeftTop = (function() {
var rectA = {};
var rectB = {};
return function(aId, bId) {
this._getRect(aId, rectA);
this._getRect(bId, rectB);
// prettier-ignore
return rectA.left < rectB.left ? -1 :
rectA.left > rectB.left ? 1 :
rectA.top < rectB.top ? -1 :
rectA.top > rectB.top ? 1 : 0;
};
})();
var htmlCollectionType = '[object HTMLCollection]';
var nodeListType = '[object NodeList]';
/**
* Check if a value is a node list
*
* @param {*} val
* @returns {Boolean}
*/
function isNodeList(val) {
var type = Object.prototype.toString.call(val);
return type === htmlCollectionType || type === nodeListType;
}
/**
* Converts a value to an array or clones an array.
*
* @param {*} target
* @returns {Array}
*/
function toArray(target) {
return isNodeList(target) ? Array.prototype.slice.call(target) : Array.prototype.concat(target);
}
var packer = new Packer();
var noop = function() {};
/**
* Creates a new Grid instance.
*
* @class
* @param {(HTMLElement|String)} element
* @param {Object} [options]
* @param {(?HTMLElement[]|NodeList|String)} [options.items]
* @param {Number} [options.showDuration=300]
* @param {String} [options.showEasing="ease"]
* @param {Object} [options.visibleStyles]
* @param {Number} [options.hideDuration=300]
* @param {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} [options.layout.rounding=true]
* @param {(Boolean|Number)} [options.layoutOnResize=100]
* @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 {?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 {?String} [options.dragAxis]
* @param {(Boolean|Function)} [options.dragSort=true]
* @param {Number} [options.dragSortInterval=100]
* @param {(Function|Object)} [options.dragSortPredicate]
* @param {Number} [options.dragSortPredicate.threshold=50]
* @param {String} [options.dragSortPredicate.action="move"]
* @param {Number} [options.dragReleaseDuration=300]
* @param {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 layoutOnResize;
// Allow passing element as selector string. Store element for instance.
element = this._element = typeof element === 'string' ? document.querySelector(element) : 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 = this._settings = mergeSettings(Grid.defaultOptions, options);
// Sanitize dragSort setting.
if (typeof settings.dragSort !== 'function') {
settings.dragSort = !!settings.dragSort;
}
// Create instance id and store it to the grid instances collection.
this._id = createUid();
gridInstances[this._id] = inst;
// Destroyed flag.
this._isDestroyed = false;
// The layout object (mutated on every layout).
this._layout = {
id: 0,
items: [],
slots: [],
setWidth: false,
setHeight: false,
width: 0,
height: 0
};
// Create private Emitter instance.
this._emitter = new Emitter();
// Add container element's class name.
addClass(element, settings.containerClass);
// Create initial items.
this._items = [];
items = settings.items;
if (typeof items === 'string') {
toArray(element.children).forEach(function(itemElement) {
if (items === '*' || elementMatches(itemElement, items)) {
inst._items.push(new Item(inst, itemElement));
}
});
} else if (Array.isArray(items) || isNodeList(items)) {
this._items = toArray(items).map(function(itemElement) {
return new Item(inst, itemElement);
});
}
// If layoutOnResize option is a valid number sanitize it and bind the resize
// handler.
layoutOnResize = settings.layoutOnResize;
if (typeof layoutOnResize !== 'number') {
layoutOnResize = layoutOnResize === true ? 0 : -1;
}
if (layoutOnResize >= 0) {
window.addEventListener(
'resize',
(inst._resizeHandler = debounce(function() {
inst.refreshItems().layout();
}, layoutOnResize))
);
}
// Layout on init if necessary.
if (settings.layoutOnInit) {
this.layout(true);
}
}
/**
* Public properties
* *****************
*/
/**
* @see Item
*/
Grid.Item = Item;
/**
* @see ItemLayout
*/
Grid.ItemLayout = ItemLayout;
/**
* @see ItemVisibility
*/
Grid.ItemVisibility = ItemVisibility;
/**
* @see ItemRelease
*/
Grid.ItemRelease = ItemRelease;
/**
* @see ItemMigrate
*/
Grid.ItemMigrate = ItemMigrate;
/**
* @see ItemAnimate
*/
Grid.ItemAnimate = ItemAnimate;
/**
* @see ItemDrag
*/
Grid.ItemDrag = ItemDrag;
/**
* @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',
// 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: true
},
layoutOnResize: 100,
layoutOnInit: true,
layoutDuration: 300,
layoutEasing: 'ease',
// Sorting
sortData: null,
// Drag & Drop
dragEnabled: false,
dragContainer: null,
dragStartPredicate: {
distance: 0,
delay: 0,
handle: false
},
dragAxis: null,
dragSort: true,
dragSortInterval: 100,
dragSortPredicate: {
threshold: 50,
action: 'move'
},
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'
};
/**
* 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) {
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) {
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) {
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). 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]
* @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 && targets !== 0)) {
return this._items.slice(0);
}
var ret = [];
var targetItems = toArray(targets);
var item;
var i;
// If target items are defined return filtered results.
for (i = 0; i < targetItems.length; i++) {
item = this._getItem(targetItems[i]);
item && ret.push(item);
}
return ret;
};
/**
* Update the cached dimensions of the instance's items.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} [items]
* @returns {Grid}
*/
Grid.prototype.refreshItems = function(items) {
if (this._isDestroyed) return this;
var targets = this.getItems(items);
var i;
for (i = 0; i < targets.length; i++) {
targets[i]._refreshDimensions();
}
return this;
};
/**
* Update the sort data of the instance's items.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} [items]
* @returns {Grid}
*/
Grid.prototype.refreshSortData = function(items) {
if (this._isDestroyed) return this;
var targetItems = this.getItems(items);
var i;
for (i = 0; i < targetItems.length; i++) {
targetItems[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
* @memberof Grid.prototype
* @returns {Grid}
*/
Grid.prototype.synchronize = function() {
if (this._isDestroyed) return this;
var container = this._element;
var items = this._items;
var fragment;
var element;
var i;
// 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.
this._emit(eventSynchronize);
return this;
};
/**
* Calculate and apply item positions.
*
* @public
* @memberof Grid.prototype
* @param {Boolean} [instant=false]
* @param {LayoutCallback} [onFinish]
* @returns {Grid}
*/
Grid.prototype.layout = function(instant, onFinish) {
if (this._isDestroyed) return this;
var inst = this;
var element = this._element;
var layout = this._updateLayout();
var layoutId = layout.id;
var itemsLength = layout.items.length;
var counter = itemsLength;
var callback = typeof instant === 'function' ? instant : onFinish;
var isCallbackFunction = typeof callback === 'function';
var callbackItems = isCallbackFunction ? layout.items.slice(0) : null;
var isBorderBox;
var item;
var i;
// 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) return;
var hasLayoutChanged = inst._layout.id !== layoutId;
isCallbackFunction && callback(hasLayoutChanged, callbackItems);
if (!hasLayoutChanged && inst._hasListeners(eventLayoutEnd)) {
inst._emit(eventLayoutEnd, layout.items.slice(0));
}
}
// 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 borders to the dimensions if
// it's box-sizing is border-box.
if (
(layout.setHeight && typeof layout.height === 'number') ||
(layout.setWidth && typeof layout.width === 'number')
) {
isBorderBox = getStyle(element, 'box-sizing') === 'border-box';
}
if (layout.setHeight) {
if (typeof layout.height === 'number') {
element.style.height =
(isBorderBox ? layout.height + this._borderTop + this._borderBottom : layout.height) + 'px';
} else {
element.style.height = layout.height;
}
}
if (layout.setWidth) {
if (typeof layout.width === 'number') {
element.style.width =
(isBorderBox ? layout.width + this._borderLeft + this._borderRight : layout.width) + 'px';
} else {
element.style.width = layout.width;
}
}
// Emit layoutStart event. Note that this is intentionally emitted after the
// container element's dimensions are set, because otherwise there would be
// no hook for reacting to container dimension changes.
if (this._hasListeners(eventLayoutStart)) {
this._emit(eventLayoutStart, layout.items.slice(0));
}
// If there are no items let's finish quickly.
if (!itemsLength) {
tryFinish();
return this;
}
// If there are items let's position them.
for (i = 0; i < itemsLength; i++) {
item = layout.items[i];
if (!item) continue;
// Update item's position.
item._left = layout.slots[i * 2];
item._top = layout.slots[i * 2 + 1];
// Layout item if it is not dragged.
item.isDragging() ? tryFinish() : item._layout.start(instant === true, tryFinish);
}
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
* @memberof Grid.prototype
* @param {(HTMLElement|HTMLElement[])} elements
* @param {Object} [options]
* @param {Number} [options.index=-1]
* @param {Boolean} [options.isActive]
* @param {(Boolean|LayoutCallback|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 || 0;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var items = this._items;
var needsLayout = false;
var item;
var i;
// Map provided elements into new grid items.
for (i = 0; i < newItems.length; i++) {
item = new Item(this, newItems[i], opts.isActive);
newItems[i] = item;
// 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;
}
}
// Add the new items to the items collection to correct index.
arrayInsert(items, newItems, opts.index);
// Emit add event.
if (this._hasListeners(eventAdd)) {
this._emit(eventAdd, newItems.slice(0));
}
// If layout is needed.
if (needsLayout && layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? layout : undefined);
}
return newItems;
};
/**
* Remove items from the instance.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} items
* @param {Object} [options]
* @param {Boolean} [options.removeElements=false]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Item[]}
*/
Grid.prototype.remove = function(items, options) {
if (this._isDestroyed) return this;
var opts = options || 0;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var needsLayout = false;
var allItems = this.getItems();
var targetItems = this.getItems(items);
var indices = [];
var item;
var i;
// Remove the individual items.
for (i = 0; i < targetItems.length; i++) {
item = targetItems[i];
indices.push(allItems.indexOf(item));
if (item._isActive) needsLayout = true;
item._destroy(opts.removeElements);
}
// Emit remove event.
if (this._hasListeners(eventRemove)) {
this._emit(eventRemove, targetItems.slice(0), indices);
}
// If layout is needed.
if (needsLayout && layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? layout : undefined);
}
return targetItems;
};
/**
* Show instance items.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} 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) {
if (this._isDestroyed) return this;
this._setItemsVisibility(items, true, options);
return this;
};
/**
* Hide instance items.
*
* @public
* @memberof Grid.prototype
* @param {GridMultiItemQuery} 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) {
if (this._isDestroyed) return this;
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
* @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) {
if (this._isDestroyed || !this._items.length) return this;
var itemsToShow = [];
var itemsToHide = [];
var isPredicateString = typeof predicate === 'string';
var isPredicateFn = typeof predicate === 'function';
var opts = options || 0;
var isInstant = opts.instant === true;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var onFinish = typeof opts.onFinish === 'function' ? 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,
onFinish: tryFinish,
layout: false
});
} else {
tryFinish();
}
// Hide items that need to be hidden.
if (itemsToHide.length) {
this.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.
if (this._hasListeners(eventFilter)) {
this._emit(eventFilter, itemsToShow.slice(0), itemsToHide.slice(0));
}
// If layout is needed.
if (layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? 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
* @memberof Grid.prototype
* @param {(Function|Item[]|String|String[])} comparer
* @param {Object} [options]
* @param {Boolean} [options.descending=false]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.sort = (function() {
var sortComparer;
var isDescending;
var origItems;
var indexMap;
function parseCriteria(data) {
return data
.trim()
.split(' ')
.map(function(val) {
return val.split(':');
});
}
function getIndexMap(items) {
var ret = {};
for (var i = 0; i < items.length; i++) {
ret[items[i]._id] = i;
}
return ret;
}
function compareIndices(itemA, itemB) {
var indexA = indexMap[itemA._id];
var indexB = indexMap[itemB._id];
return isDescending ? indexB - indexA : indexA - indexB;
}
function defaultComparer(a, b) {
var result = 0;
var criteriaName;
var criteriaOrder;
var valA;
var valB;
// Loop through the list of sort criteria.
for (var i = 0; i < sortComparer.length; i++) {
// Get the criteria name, which should match an item's sort data key.
criteriaName = sortComparer[i][0];
criteriaOrder = sortComparer[i][1];
// Get items' cached sort values for the criteria. If the item has no sort
// data let's update the items sort data (this is a lazy load mechanism).
valA = (a._sortData ? a : a._refreshSortData())._sortData[criteriaName];
valB = (b._sortData ? b : b._refreshSortData())._sortData[criteriaName];
// Sort the items in descending order if defined so explicitly. Otherwise
// sort items in ascending order.
if (criteriaOrder === 'desc' || (!criteriaOrder && isDescending)) {
result = valB < valA ? -1 : valB > valA ? 1 : 0;
} else {
result = valA < valB ? -1 : valA > valB ? 1 : 0;
}
// If we have -1 or 1 as the return value, let's return it immediately.
if (result) return result;
}
// If values are equal let's compare the item indices to make sure we
// have a stable sort.
if (!result) {
if (!indexMap) indexMap = getIndexMap(origItems);
result = compareIndices(a, b);
}
return result;
}
function customComparer(a, b) {
var result = sortComparer(a, b);
// If descending let's invert the result value.
if (isDescending && result) result = -result;
// If values are equal let's compare the item indices to make sure we
// have a stable sort.
if (!result) {
if (!indexMap) indexMap = getIndexMap(origItems);
result = compareIndices(a, b);
}
return result;
}
return function(comparer, options) {
if (this._isDestroyed || this._items.length < 2) return this;
var items = this._items;
var opts = options || 0;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var i;
// Setup parent scope data.
sortComparer = comparer;
isDescending = !!opts.descending;
origItems = items.slice(0);
indexMap = null;
// If function is provided do a native array sort.
if (typeof sortComparer === 'function') {
items.sort(customComparer);
}
// Otherwise if we got a string, let's sort by the sort data as provided in
// the instance's options.
else if (typeof sortComparer === 'string') {
sortComparer = parseCriteria(comparer);
items.sort(defaultComparer);
}
// Otherwise if we got an array, let's assume it's a presorted array of the
// items and order the items based on it.
else if (Array.isArray(sortComparer)) {
if (sortComparer.length !== items.length) {
throw new Error('[' + namespace + '] sort reference items do not match with grid items.');
}
for (i = 0; i < items.length; i++) {
if (sortComparer.indexOf(items[i]) < 0) {
throw new Error('[' + namespace + '] sort reference items do not match with grid items.');
}
items[i] = sortComparer[i];
}
if (isDescending) items.reverse();
}
// Otherwise let's just skip it, nothing we can do here.
else {
/** @todo Maybe throw an error here? */
return this;
}
// Emit sort event.
if (this._hasListeners(eventSort)) {
this._emit(eventSort, items.slice(0), origItems);
}
// If layout is needed.
if (layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? layout : undefined);
}
return this;
};
})();
/**
* Move item to another index or in place of another item.
*
* @public
* @memberof Grid.prototype
* @param {GridSingleItemQuery} item
* @param {GridSingleItemQuery} position
* @param {Object} [options]
* @param {String} [options.action="move"]
* - Accepts either "move" or "swap".
* - "move" moves the item in place of the other item.
* - "swap" swaps the position of the items.
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
* @returns {Grid}
*/
Grid.prototype.move = function(item, position, options) {
if (this._isDestroyed || this._items.length < 2) return this;
var items = this._items;
var opts = options || 0;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var isSwap = opts.action === 'swap';
var action = isSwap ? 'swap' : 'move';
var fromItem = this._getItem(item);
var toItem = this._getItem(position);
var fromIndex;
var toIndex;
// Make sure the items exist and are not the same.
if (fromItem && toItem && fromItem !== toItem) {
// Get the indices of the items.
fromIndex = items.indexOf(fromItem);
toIndex = items.indexOf(toItem);
// Do the move/swap.
if (isSwap) {
arraySwap(items, fromIndex, toIndex);
} else {
arrayMove(items, fromIndex, toIndex);
}
// Emit move event.
if (this._hasListeners(eventMove)) {
this._emit(eventMove, {
item: fromItem,
fromIndex: fromIndex,
toIndex: toIndex,
action: action
});
}
// If layout is needed.
if (layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? layout : undefined);
}
}
return this;
};
/**
* Send item to another Grid instance.
*
* @public
* @memberof Grid.prototype
* @param {GridSingleItemQuery} item
* @param {Grid} grid
* @param {GridSingleItemQuery} position
* @param {Object} [options]
* @param {HTMLElement} [options.appendTo=document.body]
* @param {(Boolean|LayoutCallback|String)} [options.layoutSender=true]
* @param {(Boolean|LayoutCallback|String)} [options.layoutReceiver=true]
* @returns {Grid}
*/
Grid.prototype.send = function(item, grid, position, options) {
if (this._isDestroyed || grid._isDestroyed || this === grid) return this;
// Make sure we have a valid target item.
item = this._getItem(item);
if (!item) return this;
var opts = options || 0;
var container = opts.appendTo || document.body;
var layoutSender = opts.layoutSender ? opts.layoutSender : opts.layoutSender === undefined;
var layoutReceiver = opts.layoutReceiver
? opts.layoutReceiver
: opts.layoutReceiver === undefined;
// Start the migration process.
item._migrate.start(grid, position, container);
// If migration was started successfully and the item is active, let's layout
// the grids.
if (item._migrate._isActive && item._isActive) {
if (layoutSender) {
this.layout(
layoutSender === 'instant',
typeof layoutSender === 'function' ? layoutSender : undefined
);
}
if (layoutReceiver) {
grid.layout(
layoutReceiver === 'instant',
typeof layoutReceiver === 'function' ? layoutReceiver : undefined
);
}
}
return this;
};
/**
* Destroy the instance.
*
* @public
* @memberof Grid.prototype
* @param {Boolean} [removeElements=false]
* @returns {Grid}
*/
Grid.prototype.destroy = function(removeElements) {
if (this._isDestroyed) return this;
var container = this._element;
var items = this._items.slice(0);
var i;
// Unbind window resize event listener.
if (this._resizeHandler) {
window.removeEventListener('resize', this._resizeHandler);
}
// Destroy items.
for (i = 0; i < items.length; i++) {
items[i]._destroy(removeElements);
}
// Restore container.
removeClass(container, this._settings.containerClass);
container.style.height = '';
container.style.width = '';
// Emit destroy event and unbind all events.
this._emit(eventDestroy);
this._emitter.destroy();
// Remove reference from the grid instances collection.
gridInstances[this._id] = undefined;
// Flag instance as destroyed.
this._isDestroyed = true;
return this;
};
/**
* Private prototype methods
* *************************
*/
/**
* 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
* @memberof Grid.prototype
* @param {GridSingleItemQuery} [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') {
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.
/** @todo This could be made a lot faster by using Map/WeakMap of elements. */
for (var i = 0; i < this._items.length; i++) {
if (this._items[i]._element === target) {
return this._items[i];
}
}
return null;
};
/**
* Recalculates and updates instance's layout data.
*
* @private
* @memberof Grid.prototype
* @returns {LayoutData}
*/
Grid.prototype._updateLayout = function() {
var layout = this._layout;
var settings = this._settings.layout;
var i;
// Let's increment layout id.
++layout.id;
// Let's update layout items
layout.items.length = 0;
for (i = 0; i < this._items.length; i++) {
if (this._items[i]._isActive) layout.items.push(this._items[i]);
}
// Let's make sure we have the correct container dimensions.
this._refreshDimensions();
// Calculate container width and height (without borders).
var width = this._width - this._borderLeft - this._borderRight;
var height = this._height - this._borderTop - this._borderBottom;
// Calculate new layout.
var newLayout =
typeof settings === 'function'
? settings(layout.items.slice(0), width, height)
: packer.getLayout(layout.items, width, height, settings);
// Let's update the grid's layout.
/**
* @todo Instead of slicing create a slots array for each grid and provide
* that to the `packer.getLayout` method, which in turn can populate it.
*/
layout.slots = newLayout.slots.slice(0);
layout.setWidth = Boolean(newLayout.setWidth);
layout.setHeight = Boolean(newLayout.setHeight);
layout.width = newLayout.width;
layout.height = newLayout.height;
return layout;
};
/**
* Emit a grid event.
*
* @private
* @memberof Grid.prototype
* @param {String} event
* @param {...*} [arg]
*/
Grid.prototype._emit = function() {
if (this._isDestroyed) return;
this._emitter.emit.apply(this._emitter, arguments);
};
/**
* Check if there are any events listeners for an event.
*
* @private
* @memberof Grid.prototype
* @param {String} event
* @returns {Boolean}
*/
Grid.prototype._hasListeners = function(event) {
var listeners = this._emitter._events[event];
return !!(listeners && listeners.length);
};
/**
* Update container's width, height and offsets.
*
* @private
* @memberof Grid.prototype
*/
Grid.prototype._updateBoundingRect = function() {
var element = this._element;
var rect = element.getBoundingClientRect();
this._width = rect.width;
this._height = rect.height;
this._left = rect.left;
this._top = rect.top;
};
/**
* Update container's border sizes.
*
* @private
* @memberof Grid.prototype
* @param {Boolean} left
* @param {Boolean} right
* @param {Boolean} top
* @param {Boolean} bottom
*/
Grid.prototype._updateBorders = function(left, right, top, bottom) {
var element = this._element;
if (left) this._borderLeft = getStyleAsFloat(element, 'border-left-width');
if (right) this._borderRight = getStyleAsFloat(element, 'border-right-width');
if (top) this._borderTop = getStyleAsFloat(element, 'border-top-width');
if (bottom) this._borderBottom = getStyleAsFloat(element, 'border-bottom-width');
};
/**
* Refresh all of container's internal dimensions and offsets.
*
* @private
* @memberof Grid.prototype
*/
Grid.prototype._refreshDimensions = function() {
this._updateBoundingRect();
this._updateBorders(1, 1, 1, 1);
};
/**
* Show or hide Grid instance's items.
*
* @private
* @memberof Grid.prototype
* @param {GridMultiItemQuery} items
* @param {Boolean} toVisible
* @param {Object} [options]
* @param {Boolean} [options.instant=false]
* @param {(ShowCallback|HideCallback)} [options.onFinish]
* @param {(Boolean|LayoutCallback|String)} [options.layout=true]
*/
Grid.prototype._setItemsVisibility = function(items, toVisible, options) {
var grid = this;
var targetItems = this.getItems(items);
var opts = options || 0;
var isInstant = opts.instant === true;
var callback = opts.onFinish;
var layout = opts.layout ? opts.layout : opts.layout === undefined;
var counter = targetItems.length;
var startEvent = toVisible ? eventShowStart : eventHideStart;
var endEvent = toVisible ? eventShowEnd : eventHideEnd;
var method = toVisible ? 'show' : 'hide';
var needsLayout = false;
var completedItems = [];
var hiddenItems = [];
var item;
var i;
// If there are no items call the callback, but don't emit any events.
if (!counter) {
if (typeof callback === 'function') callback(targetItems);
return;
}
// Emit showStart/hideStart event.
if (this._hasListeners(startEvent)) {
this._emit(startEvent, targetItems.slice(0));
}
// Show/hide items.
for (i = 0; i < targetItems.length; i++) {
item = targetItems[i];
// If inactive item is shown or active item is hidden we need to do
// layout.
if ((toVisible && !item._isActive) || (!toVisible && item._isActive)) {
needsLayout = true;
}
// If inactive item is shown we also need to do a little hack to make the
// item not animate it's next positioning (layout).
if (toVisible && !item._isActive) {
item._layout._skipNextAnimation = true;
}
// If a hidden item is being shown we need to refresh the item's
// dimensions.
if (toVisible && item._visibility._isHidden) {
hiddenItems.push(item);
}
// Show/hide the item.
item._visibility[method](isInstant, function(interrupted, item) {
// If the current item's animation was not interrupted add it to the
// completedItems array.
if (!interrupted) completedItems.push(item);
// If all items have finished their animations call the callback
// and emit showEnd/hideEnd event.
if (--counter < 1) {
if (typeof callback === 'function') callback(completedItems.slice(0));
if (grid._hasListeners(endEvent)) grid._emit(endEvent, completedItems.slice(0));
}
});
}
// Refresh hidden items.
if (hiddenItems.length) this.refreshItems(hiddenItems);
// Layout if needed.
if (needsLayout && layout) {
this.layout(layout === 'instant', typeof layout === 'function' ? layout : undefined);
}
};
/**
* Private helpers
* ***************
*/
/**
* Merge default settings with user settings. The returned object is a new
* object with merged values. The merging is a deep merge meaning that all
* objects and arrays within the provided settings objects will be also merged
* so that modifying the values of the settings object will have no effect on
* the returned object.
*
* @param {Object} defaultSettings
* @param {Object} [userSettings]
* @returns {Object} Returns a new object.
*/
function mergeSettings(defaultSettings, userSettings) {
// Create a fresh copy of default settings.
var ret = mergeObjects({}, defaultSettings);
// Merge user settings to default settings.
if (userSettings) {
ret = mergeObjects(ret, userSettings);
}
// Handle visible/hidden styles manually so that the whole object is
// overridden instead of the props.
ret.visibleStyles = (userSettings || 0).visibleStyles || (defaultSettings || 0).visibleStyles;
ret.hiddenStyles = (userSettings || 0).hiddenStyles || (defaultSettings || 0).hiddenStyles;
return ret;
}
/**
* Merge two objects recursively (deep merge). The source object's properties
* are merged to the target object.
*
* @param {Object} target
* - The target object.
* @param {Object} source
* - The source object.
* @returns {Object} Returns the target object.
*/
function mergeObjects(target, source) {
var sourceKeys = Object.keys(source);
var length = sourceKeys.length;
var isSourceObject;
var propName;
var i;
for (i = 0; i < length; i++) {
propName = sourceKeys[i];
isSourceObject = isPlainObject(source[propName]);
// If target and source values are both objects, merge the objects and
// assign the merged value to the target property.
if (isPlainObject(target[propName]) && isSourceObject) {
target[propName] = mergeObjects(mergeObjects({}, target[propName]), source[propName]);
continue;
}
// If source's value is object and target's is not let's clone the object as
// the target's value.
if (isSourceObject) {
target[propName] = mergeObjects({}, source[propName]);
continue;
}
// If source's value is an array let's clone the array as the target's
// value.
if (Array.isArray(source[propName])) {
target[propName] = source[propName].slice(0);
continue;
}
// In all other cases let's just directly assign the source's value as the
// target's value.
target[propName] = source[propName];
}
return target;
}
return Grid;
})));