util.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. // exports
  2. FC.intersectRanges = intersectRanges;
  3. FC.applyAll = applyAll;
  4. FC.debounce = debounce;
  5. FC.isInt = isInt;
  6. FC.htmlEscape = htmlEscape;
  7. FC.cssToStr = cssToStr;
  8. FC.proxy = proxy;
  9. FC.capitaliseFirstLetter = capitaliseFirstLetter;
  10. /* FullCalendar-specific DOM Utilities
  11. ----------------------------------------------------------------------------------------------------------------------*/
  12. // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
  13. // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
  14. function compensateScroll(rowEls, scrollbarWidths) {
  15. if (scrollbarWidths.left) {
  16. rowEls.css({
  17. 'border-left-width': 1,
  18. 'margin-left': scrollbarWidths.left - 1
  19. });
  20. }
  21. if (scrollbarWidths.right) {
  22. rowEls.css({
  23. 'border-right-width': 1,
  24. 'margin-right': scrollbarWidths.right - 1
  25. });
  26. }
  27. }
  28. // Undoes compensateScroll and restores all borders/margins
  29. function uncompensateScroll(rowEls) {
  30. rowEls.css({
  31. 'margin-left': '',
  32. 'margin-right': '',
  33. 'border-left-width': '',
  34. 'border-right-width': ''
  35. });
  36. }
  37. // Make the mouse cursor express that an event is not allowed in the current area
  38. function disableCursor() {
  39. $('body').addClass('fc-not-allowed');
  40. }
  41. // Returns the mouse cursor to its original look
  42. function enableCursor() {
  43. $('body').removeClass('fc-not-allowed');
  44. }
  45. // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
  46. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
  47. // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
  48. // reduces the available height.
  49. function distributeHeight(els, availableHeight, shouldRedistribute) {
  50. // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
  51. // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
  52. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
  53. var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
  54. var flexEls = []; // elements that are allowed to expand. array of DOM nodes
  55. var flexOffsets = []; // amount of vertical space it takes up
  56. var flexHeights = []; // actual css height
  57. var usedHeight = 0;
  58. undistributeHeight(els); // give all elements their natural height
  59. // find elements that are below the recommended height (expandable).
  60. // important to query for heights in a single first pass (to avoid reflow oscillation).
  61. els.each(function(i, el) {
  62. var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
  63. var naturalOffset = $(el).outerHeight(true);
  64. if (naturalOffset < minOffset) {
  65. flexEls.push(el);
  66. flexOffsets.push(naturalOffset);
  67. flexHeights.push($(el).height());
  68. }
  69. else {
  70. // this element stretches past recommended height (non-expandable). mark the space as occupied.
  71. usedHeight += naturalOffset;
  72. }
  73. });
  74. // readjust the recommended height to only consider the height available to non-maxed-out rows.
  75. if (shouldRedistribute) {
  76. availableHeight -= usedHeight;
  77. minOffset1 = Math.floor(availableHeight / flexEls.length);
  78. minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
  79. }
  80. // assign heights to all expandable elements
  81. $(flexEls).each(function(i, el) {
  82. var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
  83. var naturalOffset = flexOffsets[i];
  84. var naturalHeight = flexHeights[i];
  85. var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
  86. if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
  87. $(el).height(newHeight);
  88. }
  89. });
  90. }
  91. // Undoes distrubuteHeight, restoring all els to their natural height
  92. function undistributeHeight(els) {
  93. els.height('');
  94. }
  95. // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
  96. // cells to be that width.
  97. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
  98. function matchCellWidths(els) {
  99. var maxInnerWidth = 0;
  100. els.find('> span').each(function(i, innerEl) {
  101. var innerWidth = $(innerEl).outerWidth();
  102. if (innerWidth > maxInnerWidth) {
  103. maxInnerWidth = innerWidth;
  104. }
  105. });
  106. maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
  107. els.width(maxInnerWidth);
  108. return maxInnerWidth;
  109. }
  110. // Given one element that resides inside another,
  111. // Subtracts the height of the inner element from the outer element.
  112. function subtractInnerElHeight(outerEl, innerEl) {
  113. var both = outerEl.add(innerEl);
  114. var diff;
  115. // effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
  116. both.css({
  117. position: 'relative', // cause a reflow, which will force fresh dimension recalculation
  118. left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
  119. });
  120. diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
  121. both.css({ position: '', left: '' }); // undo hack
  122. return diff;
  123. }
  124. /* Element Geom Utilities
  125. ----------------------------------------------------------------------------------------------------------------------*/
  126. FC.getOuterRect = getOuterRect;
  127. FC.getClientRect = getClientRect;
  128. FC.getContentRect = getContentRect;
  129. FC.getScrollbarWidths = getScrollbarWidths;
  130. // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
  131. function getScrollParent(el) {
  132. var position = el.css('position'),
  133. scrollParent = el.parents().filter(function() {
  134. var parent = $(this);
  135. return (/(auto|scroll)/).test(
  136. parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
  137. );
  138. }).eq(0);
  139. return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
  140. }
  141. // Queries the outer bounding area of a jQuery element.
  142. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  143. // Origin is optional.
  144. function getOuterRect(el, origin) {
  145. var offset = el.offset();
  146. var left = offset.left - (origin ? origin.left : 0);
  147. var top = offset.top - (origin ? origin.top : 0);
  148. return {
  149. left: left,
  150. right: left + el.outerWidth(),
  151. top: top,
  152. bottom: top + el.outerHeight()
  153. };
  154. }
  155. // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
  156. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  157. // Origin is optional.
  158. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  159. function getClientRect(el, origin) {
  160. var offset = el.offset();
  161. var scrollbarWidths = getScrollbarWidths(el);
  162. var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
  163. var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
  164. return {
  165. left: left,
  166. right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
  167. top: top,
  168. bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
  169. };
  170. }
  171. // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
  172. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
  173. // Origin is optional.
  174. function getContentRect(el, origin) {
  175. var offset = el.offset(); // just outside of border, margin not included
  176. var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
  177. (origin ? origin.left : 0);
  178. var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
  179. (origin ? origin.top : 0);
  180. return {
  181. left: left,
  182. right: left + el.width(),
  183. top: top,
  184. bottom: top + el.height()
  185. };
  186. }
  187. // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
  188. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
  189. function getScrollbarWidths(el) {
  190. var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
  191. var widths = {
  192. left: 0,
  193. right: 0,
  194. top: 0,
  195. bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
  196. };
  197. if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
  198. widths.left = leftRightWidth;
  199. }
  200. else {
  201. widths.right = leftRightWidth;
  202. }
  203. return widths;
  204. }
  205. // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
  206. var _isLeftRtlScrollbars = null;
  207. function getIsLeftRtlScrollbars() { // responsible for caching the computation
  208. if (_isLeftRtlScrollbars === null) {
  209. _isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
  210. }
  211. return _isLeftRtlScrollbars;
  212. }
  213. function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
  214. var el = $('<div><div/></div>')
  215. .css({
  216. position: 'absolute',
  217. top: -1000,
  218. left: 0,
  219. border: 0,
  220. padding: 0,
  221. overflow: 'scroll',
  222. direction: 'rtl'
  223. })
  224. .appendTo('body');
  225. var innerEl = el.children();
  226. var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
  227. el.remove();
  228. return res;
  229. }
  230. // Retrieves a jQuery element's computed CSS value as a floating-point number.
  231. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
  232. function getCssFloat(el, prop) {
  233. return parseFloat(el.css(prop)) || 0;
  234. }
  235. /* Mouse / Touch Utilities
  236. ----------------------------------------------------------------------------------------------------------------------*/
  237. FC.preventDefault = preventDefault;
  238. // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
  239. function isPrimaryMouseButton(ev) {
  240. return ev.which == 1 && !ev.ctrlKey;
  241. }
  242. function getEvX(ev) {
  243. if (ev.pageX !== undefined) {
  244. return ev.pageX;
  245. }
  246. var touches = ev.originalEvent.touches;
  247. if (touches) {
  248. return touches[0].pageX;
  249. }
  250. }
  251. function getEvY(ev) {
  252. if (ev.pageY !== undefined) {
  253. return ev.pageY;
  254. }
  255. var touches = ev.originalEvent.touches;
  256. if (touches) {
  257. return touches[0].pageY;
  258. }
  259. }
  260. function getEvIsTouch(ev) {
  261. return /^touch/.test(ev.type);
  262. }
  263. function preventSelection(el) {
  264. el.addClass('fc-unselectable')
  265. .on('selectstart', preventDefault);
  266. }
  267. // Stops a mouse/touch event from doing it's native browser action
  268. function preventDefault(ev) {
  269. ev.preventDefault();
  270. }
  271. // attach a handler to get called when ANY scroll action happens on the page.
  272. // this was impossible to do with normal on/off because 'scroll' doesn't bubble.
  273. // http://stackoverflow.com/a/32954565/96342
  274. // returns `true` on success.
  275. function bindAnyScroll(handler) {
  276. if (window.addEventListener) {
  277. window.addEventListener('scroll', handler, true); // useCapture=true
  278. return true;
  279. }
  280. return false;
  281. }
  282. // undoes bindAnyScroll. must pass in the original function.
  283. // returns `true` on success.
  284. function unbindAnyScroll(handler) {
  285. if (window.removeEventListener) {
  286. window.removeEventListener('scroll', handler, true); // useCapture=true
  287. return true;
  288. }
  289. return false;
  290. }
  291. /* General Geometry Utils
  292. ----------------------------------------------------------------------------------------------------------------------*/
  293. FC.intersectRects = intersectRects;
  294. // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
  295. function intersectRects(rect1, rect2) {
  296. var res = {
  297. left: Math.max(rect1.left, rect2.left),
  298. right: Math.min(rect1.right, rect2.right),
  299. top: Math.max(rect1.top, rect2.top),
  300. bottom: Math.min(rect1.bottom, rect2.bottom)
  301. };
  302. if (res.left < res.right && res.top < res.bottom) {
  303. return res;
  304. }
  305. return false;
  306. }
  307. // Returns a new point that will have been moved to reside within the given rectangle
  308. function constrainPoint(point, rect) {
  309. return {
  310. left: Math.min(Math.max(point.left, rect.left), rect.right),
  311. top: Math.min(Math.max(point.top, rect.top), rect.bottom)
  312. };
  313. }
  314. // Returns a point that is the center of the given rectangle
  315. function getRectCenter(rect) {
  316. return {
  317. left: (rect.left + rect.right) / 2,
  318. top: (rect.top + rect.bottom) / 2
  319. };
  320. }
  321. // Subtracts point2's coordinates from point1's coordinates, returning a delta
  322. function diffPoints(point1, point2) {
  323. return {
  324. left: point1.left - point2.left,
  325. top: point1.top - point2.top
  326. };
  327. }
  328. /* Object Ordering by Field
  329. ----------------------------------------------------------------------------------------------------------------------*/
  330. FC.parseFieldSpecs = parseFieldSpecs;
  331. FC.compareByFieldSpecs = compareByFieldSpecs;
  332. FC.compareByFieldSpec = compareByFieldSpec;
  333. FC.flexibleCompare = flexibleCompare;
  334. function parseFieldSpecs(input) {
  335. var specs = [];
  336. var tokens = [];
  337. var i, token;
  338. if (typeof input === 'string') {
  339. tokens = input.split(/\s*,\s*/);
  340. }
  341. else if (typeof input === 'function') {
  342. tokens = [ input ];
  343. }
  344. else if ($.isArray(input)) {
  345. tokens = input;
  346. }
  347. for (i = 0; i < tokens.length; i++) {
  348. token = tokens[i];
  349. if (typeof token === 'string') {
  350. specs.push(
  351. token.charAt(0) == '-' ?
  352. { field: token.substring(1), order: -1 } :
  353. { field: token, order: 1 }
  354. );
  355. }
  356. else if (typeof token === 'function') {
  357. specs.push({ func: token });
  358. }
  359. }
  360. return specs;
  361. }
  362. function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
  363. var i;
  364. var cmp;
  365. for (i = 0; i < fieldSpecs.length; i++) {
  366. cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
  367. if (cmp) {
  368. return cmp;
  369. }
  370. }
  371. return 0;
  372. }
  373. function compareByFieldSpec(obj1, obj2, fieldSpec) {
  374. if (fieldSpec.func) {
  375. return fieldSpec.func(obj1, obj2);
  376. }
  377. return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
  378. (fieldSpec.order || 1);
  379. }
  380. function flexibleCompare(a, b) {
  381. if (!a && !b) {
  382. return 0;
  383. }
  384. if (b == null) {
  385. return -1;
  386. }
  387. if (a == null) {
  388. return 1;
  389. }
  390. if ($.type(a) === 'string' || $.type(b) === 'string') {
  391. return String(a).localeCompare(String(b));
  392. }
  393. return a - b;
  394. }
  395. /* FullCalendar-specific Misc Utilities
  396. ----------------------------------------------------------------------------------------------------------------------*/
  397. // Computes the intersection of the two ranges. Returns undefined if no intersection.
  398. // Expects all dates to be normalized to the same timezone beforehand.
  399. // TODO: move to date section?
  400. function intersectRanges(subjectRange, constraintRange) {
  401. var subjectStart = subjectRange.start;
  402. var subjectEnd = subjectRange.end;
  403. var constraintStart = constraintRange.start;
  404. var constraintEnd = constraintRange.end;
  405. var segStart, segEnd;
  406. var isStart, isEnd;
  407. if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
  408. if (subjectStart >= constraintStart) {
  409. segStart = subjectStart.clone();
  410. isStart = true;
  411. }
  412. else {
  413. segStart = constraintStart.clone();
  414. isStart = false;
  415. }
  416. if (subjectEnd <= constraintEnd) {
  417. segEnd = subjectEnd.clone();
  418. isEnd = true;
  419. }
  420. else {
  421. segEnd = constraintEnd.clone();
  422. isEnd = false;
  423. }
  424. return {
  425. start: segStart,
  426. end: segEnd,
  427. isStart: isStart,
  428. isEnd: isEnd
  429. };
  430. }
  431. }
  432. /* Date Utilities
  433. ----------------------------------------------------------------------------------------------------------------------*/
  434. FC.computeIntervalUnit = computeIntervalUnit;
  435. FC.divideRangeByDuration = divideRangeByDuration;
  436. FC.divideDurationByDuration = divideDurationByDuration;
  437. FC.multiplyDuration = multiplyDuration;
  438. FC.durationHasTime = durationHasTime;
  439. var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
  440. var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
  441. // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
  442. // Moments will have their timezones normalized.
  443. function diffDayTime(a, b) {
  444. return moment.duration({
  445. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
  446. ms: a.time() - b.time() // time-of-day from day start. disregards timezone
  447. });
  448. }
  449. // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
  450. function diffDay(a, b) {
  451. return moment.duration({
  452. days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
  453. });
  454. }
  455. // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
  456. function diffByUnit(a, b, unit) {
  457. return moment.duration(
  458. Math.round(a.diff(b, unit, true)), // returnFloat=true
  459. unit
  460. );
  461. }
  462. // Computes the unit name of the largest whole-unit period of time.
  463. // For example, 48 hours will be "days" whereas 49 hours will be "hours".
  464. // Accepts start/end, a range object, or an original duration object.
  465. function computeIntervalUnit(start, end) {
  466. var i, unit;
  467. var val;
  468. for (i = 0; i < intervalUnits.length; i++) {
  469. unit = intervalUnits[i];
  470. val = computeRangeAs(unit, start, end);
  471. if (val >= 1 && isInt(val)) {
  472. break;
  473. }
  474. }
  475. return unit; // will be "milliseconds" if nothing else matches
  476. }
  477. // Computes the number of units (like "hours") in the given range.
  478. // Range can be a {start,end} object, separate start/end args, or a Duration.
  479. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
  480. // of month-diffing logic (which tends to vary from version to version).
  481. function computeRangeAs(unit, start, end) {
  482. if (end != null) { // given start, end
  483. return end.diff(start, unit, true);
  484. }
  485. else if (moment.isDuration(start)) { // given duration
  486. return start.as(unit);
  487. }
  488. else { // given { start, end } range object
  489. return start.end.diff(start.start, unit, true);
  490. }
  491. }
  492. // Intelligently divides a range (specified by a start/end params) by a duration
  493. function divideRangeByDuration(start, end, dur) {
  494. var months;
  495. if (durationHasTime(dur)) {
  496. return (end - start) / dur;
  497. }
  498. months = dur.asMonths();
  499. if (Math.abs(months) >= 1 && isInt(months)) {
  500. return end.diff(start, 'months', true) / months;
  501. }
  502. return end.diff(start, 'days', true) / dur.asDays();
  503. }
  504. // Intelligently divides one duration by another
  505. function divideDurationByDuration(dur1, dur2) {
  506. var months1, months2;
  507. if (durationHasTime(dur1) || durationHasTime(dur2)) {
  508. return dur1 / dur2;
  509. }
  510. months1 = dur1.asMonths();
  511. months2 = dur2.asMonths();
  512. if (
  513. Math.abs(months1) >= 1 && isInt(months1) &&
  514. Math.abs(months2) >= 1 && isInt(months2)
  515. ) {
  516. return months1 / months2;
  517. }
  518. return dur1.asDays() / dur2.asDays();
  519. }
  520. // Intelligently multiplies a duration by a number
  521. function multiplyDuration(dur, n) {
  522. var months;
  523. if (durationHasTime(dur)) {
  524. return moment.duration(dur * n);
  525. }
  526. months = dur.asMonths();
  527. if (Math.abs(months) >= 1 && isInt(months)) {
  528. return moment.duration({ months: months * n });
  529. }
  530. return moment.duration({ days: dur.asDays() * n });
  531. }
  532. // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
  533. function durationHasTime(dur) {
  534. return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
  535. }
  536. function isNativeDate(input) {
  537. return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
  538. }
  539. // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
  540. function isTimeString(str) {
  541. return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
  542. }
  543. /* Logging and Debug
  544. ----------------------------------------------------------------------------------------------------------------------*/
  545. FC.log = function() {
  546. var console = window.console;
  547. if (console && console.log) {
  548. return console.log.apply(console, arguments);
  549. }
  550. };
  551. FC.warn = function() {
  552. var console = window.console;
  553. if (console && console.warn) {
  554. return console.warn.apply(console, arguments);
  555. }
  556. else {
  557. return FC.log.apply(FC, arguments);
  558. }
  559. };
  560. /* General Utilities
  561. ----------------------------------------------------------------------------------------------------------------------*/
  562. var hasOwnPropMethod = {}.hasOwnProperty;
  563. // Merges an array of objects into a single object.
  564. // The second argument allows for an array of property names who's object values will be merged together.
  565. function mergeProps(propObjs, complexProps) {
  566. var dest = {};
  567. var i, name;
  568. var complexObjs;
  569. var j, val;
  570. var props;
  571. if (complexProps) {
  572. for (i = 0; i < complexProps.length; i++) {
  573. name = complexProps[i];
  574. complexObjs = [];
  575. // collect the trailing object values, stopping when a non-object is discovered
  576. for (j = propObjs.length - 1; j >= 0; j--) {
  577. val = propObjs[j][name];
  578. if (typeof val === 'object') {
  579. complexObjs.unshift(val);
  580. }
  581. else if (val !== undefined) {
  582. dest[name] = val; // if there were no objects, this value will be used
  583. break;
  584. }
  585. }
  586. // if the trailing values were objects, use the merged value
  587. if (complexObjs.length) {
  588. dest[name] = mergeProps(complexObjs);
  589. }
  590. }
  591. }
  592. // copy values into the destination, going from last to first
  593. for (i = propObjs.length - 1; i >= 0; i--) {
  594. props = propObjs[i];
  595. for (name in props) {
  596. if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
  597. dest[name] = props[name];
  598. }
  599. }
  600. }
  601. return dest;
  602. }
  603. // Create an object that has the given prototype. Just like Object.create
  604. function createObject(proto) {
  605. var f = function() {};
  606. f.prototype = proto;
  607. return new f();
  608. }
  609. function copyOwnProps(src, dest) {
  610. for (var name in src) {
  611. if (hasOwnProp(src, name)) {
  612. dest[name] = src[name];
  613. }
  614. }
  615. }
  616. // Copies over certain methods with the same names as Object.prototype methods. Overcomes an IE<=8 bug:
  617. // https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug
  618. function copyNativeMethods(src, dest) {
  619. var names = [ 'constructor', 'toString', 'valueOf' ];
  620. var i, name;
  621. for (i = 0; i < names.length; i++) {
  622. name = names[i];
  623. if (src[name] !== Object.prototype[name]) {
  624. dest[name] = src[name];
  625. }
  626. }
  627. }
  628. function hasOwnProp(obj, name) {
  629. return hasOwnPropMethod.call(obj, name);
  630. }
  631. // Is the given value a non-object non-function value?
  632. function isAtomic(val) {
  633. return /undefined|null|boolean|number|string/.test($.type(val));
  634. }
  635. function applyAll(functions, thisObj, args) {
  636. if ($.isFunction(functions)) {
  637. functions = [ functions ];
  638. }
  639. if (functions) {
  640. var i;
  641. var ret;
  642. for (i=0; i<functions.length; i++) {
  643. ret = functions[i].apply(thisObj, args) || ret;
  644. }
  645. return ret;
  646. }
  647. }
  648. function firstDefined() {
  649. for (var i=0; i<arguments.length; i++) {
  650. if (arguments[i] !== undefined) {
  651. return arguments[i];
  652. }
  653. }
  654. }
  655. function htmlEscape(s) {
  656. return (s + '').replace(/&/g, '&amp;')
  657. .replace(/</g, '&lt;')
  658. .replace(/>/g, '&gt;')
  659. .replace(/'/g, '&#039;')
  660. .replace(/"/g, '&quot;')
  661. .replace(/\n/g, '<br />');
  662. }
  663. function stripHtmlEntities(text) {
  664. return text.replace(/&.*?;/g, '');
  665. }
  666. // Given a hash of CSS properties, returns a string of CSS.
  667. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
  668. function cssToStr(cssProps) {
  669. var statements = [];
  670. $.each(cssProps, function(name, val) {
  671. if (val != null) {
  672. statements.push(name + ':' + val);
  673. }
  674. });
  675. return statements.join(';');
  676. }
  677. function capitaliseFirstLetter(str) {
  678. return str.charAt(0).toUpperCase() + str.slice(1);
  679. }
  680. function compareNumbers(a, b) { // for .sort()
  681. return a - b;
  682. }
  683. function isInt(n) {
  684. return n % 1 === 0;
  685. }
  686. // Returns a method bound to the given object context.
  687. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
  688. // different contexts as identical when binding/unbinding events.
  689. function proxy(obj, methodName) {
  690. var method = obj[methodName];
  691. return function() {
  692. return method.apply(obj, arguments);
  693. };
  694. }
  695. // Returns a function, that, as long as it continues to be invoked, will not
  696. // be triggered. The function will be called after it stops being called for
  697. // N milliseconds. If `immediate` is passed, trigger the function on the
  698. // leading edge, instead of the trailing.
  699. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
  700. function debounce(func, wait, immediate) {
  701. var timeout, args, context, timestamp, result;
  702. var later = function() {
  703. var last = +new Date() - timestamp;
  704. if (last < wait) {
  705. timeout = setTimeout(later, wait - last);
  706. }
  707. else {
  708. timeout = null;
  709. if (!immediate) {
  710. result = func.apply(context, args);
  711. context = args = null;
  712. }
  713. }
  714. };
  715. return function() {
  716. context = this;
  717. args = arguments;
  718. timestamp = +new Date();
  719. var callNow = immediate && !timeout;
  720. if (!timeout) {
  721. timeout = setTimeout(later, wait);
  722. }
  723. if (callNow) {
  724. result = func.apply(context, args);
  725. context = args = null;
  726. }
  727. return result;
  728. };
  729. }
  730. // HACK around jQuery's now A+ promises: execute callback synchronously if already resolved.
  731. // thenFunc shouldn't accept args.
  732. // similar to whenResources in Scheduler plugin.
  733. function syncThen(promise, thenFunc) {
  734. // not a promise, or an already-resolved promise?
  735. if (!promise || !promise.then || promise.state() === 'resolved') {
  736. return $.when(thenFunc()); // resolve immediately
  737. }
  738. else if (thenFunc) {
  739. return promise.then(thenFunc);
  740. }
  741. }