-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
724 lines (481 loc) · 16.3 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
if(window.ActiveXObject || "ActiveXObject" in window){
alert('bad browser detected, this will not work properly.');
}
// INIT
;(function($, window, document, undefined) {
'use strict';
// helpers
function _id(e) { return document.getElementById(e); }
function _e(e) { return document.querySelector(e); }
function _ee(e) { return document.querySelectorAll(e); }
function _for(e,f) { var i, len=e.length; for(i=0;i<len;i++){ f(e[i]); }}
function log(e, before) { before=before||''; console.log(before+e); }
// default stuff : get from data-values later on (even though slower)
var monthArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var dayArr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
var dayLongArr = ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var month, year;
// add dates to output
// rename this func to something sane
function lurker(date,fromTo){
var main = _id('fromTo'),
y, m, d, day, cur, monthNice, dayNice, str='';
// check if we're not resetting the texts
if(date !== 'reset'){
fromTo=fromTo||'from'; // default = from
// BASE DATE + VARs
var date = new Date(date);
y = date.getFullYear().toString();
m = date.getMonth();
d = date.getDate().toString();
day = date.getDay();
monthNice = monthArr[m].substr(0,3);
dayNice = dayLongArr[day];
// Split day
var dayNice1 = dayNice.substr(0,3),
dayNice2 = dayNice.substr(3, 20);
if( fromTo == 'from' ){
cur = _id('dateFrom');
_id('dateTo').classList.remove('off');
}
else {
cur = _id('dateTo');
}
cur.classList.add('active');
str = dayNice1 + '<span class="hideSmall">' + dayNice2 + '</span>, ' + d + ' ' + monthNice + ' ' + y;
}
// reset
else {
cur = main;
str = 'Select a date'; // make this multi-lang capable via data-attributes
var dateTo = _id('dateTo'),
daysNum = _id('daysNum');
dateTo.classList.add('off');
daysNum.classList.add('off');
daysNum.querySelector('em').innerHTML = 0;
dateTo.classList.remove('active');
_id('dateFrom').classList.remove('active');
dateTo.querySelector('.r_date').innerText = str;
}
// Text selectors
var $cur = $(cur);
var r_date = $cur.children('.r_date');
// Set text (date)
r_date.html(str);
}
// returns total selected days
function showDateDiff(date1,date2,sel2){
// Create dates
var dmy1 = new Date(date1),
dmy2 = new Date(date2);
var days = Math.abs(Math.ceil( dmy1.getTime() / (3600*24*1000)) - Math.ceil( dmy2.getTime() / (3600*24*1000)));
days++;
return days;
}
/*-----------------------------------------------------
USER SELECT ACTION
1 kb
-----------------------------------------------------*/
function userSelect(e,main){
var sel1 = _id('sel1'),
sel2 = _id('sel2');
/* first selection does not exist */
if( sel1 === null ){
e.id = 'sel1';
sel1 = e;
sel1.classList.add('sel1');
lurker( sel1.getAttribute('data-date'));
// mark all previous as disabled
var td = main.querySelectorAll('tbody td'),
i=0, s1i = 9999;
_for(td, function(e){
i++;
if( e.id == 'sel1' ) { s1i = i; }
if(i < s1i){ e.classList.add('disabled'); }
})
//console.log( e.index );
}
/* first exist but not second */
else if( sel2 === null && e.id !== 'sel1' && e.className.indexOf('disabled') === -1 ){ // prevent making #2 to #1
e.id = 'sel2';
sel2 = e;
sel2.classList.add('sel2');
// set texts
lurker( sel2.getAttribute('data-date'), 'to');
// show total selected days
var numDays = showDateDiff( sel1.getAttribute('data-date'), sel2.getAttribute('data-date') );
var daysNum = _id('daysNum');
daysNum.querySelector('em').innerHTML = numDays;
daysNum.classList.remove('off');
daysNum.classList.add('bounce');
// selection is complete
var par = e.parentNode, // tr
parPar = main; // tbody (main)
var td = main.querySelectorAll('td'),
go = false,
stop = false,
i=0,
s1i=0,
s2i=999;
// add classes to td's between selections
_for(td, function(e){
i++;
if( e.id == 'sel1' ) { go=1; s1i = i; }
if( e.id == 'sel2' ) { stop=1; s2i = i; }
if( s1i < s2i && go ){
if(go){ e.classList.add('range'); }
}
if(stop){ go=0; }
})
}
/* both selections exist */
else {
lurker('reset');
var td = main.querySelectorAll('td');
_for(td, function(e){ e.classList.remove('range','disabled'); })
sel1.classList.remove('sel1');
sel1.removeAttribute('id');
_id('daysNum').classList.remove('bounce');
if(sel2 !== null){
sel2.classList.remove('sel2');
sel2.removeAttribute('id');
}
$(e).trigger('click'); // this isn't super nice...
}
}
/*-----------------------------------------------------
GET MONTH DATA
1.26kb
Fork of github thingy
-----------------------------------------------------*/
// month info,fork off of github
var monthData=function(year,month){var date=new Date(year,month,0);this.totalDays=date.getDate();this.endDay=date.getDay();date.setDate(0);this.startDay=date.getDay(0);this.days=[];this.nextMonthStart=false;var prevMonthDays=0;if(this.startDay!==0)prevMonthDays=(new Date(year,month-1,0)).getDate()-this.startDay;var count=0;for(var i=0;i<42;i++){var day={};if(i<this.startDay)day.date=prevMonthDays=prevMonthDays+1;else if(i>this.totalDays+(this.startDay-1)){day.date=count=count+1;if(!this.nextMonthStart)this.nextMonthStart=i}else day.date=i-this.startDay+1;this.days[this.days.length]=day.date}};
// year, month, mainSelector to append to
function getMonth(year, month, main, numCalendar){
numCalendar = numCalendar||1; // number or just 1
// BASE VARs / VAR cache
var ni = 0,
i = 0,
monthNice,
dayNice,
m,
days,
startDay,
endDay,
totalDays,
nextMonth,
nextMonthStart,
nextYear,
curDate,
key,
out = '';
// begin loop
for(ni;ni<numCalendar;ni++){
// increase month
month++;
if(month === 13) { month=1; year++; }
// month data
m = {};
monthData.call(m, year, month); // returns object to m, wants 1-12 index
// SET VARs
days = m.days;
startDay = m.startDay;
endDay = m.endDay;
totalDays = m.totalDays;
nextMonthStart = m.nextMonthStart;
monthNice = monthArr[month-1]; // zero-based index
if(month > 12) { nextMonth = 1; nextYear = year+1; } else { nextMonth=month; nextYear = year; }
// BEGIN out
out += '<div class="r_month">';
out += '<em class="r_title">' + monthNice + ' <span>' + year + '</span></em>';
out += '<table>';
// weekdays
out += '<thead><tr>';
_for(dayArr, function(e){ out += '<td>' + e + '</td>'; })
out += '</tr></thead>';
// days
out += '<tbody>';
for(key in days){
i++;
curDate = nextYear + '-' + nextMonth + '-' + days[key];
// start row
if(i === 1) out += '<tr>';
// not in current month
if( key < startDay || ( key >= nextMonthStart ) ) {
switch(true){
case key < startDay && nextMonth != 1:
curDate = nextYear + '-' + (nextMonth-1) + '-' + days[key]; // previous month = month-1
break;
case key < startDay && nextMonth == 1:
curDate = (nextYear-1) + '-' + 12 + '-' + days[key]; // previous month is december the year before
break;
case key >= nextMonthStart && nextMonth != 12:
curDate = nextYear + '-' + (nextMonth+1) + '-' + days[key]; // next month = month+1
break;
case key >= nextMonthStart && nextMonth == 12:
curDate = nextYear+1 + '-' + 1 + '-' + days[key]; // next month is january next year
break;
}
out += '<td class="notCurMonth" data-date="'+ curDate +'"><i>'+days[key]+'</i></td>';
}
// the rest, current month
else {
out += '<td data-date="'+ curDate +'"><i>'+days[key]+'</i></td>';
}
// end row
if(i === 7) { out += '</tr>'; i=0; }
}
out += '</tbody>';
out += '</table>';
out += '</div>'; // end r_month
} // end loop
$('#dp').html(out);
} // getMonth() end
/*-----------------------------------------------------
INIT ON LOAD
-----------------------------------------------------*/
// init on load
var main = _id('dp'); // datePicker main div
var now = new Date()
var month = now.getMonth(),
date = now.getDate(),
year = now.getFullYear(),
totalMonths = 12;
// getmonth year, month, mainSelector, number of months
// renders all the month data
getMonth(year, month, main, totalMonths);
/*-----------------------------------------------------
BINDS
-----------------------------------------------------*/
$(main).on('click', 'tbody td', function(){ userSelect(this, main); });
var rNav = $('#r_nav'),
dp = _id('dp');
/* NAVIGATE */
rNav.on('click', '.nav', function(e){
var curX,
curId = this.id,
calWidth = dp.offsetWidth;
if( dp.className == '' ) { curX = 0; dp.className = 0; }
else {
curX = dp.className;
curX = parseInt(curX);
}
// calculate max percentage
var len = totalMonths;
if(calWidth > 500) { len = len/2; }
len = len-1+'00';
len = '-' + len;
if(curId == 'next' && curX > len ){
if(calWidth < 500) { curX = curX-100; }
else { curX = curX-50; }
_id('prev').classList.remove('off');
}
else if(curId == 'next' && curX <= len) {
this.classList.add('off');
}
if(curId == 'prev' && curX < 0 ){
if(calWidth < 500) { curX = curX+100; }
else { curX = curX+50; }
_id('next').classList.remove('off');
}
else if(curId == 'prev' && curX > len) {
this.classList.add('off');
}
// 12/2 = 6 views total.
// 6 = @ 600% the views are gone!
// (12/2)-1+'00%' = max slide
dp.style.transform = 'translateX(' + curX + '%)';
dp.className = curX;
})
/*-----------------------------------------------------
OK / CANCEL BUTTONS
Only thing this should be doing is
1. Reset dates
2. Close datepicker
Dates are set at selection
..or is this bad because no way of then resetting form?
.. creates horrible markup since we then need to have extra vals @ input
-----------------------------------------------------*/
$('#dactions').on('click', 'button', function(){
// Cancel button
if( this.className.indexOf('red') > -1 ){
// reset form and close
}
// OK button
else {
// close the datepicker
}
})
/*-----------------------------------------------------
EXTRAS
Todo: Have this be plugins/extensions
Current @ 1.5kb uncompressed
-----------------------------------------------------*/
// show selection on hover
// add this as some sort of plugin, adds ~0.6kb to total
var hoverTimer = 20,
hoverId;
$(main).on('mouseenter', 'tbody td', function(){
clearTimeout(hoverId);
hoverId = setTimeout(hoverRange, hoverTimer, this); // use throttling for perf reasons
});
function hoverRange(t){
var sel1 = _id('sel1'), // later move all this outside of mouseenter for perf reasons; note: calendar must ofc exist *BEFORE* all binds
sel2 = _id('sel2');
if( sel1 !== null && sel2 == null ){
var td = document.querySelectorAll('tbody td'), // later move outside for perf reasons
i=0, s1i=0, s2i=0, sel2, sel1data,
t = t;
_for(td, function(e){
i++;
e.classList.remove('selCur','range');
t.classList.add('selCur');
if( e.id == 'sel1' ) { s1i = i; sel1 = e.getAttribute('data-date'); } // get index of selection 1 and start from this <td>
if( e.className.indexOf("selCur") > -1 ) { s2i = i+1; sel2 = e.getAttribute('data-date'); }
var dateDiff = showDateDiff(sel1, sel2);
_id('daysNum').querySelector('em').innerText = dateDiff;
_id('daysNum').classList.remove('off');
}) // end for-loop
i=0;
_for(td, function(e){
i++;
if(i > s1i && i < s2i ) { e.classList.add('range'); }
})
} // end if sel1 !== null
};
/*-----------------------------------------------------
Keyboard/mouse navigation
Adds: ~0.7kb
-----------------------------------------------------*/
/*
$(document).on('keydown', function(e){
var keyCode = e.keyCode || e.which,
arrow = {left: 37, up: 38, right: 39, down: 40 };
switch (keyCode) {
case arrow.left:
$(_id('prev')).trigger('click');
e.preventDefault();
break;
case arrow.right:
$(_id('next')).trigger('click');
e.preventDefault();
break;
case arrow.up:
break;
case arrow.down:
break;
}
})
// Important option
// timer delay in ms, higher = better perf but less responsive ui
var menuTimer = 60,
timerId,
navPrev = $(_id('prev')),
navNext = $(_id('next')),
collectUp = 0,
collectDown = 0;
// VARs
var win = $(window),
rcal = $('#r_cals');
// Evil window scroll function
rcal.on('mousewheel DOMMouseScroll', function (event) {
clearTimeout(timerId);
//var delta = event.originalEvent.wheelDelta;
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// up
collectUp++;
collectDown = 0;
}
else {
// down
collectDown++;
collectUp = 0;
}
timerId = setTimeout(function(){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
if(collectUp < 2) collectUp = 1;
//up
while(collectUp--){ navPrev.trigger('click'); } // navPrev/next should be a function that takes X interations in order to multiple value when scrolling fast instead of firing 10x times etc.
}
else {
//down
if(collectDown < 2) collectDown = 1;
while(collectDown--){ navNext.trigger('click'); }
}
}, menuTimer);
event.preventDefault();
});
*/
/*-----------------------------------------------------
MISC
-----------------------------------------------------*/
/*
var tip=null;
// TEMP HOVER TO SHOW DATA-DATE
$(main).on('mouseenter', 'tbody td', function(){
var d = this.getAttribute('data-date');
this.innerHTML += '<div id="tip" class="tip">'+d+'</div>';
tip = _ee('.tip');
})
.on('mouseleave', 'tbody td', function(){
$(tip).remove();
});
*/
/*-----------------------------------------------------
SWIPE
0.55kb
use: wipeLeft, wipeRight, wipeUp, wipeDown
-----------------------------------------------------*/
$.fn.swipe = function(o) {
var el = $(this),
left = o.left,
right = o.right,
up = o.up,
down = o.down,
requiredDist = o.requiredDist || 100,
allowedTime = o.allowedTime || 500,
startTime = 0,
distX = 0,
distY = 0,
startX = 0,
startY = 0;
el.on({
touchstart: function (e) {
//e.preventDefault(); // causes clicks not to work
var touch = e.originalEvent.changedTouches[0];
startX = touch.pageX;
startY = touch.pageY;
distX = 0;
distY = 0;
startTime = new Date().getTime();
},
touchmove: function (e) { e.preventDefault(); },
touchend: function (e) {
var touch = e.originalEvent.changedTouches[0],
distX = touch.pageX - startX,
distY = touch.pageY - startY,
time = new Date().getTime() - startTime;
if (time < allowedTime) {
if (Math.abs(distX) >= requiredDist) {
if (distX > 0 && right) right.call(this);
if (distX < 0 && left) left.call(this);
e.preventDefault();
}
if (Math.abs(distY) >= requiredDist) {
if (distY > 0 && down) down.call(this);
if (distY < 0 && up) up.call(this);
e.preventDefault();
}
}
}
});
};
// init swipe gestures
var cal = $('#cal');
cal.swipe({
left: function (evt) { $(_id('next')).trigger('click'); },
right: function (evt) { $(_id('prev')).trigger('click'); },
requiredDist: 30, // Required distance to trigger swipe. Optional, defaults to 100
allowedTime: 300 // Distance must be covered in this time. Optional, defaults to 500
});
})(jQuery, window, document); // end() init