util.js
18.2 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
// exports
fc.intersectionToSeg = intersectionToSeg;
fc.applyAll = applyAll;
fc.debounce = debounce;
fc.isInt = isInt;
fc.htmlEscape = htmlEscape;
fc.cssToStr = cssToStr;
fc.proxy = proxy;
/* FullCalendar-specific DOM Utilities
----------------------------------------------------------------------------------------------------------------------*/
// Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
// and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
function compensateScroll(rowEls, scrollbarWidths) {
if (scrollbarWidths.left) {
rowEls.css({
'border-left-width': 1,
'margin-left': scrollbarWidths.left - 1
});
}
if (scrollbarWidths.right) {
rowEls.css({
'border-right-width': 1,
'margin-right': scrollbarWidths.right - 1
});
}
}
// Undoes compensateScroll and restores all borders/margins
function uncompensateScroll(rowEls) {
rowEls.css({
'margin-left': '',
'margin-right': '',
'border-left-width': '',
'border-right-width': ''
});
}
// Make the mouse cursor express that an event is not allowed in the current area
function disableCursor() {
$('body').addClass('fc-not-allowed');
}
// Returns the mouse cursor to its original look
function enableCursor() {
$('body').removeClass('fc-not-allowed');
}
// Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
// By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
// any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
// reduces the available height.
function distributeHeight(els, availableHeight, shouldRedistribute) {
// *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
// and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
var flexEls = []; // elements that are allowed to expand. array of DOM nodes
var flexOffsets = []; // amount of vertical space it takes up
var flexHeights = []; // actual css height
var usedHeight = 0;
undistributeHeight(els); // give all elements their natural height
// find elements that are below the recommended height (expandable).
// important to query for heights in a single first pass (to avoid reflow oscillation).
els.each(function(i, el) {
var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
var naturalOffset = $(el).outerHeight(true);
if (naturalOffset < minOffset) {
flexEls.push(el);
flexOffsets.push(naturalOffset);
flexHeights.push($(el).height());
}
else {
// this element stretches past recommended height (non-expandable). mark the space as occupied.
usedHeight += naturalOffset;
}
});
// readjust the recommended height to only consider the height available to non-maxed-out rows.
if (shouldRedistribute) {
availableHeight -= usedHeight;
minOffset1 = Math.floor(availableHeight / flexEls.length);
minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
}
// assign heights to all expandable elements
$(flexEls).each(function(i, el) {
var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
var naturalOffset = flexOffsets[i];
var naturalHeight = flexHeights[i];
var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
$(el).height(newHeight);
}
});
}
// Undoes distrubuteHeight, restoring all els to their natural height
function undistributeHeight(els) {
els.height('');
}
// Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
// cells to be that width.
// PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
function matchCellWidths(els) {
var maxInnerWidth = 0;
els.find('> *').each(function(i, innerEl) {
var innerWidth = $(innerEl).outerWidth();
if (innerWidth > maxInnerWidth) {
maxInnerWidth = innerWidth;
}
});
maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
els.width(maxInnerWidth);
return maxInnerWidth;
}
// Turns a container element into a scroller if its contents is taller than the allotted height.
// Returns true if the element is now a scroller, false otherwise.
// NOTE: this method is best because it takes weird zooming dimensions into account
function setPotentialScroller(containerEl, height) {
containerEl.height(height).addClass('fc-scroller');
// are scrollbars needed?
if (containerEl[0].scrollHeight - 1 > containerEl[0].clientHeight) { // !!! -1 because IE is often off-by-one :(
return true;
}
unsetScroller(containerEl); // undo
return false;
}
// Takes an element that might have been a scroller, and turns it back into a normal element.
function unsetScroller(containerEl) {
containerEl.height('').removeClass('fc-scroller');
}
/* General DOM Utilities
----------------------------------------------------------------------------------------------------------------------*/
fc.getClientRect = getClientRect;
fc.getContentRect = getContentRect;
fc.getScrollbarWidths = getScrollbarWidths;
// borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
function getScrollParent(el) {
var position = el.css('position'),
scrollParent = el.parents().filter(function() {
var parent = $(this);
return (/(auto|scroll)/).test(
parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
);
}).eq(0);
return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
}
// Queries the outer bounding area of a jQuery element.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
function getOuterRect(el) {
var offset = el.offset();
return {
left: offset.left,
right: offset.left + el.outerWidth(),
top: offset.top,
bottom: offset.top + el.outerHeight()
};
}
// Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
function getClientRect(el) {
var offset = el.offset();
var scrollbarWidths = getScrollbarWidths(el);
var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left;
var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top;
return {
left: left,
right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
top: top,
bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
};
}
// Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
function getContentRect(el) {
var offset = el.offset(); // just outside of border, margin not included
var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left');
var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top');
return {
left: left,
right: left + el.width(),
top: top,
bottom: top + el.height()
};
}
// Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
function getScrollbarWidths(el) {
var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
var widths = {
left: 0,
right: 0,
top: 0,
bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
};
if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
widths.left = leftRightWidth;
}
else {
widths.right = leftRightWidth;
}
return widths;
}
// Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
var _isLeftRtlScrollbars = null;
function getIsLeftRtlScrollbars() { // responsible for caching the computation
if (_isLeftRtlScrollbars === null) {
_isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
}
return _isLeftRtlScrollbars;
}
function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
var el = $('<div><div/></div>')
.css({
position: 'absolute',
top: -1000,
left: 0,
border: 0,
padding: 0,
overflow: 'scroll',
direction: 'rtl'
})
.appendTo('body');
var innerEl = el.children();
var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
el.remove();
return res;
}
// Retrieves a jQuery element's computed CSS value as a floating-point number.
// If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
function getCssFloat(el, prop) {
return parseFloat(el.css(prop)) || 0;
}
// Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
function isPrimaryMouseButton(ev) {
return ev.which == 1 && !ev.ctrlKey;
}
/* Geometry
----------------------------------------------------------------------------------------------------------------------*/
// Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
function intersectRects(rect1, rect2) {
var res = {
left: Math.max(rect1.left, rect2.left),
right: Math.min(rect1.right, rect2.right),
top: Math.max(rect1.top, rect2.top),
bottom: Math.min(rect1.bottom, rect2.bottom)
};
if (res.left < res.right && res.top < res.bottom) {
return res;
}
return false;
}
// Returns a new point that will have been moved to reside within the given rectangle
function constrainPoint(point, rect) {
return {
left: Math.min(Math.max(point.left, rect.left), rect.right),
top: Math.min(Math.max(point.top, rect.top), rect.bottom)
};
}
// Returns a point that is the center of the given rectangle
function getRectCenter(rect) {
return {
left: (rect.left + rect.right) / 2,
top: (rect.top + rect.bottom) / 2
};
}
// Subtracts point2's coordinates from point1's coordinates, returning a delta
function diffPoints(point1, point2) {
return {
left: point1.left - point2.left,
top: point1.top - point2.top
};
}
/* FullCalendar-specific Misc Utilities
----------------------------------------------------------------------------------------------------------------------*/
// Creates a basic segment with the intersection of the two ranges. Returns undefined if no intersection.
// Expects all dates to be normalized to the same timezone beforehand.
// TODO: move to date section?
function intersectionToSeg(subjectRange, constraintRange) {
var subjectStart = subjectRange.start;
var subjectEnd = subjectRange.end;
var constraintStart = constraintRange.start;
var constraintEnd = constraintRange.end;
var segStart, segEnd;
var isStart, isEnd;
if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
if (subjectStart >= constraintStart) {
segStart = subjectStart.clone();
isStart = true;
}
else {
segStart = constraintStart.clone();
isStart = false;
}
if (subjectEnd <= constraintEnd) {
segEnd = subjectEnd.clone();
isEnd = true;
}
else {
segEnd = constraintEnd.clone();
isEnd = false;
}
return {
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd
};
}
}
/* Date Utilities
----------------------------------------------------------------------------------------------------------------------*/
fc.computeIntervalUnit = computeIntervalUnit;
fc.durationHasTime = durationHasTime;
var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
// Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
// Moments will have their timezones normalized.
function diffDayTime(a, b) {
return moment.duration({
days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
ms: a.time() - b.time() // time-of-day from day start. disregards timezone
});
}
// Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
function diffDay(a, b) {
return moment.duration({
days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
});
}
// Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
function diffByUnit(a, b, unit) {
return moment.duration(
Math.round(a.diff(b, unit, true)), // returnFloat=true
unit
);
}
// Computes the unit name of the largest whole-unit period of time.
// For example, 48 hours will be "days" whereas 49 hours will be "hours".
// Accepts start/end, a range object, or an original duration object.
function computeIntervalUnit(start, end) {
var i, unit;
var val;
for (i = 0; i < intervalUnits.length; i++) {
unit = intervalUnits[i];
val = computeRangeAs(unit, start, end);
if (val >= 1 && isInt(val)) {
break;
}
}
return unit; // will be "milliseconds" if nothing else matches
}
// Computes the number of units (like "hours") in the given range.
// Range can be a {start,end} object, separate start/end args, or a Duration.
// Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
// of month-diffing logic (which tends to vary from version to version).
function computeRangeAs(unit, start, end) {
if (end != null) { // given start, end
return end.diff(start, unit, true);
}
else if (moment.isDuration(start)) { // given duration
return start.as(unit);
}
else { // given { start, end } range object
return start.end.diff(start.start, unit, true);
}
}
// Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
function durationHasTime(dur) {
return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
}
function isNativeDate(input) {
return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
}
// Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
function isTimeString(str) {
return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
}
/* General Utilities
----------------------------------------------------------------------------------------------------------------------*/
var hasOwnPropMethod = {}.hasOwnProperty;
// Create an object that has the given prototype. Just like Object.create
function createObject(proto) {
var f = function() {};
f.prototype = proto;
return new f();
}
function copyOwnProps(src, dest) {
for (var name in src) {
if (hasOwnProp(src, name)) {
dest[name] = src[name];
}
}
}
// Copies over certain methods with the same names as Object.prototype methods. Overcomes an IE<=8 bug:
// https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
function copyNativeMethods(src, dest) {
var names = [ 'constructor', 'toString', 'valueOf' ];
var i, name;
for (i = 0; i < names.length; i++) {
name = names[i];
if (src[name] !== Object.prototype[name]) {
dest[name] = src[name];
}
}
}
function hasOwnProp(obj, name) {
return hasOwnPropMethod.call(obj, name);
}
// Is the given value a non-object non-function value?
function isAtomic(val) {
return /undefined|null|boolean|number|string/.test($.type(val));
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
function htmlEscape(s) {
return (s + '').replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function stripHtmlEntities(text) {
return text.replace(/&.*?;/g, '');
}
// Given a hash of CSS properties, returns a string of CSS.
// Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
function cssToStr(cssProps) {
var statements = [];
$.each(cssProps, function(name, val) {
if (val != null) {
statements.push(name + ':' + val);
}
});
return statements.join(';');
}
function capitaliseFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function compareNumbers(a, b) { // for .sort()
return a - b;
}
function isInt(n) {
return n % 1 === 0;
}
// Returns a method bound to the given object context.
// Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
// different contexts as identical when binding/unbinding events.
function proxy(obj, methodName) {
var method = obj[methodName];
return function() {
return method.apply(obj, arguments);
};
}
// 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.
// https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
function debounce(func, wait) {
var timeoutId;
var args;
var context;
var timestamp; // of most recent call
var later = function() {
var last = +new Date() - timestamp;
if (last < wait && last > 0) {
timeoutId = setTimeout(later, wait - last);
}
else {
timeoutId = null;
func.apply(context, args);
if (!timeoutId) {
context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = +new Date();
if (!timeoutId) {
timeoutId = setTimeout(later, wait);
}
};
}