gantt_chart.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. * Altair Admin
  3. * Gantt Chart
  4. */
  5. /*! jquery.kinetic - v2.1.0 - 2015-06-23 http://the-taylors.org/jquery.kinetic
  6. * Copyright (c) 2015 Dave Taylor; Licensed MIT */
  7. !function(a){"use strict";var b="kinetic-active";window.requestAnimationFrame||(window.requestAnimationFrame=function(){return window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1e3/60)}}()),a.support=a.support||{},a.extend(a.support,{touch:"ontouchend"in document});var c=function(){return!1},d=function(b,c){return this.settings=c,this.el=b,this.$el=a(b),this._initElements(),this};d.DATA_KEY="kinetic",d.DEFAULTS={cursor:"move",decelerate:!0,triggerHardware:!1,threshold:0,y:!0,x:!0,slowdown:.9,maxvelocity:40,throttleFPS:60,movingClass:{up:"kinetic-moving-up",down:"kinetic-moving-down",left:"kinetic-moving-left",right:"kinetic-moving-right"},deceleratingClass:{up:"kinetic-decelerating-up",down:"kinetic-decelerating-down",left:"kinetic-decelerating-left",right:"kinetic-decelerating-right"}},d.prototype.start=function(b){this.settings=a.extend(this.settings,b),this.velocity=b.velocity||this.velocity,this.velocityY=b.velocityY||this.velocityY,this.settings.decelerate=!1,this._move()},d.prototype.end=function(){this.settings.decelerate=!0},d.prototype.stop=function(){this.velocity=0,this.velocityY=0,this.settings.decelerate=!0,a.isFunction(this.settings.stopped)&&this.settings.stopped.call(this)},d.prototype.detach=function(){this._detachListeners(),this.$el.removeClass(b).css("cursor","")},d.prototype.attach=function(){this.$el.hasClass(b)||(this._attachListeners(this.$el),this.$el.addClass(b).css("cursor",this.settings.cursor))},d.prototype._initElements=function(){this.$el.addClass(b),a.extend(this,{xpos:null,prevXPos:!1,ypos:null,prevYPos:!1,mouseDown:!1,throttleTimeout:1e3/this.settings.throttleFPS,lastMove:null,elementFocused:null}),this.velocity=0,this.velocityY=0,a(document).mouseup(a.proxy(this._resetMouse,this)).click(a.proxy(this._resetMouse,this)),this._initEvents(),this.$el.css("cursor",this.settings.cursor),this.settings.triggerHardware&&this.$el.css({"-webkit-transform":"translate3d(0,0,0)","-webkit-perspective":"1000","-webkit-backface-visibility":"hidden"})},d.prototype._initEvents=function(){var b=this;this.settings.events={touchStart:function(a){var c;b._useTarget(a.target,a)&&(c=a.originalEvent.touches[0],b.threshold=b._threshold(a.target,a),b._start(c.clientX,c.clientY),a.stopPropagation())},touchMove:function(a){var c;b.mouseDown&&(c=a.originalEvent.touches[0],b._inputmove(c.clientX,c.clientY),a.preventDefault&&a.preventDefault())},inputDown:function(a){b._useTarget(a.target,a)&&(b.threshold=b._threshold(a.target,a),b._start(a.clientX,a.clientY),b.elementFocused=a.target,"IMG"===a.target.nodeName&&a.preventDefault(),a.stopPropagation())},inputEnd:function(a){b._useTarget(a.target,a)&&(b._end(),b.elementFocused=null,a.preventDefault&&a.preventDefault())},inputMove:function(a){b.mouseDown&&(b._inputmove(a.clientX,a.clientY),a.preventDefault&&a.preventDefault())},scroll:function(c){a.isFunction(b.settings.moved)&&b.settings.moved.call(b,b.settings),c.preventDefault&&c.preventDefault()},inputClick:function(a){return Math.abs(b.velocity)>0?(a.preventDefault(),!1):void 0},dragStart:function(a){return b._useTarget(a.target,a)&&b.elementFocused?!1:void 0}},this._attachListeners(this.$el,this.settings)},d.prototype._inputmove=function(b,c){{var d=this.$el;this.el}if((!this.lastMove||new Date>new Date(this.lastMove.getTime()+this.throttleTimeout))&&(this.lastMove=new Date,this.mouseDown&&(this.xpos||this.ypos))){var e=b-this.xpos,f=c-this.ypos;if(this.threshold>0){var g=Math.sqrt(e*e+f*f);if(this.threshold>g)return;this.threshold=0}this.elementFocused&&(a(this.elementFocused).blur(),this.elementFocused=null,d.focus()),this.settings.decelerate=!1,this.velocity=this.velocityY=0;var h=this.scrollLeft(),i=this.scrollTop();this.scrollLeft(this.settings.x?h-e:h),this.scrollTop(this.settings.y?i-f:i),this.prevXPos=this.xpos,this.prevYPos=this.ypos,this.xpos=b,this.ypos=c,this._calculateVelocities(),this._setMoveClasses(this.settings.movingClass),a.isFunction(this.settings.moved)&&this.settings.moved.call(this,this.settings)}},d.prototype._calculateVelocities=function(){this.velocity=this._capVelocity(this.prevXPos-this.xpos,this.settings.maxvelocity),this.velocityY=this._capVelocity(this.prevYPos-this.ypos,this.settings.maxvelocity)},d.prototype._end=function(){this.xpos&&this.prevXPos&&this.settings.decelerate===!1&&(this.settings.decelerate=!0,this._calculateVelocities(),this.xpos=this.prevXPos=this.mouseDown=!1,this._move())},d.prototype._useTarget=function(b,c){return a.isFunction(this.settings.filterTarget)?this.settings.filterTarget.call(this,b,c)!==!1:!0},d.prototype._threshold=function(b,c){return a.isFunction(this.settings.threshold)?this.settings.threshold.call(this,b,c):this.settings.threshold},d.prototype._start=function(a,b){this.mouseDown=!0,this.velocity=this.prevXPos=0,this.velocityY=this.prevYPos=0,this.xpos=a,this.ypos=b},d.prototype._resetMouse=function(){this.xpos=!1,this.ypos=!1,this.mouseDown=!1},d.prototype._decelerateVelocity=function(a,b){return 0===Math.floor(Math.abs(a))?0:a*b},d.prototype._capVelocity=function(a,b){var c=a;return a>0?a>b&&(c=b):0-b>a&&(c=0-b),c},d.prototype._setMoveClasses=function(a){var b=this.settings,c=this.$el;c.removeClass(b.movingClass.up).removeClass(b.movingClass.down).removeClass(b.movingClass.left).removeClass(b.movingClass.right).removeClass(b.deceleratingClass.up).removeClass(b.deceleratingClass.down).removeClass(b.deceleratingClass.left).removeClass(b.deceleratingClass.right),this.velocity>0&&c.addClass(a.right),this.velocity<0&&c.addClass(a.left),this.velocityY>0&&c.addClass(a.down),this.velocityY<0&&c.addClass(a.up)},d.prototype._move=function(){var b=(this.$el,this.el),c=this,d=c.settings;d.x&&b.scrollWidth>0?(this.scrollLeft(this.scrollLeft()+this.velocity),Math.abs(this.velocity)>0&&(this.velocity=d.decelerate?c._decelerateVelocity(this.velocity,d.slowdown):this.velocity)):this.velocity=0,d.y&&b.scrollHeight>0?(this.scrollTop(this.scrollTop()+this.velocityY),Math.abs(this.velocityY)>0&&(this.velocityY=d.decelerate?c._decelerateVelocity(this.velocityY,d.slowdown):this.velocityY)):this.velocityY=0,c._setMoveClasses(d.deceleratingClass),a.isFunction(d.moved)&&d.moved.call(this,d),Math.abs(this.velocity)>0||Math.abs(this.velocityY)>0?this.moving||(this.moving=!0,window.requestAnimationFrame(function(){c.moving=!1,c._move()})):c.stop()},d.prototype._getScroller=function(){var b=this.$el;return(this.$el.is("body")||this.$el.is("html"))&&(b=a(window)),b},d.prototype.scrollLeft=function(a){var b=this._getScroller();return"number"!=typeof a?b.scrollLeft():(b.scrollLeft(a),void(this.settings.scrollLeft=a))},d.prototype.scrollTop=function(a){var b=this._getScroller();return"number"!=typeof a?b.scrollTop():(b.scrollTop(a),void(this.settings.scrollTop=a))},d.prototype._attachListeners=function(){var b=this.$el,d=this.settings;a.support.touch&&b.bind("touchstart",d.events.touchStart).bind("touchend",d.events.inputEnd).bind("touchmove",d.events.touchMove),b.mousedown(d.events.inputDown).mouseup(d.events.inputEnd).mousemove(d.events.inputMove),b.click(d.events.inputClick).scroll(d.events.scroll).bind("selectstart",c).bind("dragstart",d.events.dragStart)},d.prototype._detachListeners=function(){var b=this.$el,d=this.settings;a.support.touch&&b.unbind("touchstart",d.events.touchStart).unbind("touchend",d.events.inputEnd).unbind("touchmove",d.events.touchMove),b.unbind("mousedown",d.events.inputDown).unbind("mouseup",d.events.inputEnd).unbind("mousemove",d.events.inputMove),b.unbind("click",d.events.inputClick).unbind("scroll",d.events.scroll).unbind("selectstart",c).unbind("dragstart",d.events.dragStart)},a.Kinetic=d,a.fn.kinetic=function(b,c){return this.each(function(){var e=a(this),f=e.data(d.DATA_KEY),g=a.extend({},d.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data(d.DATA_KEY,f=new d(this,g)),"string"==typeof b&&f[b](c)})}}(window.jQuery||window.Zepto);
  8. /*! Moment Duration Format v1.3.0
  9. * https://github.com/jsmreese/moment-duration-format
  10. * Date: 2014-07-15
  11. *
  12. * Duration format plugin function for the Moment.js library
  13. * http://momentjs.com/
  14. *
  15. * Copyright 2014 John Madhavan-Reese
  16. * Released under the MIT license
  17. */
  18. (function(n,B){function r(a){var b="";a=parseInt(a,10);if(!a||1>a)return b;for(;a;)b+="0",--a;return b}function l(a,b,c){null==a&&(a="");a=""+a;return(c?a:"")+r(b-a.length)+(c?"":a)}function x(a,b){for(var c=a.length;--c;)if(b(a[c]))return a[c]}function t(a,b){var c=0,e=a.length,f;"function"!==typeof b&&(f=b,b=function(a){return a===f});for(;c<e;){if(b(a[c]))return a[c];c+=1}}function h(a,b){var c=0,e=a.length;if(a&&e)for(;c<e&&!1!==b(a[c],c);)c+=1}function k(a,b){var c=0,e=a.length,f=[];if(!a||!e)return f; for(;c<e;)f[c]=b(a[c],c),c+=1;return f}function u(a,b){return k(a,function(a){return a[b]})}function y(a){var b=[];h(a,function(a){a&&b.push(a)});return b}function v(a){var b=[];h(a,function(a){t(b,a)||b.push(a)});return b}function z(a,b){var c=[];h(a,function(a){h(b,function(b){a===b&&c.push(a)})});return v(c)}function w(a,b){var c=[];h(a,function(e,f){if(!b(e))return c=a.slice(f),!1});return c}function A(a,b){var c=a.slice().reverse();return w(c,b).reverse()}function q(a,b){for(var c in b)b.hasOwnProperty(c)&& (a[c]=b[c]);return a}var g;if("function"===typeof require)try{g=require("moment")}catch(a){}!g&&n.moment&&(g=n.moment);if(!g)throw"Moment Duration Format cannot find Moment.js";g.duration.fn.format=function(){var a,b,c,e,f,p;a=[].slice.call(arguments);var d=q({},this.format.defaults),n=g.duration(this);d.duration=this;h(a,function(a){"string"===typeof a||"function"===typeof a?d.template=a:"number"===typeof a?d.precision=a:"[object Object]"===Object.prototype.toString.call(a)&&q(d,a)});c=d.types="[object Array]"=== Object.prototype.toString.call(d.types)?d.types:d.types.split(" ");"function"===typeof d.template&&(d.template=d.template.apply(d));a=new RegExp(k(c,function(a){return d[a].source}).join("|"),"g");e=function(a){return t(c,function(b){return d[b].test(a)})};b=k(d.template.match(a),function(a,b){var c=e(a);return{index:b,length:a.length,token:"escape"===c?a.replace(d.escape,"$1"):a,type:"escape"===c||"general"===c?null:c}},this);f=z(c,v(y(u(b,"type"))));if(!f.length)return u(b,"token").join("");h(f, function(a,c){var m,e,g,l,k;m=n.as(a);e=0<m?Math.floor(m):Math.ceil(m);g=m-e;l=c+1===f.length;k=!c;h(b,function(b){b.type===a&&(q(b,{value:m,wholeValue:e,decimalValue:g,isLeast:l,isMost:k}),k&&null==d.forceLength&&1<b.length&&(d.forceLength=!0))});n.subtract(e,a)});d.trim&&(b=("left"===d.trim?w:A)(b,function(a){return!(a.isLeast||null!=a.type&&a.wholeValue)}));p=!1;"right"===d.trim&&b.reverse();b=k(b,function(a){var b,c;if(!a.type)return a.token;b=a.isLeast&&0>d.precision?(Math.floor(a.wholeValue* Math.pow(10,d.precision))*Math.pow(10,-d.precision)).toString():a.wholeValue.toString();b=b.replace(/^\-/,"");1<a.length&&(p||a.isMost||d.forceLength)&&(b=l(b,a.length));if(a.isLeast&&0<d.precision)switch(c=a.decimalValue.toString().replace(/^\-/,"").split(/\.|e\-/),c.length){case 1:b+="."+l(c[0],d.precision,!0).slice(0,d.precision);break;case 2:b+="."+l(c[1],d.precision,!0).slice(0,d.precision);break;case 3:b+="."+l(r(+c[2]-1)+(c[0]||"0")+c[1],d.precision,!0).slice(0,d.precision);break;default:throw"Moment Duration Format: unable to parse token decimal value."; }a.isMost&&0>a.value&&(b="-"+b);p=!0;return b});"right"===d.trim&&b.reverse();return b.join("")};g.duration.fn.format.defaults={escape:/\[(.+?)\]/,years:/[Yy]+/,months:/M+/,weeks:/[Ww]+/,days:/[Dd]+/,hours:/[Hh]+/,minutes:/m+/,seconds:/s+/,milliseconds:/S+/,general:/.+?/,types:"escape years months weeks days hours minutes seconds milliseconds general",trim:"left",precision:0,forceLength:null,template:function(){var a=this.duration;switch(x(this.types,function(b){return a._data[b]})){case "seconds":return"h:mm:ss"; case "minutes":return"d[d] h:mm";case "hours":return"d[d] h[h]";case "days":return"M[m] d[d]";case "weeks":return"y[y] w[w]";case "months":return"y[y] M[m]";case "years":return"y[y]";default:return"y[y] M[m] d[d] h:mm:ss"}}}})(this);
  19. /*
  20. jQuery.ganttView v.0.8.8
  21. Copyright (c) 2010 JC Grubbs - jc.grubbs@devmynd.com
  22. MIT License Applies
  23. */
  24. (function (jQuery) {
  25. jQuery.fn.ganttView = function () {
  26. var args = Array.prototype.slice.call(arguments);
  27. if (args.length == 1 && typeof(args[0]) == "object") {
  28. build.call(this, args[0]);
  29. }
  30. if (args.length == 2 && typeof(args[0]) == "string") {
  31. handleMethod.call(this, args[0], args[1]);
  32. }
  33. };
  34. function build(options) {
  35. var els = this;
  36. var defaults = {
  37. showWeekends: true,
  38. toggleProjects: true,
  39. cellWidth: 20,
  40. slideWidth: 400,
  41. kineticScroll: true,
  42. startDate: false,
  43. endDate: false,
  44. behavior: {
  45. clickable: false,
  46. draggable: true,
  47. resizable: true
  48. }
  49. };
  50. var opts = jQuery.extend(true, defaults, options);
  51. if (opts.data) {
  52. build();
  53. } else if (opts.dataUrl) {
  54. jQuery.getJSON(opts.dataUrl, function (data) { opts.data = data; build(); });
  55. }
  56. function build() {
  57. var minDays = Math.floor((opts.slideWidth / opts.cellWidth) + 5);
  58. var startEnd = DateUtils.getBoundaryDatesFromData(opts.data, minDays);
  59. opts.start = opts.startDate ? moment(opts.startDate,"MM/DD/YYYY")._d : startEnd[0];
  60. opts.end = opts.endDate ? moment(opts.endDate,"MM/DD/YYYY")._d : startEnd[1];
  61. els.each(function () {
  62. var container = jQuery(this);
  63. var div = jQuery("<div>", { "class": "ganttview" });
  64. new Chart(div, opts).render();
  65. container.append(div);
  66. var w = jQuery("div.ganttview-vtheader", container).outerWidth() +
  67. jQuery("div.ganttview-slide-container", container).outerWidth();
  68. new Behavior(container, opts).apply();
  69. });
  70. }
  71. }
  72. function handleMethod(method, value) {
  73. if (method == "setSlideWidth") {
  74. var div = $("div.ganttview", this);
  75. div.each(function () {
  76. var vtWidth = $("div.ganttview-vtheader", div).outerWidth();
  77. $(div).width(vtWidth + value + 1);
  78. $("div.ganttview-slide-container", this).width(value);
  79. });
  80. }
  81. }
  82. var Chart = function(div, opts) {
  83. function render() {
  84. addVtHeader(div, opts.data);
  85. var slideDiv = jQuery("<div>", {
  86. "class": "ganttview-slide-container"
  87. });
  88. dates = getDates(opts.start, opts.end);
  89. addHzHeader(slideDiv, dates, opts.cellWidth, opts.showWeekends);
  90. addGrid(slideDiv, opts.data, dates, opts.cellWidth, opts.showWeekends);
  91. addBlockContainers(slideDiv, opts.data);
  92. addBlocks(slideDiv, opts.data, opts.cellWidth, opts.start);
  93. div.append(slideDiv);
  94. jQuery(div).find('.ganttview-blocks').width(slideDiv.find('.ganttview-grid').width());
  95. applyLastClass(div.parent());
  96. if(opts.toggleProjects) {
  97. toggleProjects(div);
  98. }
  99. if(opts.kineticScroll && !Modernizr.touch) {
  100. kineticScroll(div);
  101. }
  102. }
  103. // Creates a 3 dimensional array [year][month][day] of every day
  104. // between the given start and end dates
  105. function getDates(start, end) {
  106. var dates = [];
  107. dates[start.getFullYear()] = [];
  108. dates[start.getFullYear()][start.getMonth()] = [start];
  109. var last = start;
  110. while (moment(end).isAfter(last)) {
  111. var next = moment(last).add(1,'days')._d;
  112. if (!dates[next.getFullYear()]) { dates[next.getFullYear()] = []; }
  113. if (!dates[next.getFullYear()][next.getMonth()]) {
  114. dates[next.getFullYear()][next.getMonth()] = [];
  115. }
  116. dates[next.getFullYear()][next.getMonth()].push(next);
  117. last = next;
  118. }
  119. return dates;
  120. }
  121. function addVtHeader(div, data) {
  122. var headerDiv = jQuery("<div>", { "class": "ganttview-vtheader" });
  123. for (var i = 0; i < data.length; i++) {
  124. var itemDiv = jQuery("<div>", { "class": "ganttview-vtheader-group" });
  125. itemDiv.append(jQuery("<div>", {
  126. "class": "ganttview-vtheader-group-name",
  127. "id": "groupId_" + i
  128. }).append(data[i].name).append('<span/>'));
  129. var seriesDiv = jQuery("<div>", { "class": "ganttview-vtheader-series" });
  130. for (var j = 0; j < data[i].series.length; j++) {
  131. var seriesRow = jQuery("<div>", { "class": "ganttview-vtheader-series-row" });
  132. if((data[i].series[j].sub_series)) {
  133. var series_content = jQuery("<div>", { "class": "series-content" }),
  134. series_dates = jQuery("<div>", { "class": "series-dates" });
  135. series_users = jQuery("<div>", { "class": "series-users" });
  136. series_content.append( '<div class="series-name">' +
  137. data[i].series[j].name +
  138. '</div>');
  139. for (var k = 0; k < data[i].series[j].sub_series.length; k++) {
  140. var moreItems = k > 0 ? '<span class="date-sep">|</span>' : '',
  141. sub_serie = data[i].series[j].sub_series[k];
  142. if(sub_serie.user_avatar) {
  143. var series_user = jQuery("<div>", { "class": "series-user" }),
  144. user_name = sub_serie.user_name;
  145. user_avatar = sub_serie.user_avatar;
  146. series_user.append('<span><img src="'+ user_avatar +'"/></span>');
  147. series_users.append(series_user);
  148. seriesRow.append(series_users);
  149. }
  150. series_dates.append( function() {
  151. return moreItems +
  152. moment(sub_serie.start,"MM/DD/YYYY").format('D MMM') +
  153. " - " +
  154. moment(sub_serie.end,"MM/DD/YYYY").format('D MMM')
  155. });
  156. series_content.append(series_dates);
  157. seriesRow.append(series_content);
  158. }
  159. } else {
  160. seriesRow.append(
  161. function() {
  162. var avatar =
  163. (data[i].series[j].user_avatar)
  164. ? "<div class='series-user'><span><img src='"+ data[i].series[j].user_avatar +"' /></span></div>"
  165. : "";
  166. return avatar +
  167. "<div class='series-content'>" +
  168. '<div class="series-name">' +
  169. data[i].series[j].name +
  170. '</div>' +
  171. "<div class='series-dates'>" +
  172. moment(data[i].series[j].start,"MM/DD/YYYY").format('D MMM') +
  173. " - " +
  174. moment(data[i].series[j].end,"MM/DD/YYYY").format('D MMM') +
  175. "</div>" +
  176. "</div>"
  177. }
  178. );
  179. }
  180. seriesDiv.append(seriesRow);
  181. }
  182. itemDiv.append(seriesDiv);
  183. headerDiv.append(itemDiv);
  184. }
  185. div.append(headerDiv);
  186. }
  187. function addHzHeader(div, dates, cellWidth, showWeekends) {
  188. var headerDiv = jQuery("<div>", { "class": "ganttview-hzheader" });
  189. var monthsDiv = jQuery("<div>", { "class": "ganttview-hzheader-months" });
  190. var daysDiv = jQuery("<div>", { "class": "ganttview-hzheader-days" });
  191. var totalW = 0;
  192. for (var y in dates) {
  193. for (var m in dates[y]) {
  194. var w = dates[y][m].length * cellWidth;
  195. totalW = totalW + w;
  196. monthsDiv.append(jQuery("<div>", {
  197. "class": "ganttview-hzheader-month",
  198. "css": { "width": (w - 1) + "px" }
  199. }).append(moment(parseInt(m)+1,"M").format('MMMM') + " " + y));
  200. for (var d in dates[y][m]) {
  201. var headerDay = jQuery("<div>", { "class": "ganttview-hzheader-day" });
  202. if (DateUtils.isWeekend(dates[y][m][d]) && showWeekends) {
  203. headerDay.addClass("ganttview-weekend");
  204. }
  205. daysDiv.append( headerDay.append(dates[y][m][d].getDate()) );
  206. }
  207. }
  208. }
  209. monthsDiv.css("width", totalW + "px");
  210. daysDiv.css("width", totalW + "px");
  211. headerDiv.append(monthsDiv).append(daysDiv);
  212. div.append(headerDiv);
  213. }
  214. function addGrid(div, data, dates, cellWidth, showWeekends) {
  215. var gridDiv = jQuery("<div>", { "class": "ganttview-grid" });
  216. var rowDiv = jQuery("<div>", { "class": "ganttview-grid-row" });
  217. for (var y in dates) {
  218. for (var m in dates[y]) {
  219. for (var d in dates[y][m]) {
  220. var cellDiv = jQuery("<div>", { "class": "ganttview-grid-row-cell" });
  221. if (DateUtils.isWeekend(dates[y][m][d]) && showWeekends) {
  222. cellDiv.addClass("ganttview-weekend");
  223. }
  224. rowDiv.append(cellDiv);
  225. }
  226. }
  227. }
  228. var w = jQuery("div.ganttview-grid-row-cell", rowDiv).length * cellWidth;
  229. rowDiv.css("width", w + "px");
  230. gridDiv.css("width", w + "px");
  231. for (var i = 0; i < data.length; i++) {
  232. gridDiv.append(jQuery("<div>", {
  233. "class": "ganttview-grid-spacer",
  234. "data-click-target": "groupId_" + i
  235. }));
  236. for (var j = 0; j < data[i].series.length; j++) {
  237. gridDiv.append(rowDiv.clone().addClass('groupId_' + i));
  238. }
  239. }
  240. div.append(gridDiv);
  241. }
  242. function addBlockContainers(div, data) {
  243. var blocksDiv = jQuery("<div>", {
  244. "class": "ganttview-blocks"
  245. });
  246. for (var i = 0; i < data.length; i++) {
  247. blocksDiv.append(jQuery("<div>", { "class": "ganttview-block-spacer" }));
  248. for (var j = 0; j < data[i].series.length; j++) {
  249. blocksDiv.append(jQuery("<div>", {
  250. "class": "ganttview-block-container groupId_" + i
  251. }));
  252. }
  253. }
  254. div.append(blocksDiv);
  255. }
  256. function addBlocks(div, data, cellWidth, start) {
  257. var rows = jQuery("div.ganttview-blocks div.ganttview-block-container", div);
  258. var rowIdx = 0;
  259. for (var i = 0; i < data.length; i++) {
  260. for (var j = 0; j < data[i].series.length; j++) {
  261. if(data[i].series[j].sub_series) {
  262. var sub_series = data[i].series[j].sub_series;
  263. var $sub_series_name = (data[i].series[j].name).replace(/(<([^>]+)>)/ig," ");
  264. $.each(sub_series, function($key,$value) {
  265. var size = DateUtils.daysBetween($value.start, $value.end) + 1;
  266. var offset = DateUtils.daysBetween(start, $value.start);
  267. var user_name = $value.user_name ? ' (' + $value.user_name + ')' : '';
  268. var block = jQuery("<div>", {
  269. "class": "ganttview-block",
  270. "title": $sub_series_name + user_name,
  271. "css": {
  272. "width": ((size * cellWidth) - 9) + "px",
  273. "left": ((offset * cellWidth) + 3) + "px"
  274. }
  275. });
  276. addBlockData(block, data[i], sub_series[$key]);
  277. if ($value.color) {
  278. block.css("background-color", $value.color);
  279. }
  280. var title = $value.title ? $value.link ? '<a href="'+$value.link+'" title="'+$value.link+'">' + $value.title + '</a>': $value.title : moment.duration(size,'days').format();
  281. if($value.link) {
  282. block.append(jQuery("<div>", { "class": "ganttview-block-text" }).html( title ));
  283. } else {
  284. block.append(jQuery("<div>", { "class": "ganttview-block-text" }).text( title ));
  285. }
  286. jQuery(rows[rowIdx]).append(block);
  287. });
  288. } else {
  289. var series = data[i].series[j];
  290. var $series_name = (series.name).replace(/(<([^>]+)>)/ig," ");
  291. var size = DateUtils.daysBetween(series.start, series.end) + 1;
  292. var offset = DateUtils.daysBetween(start, series.start);
  293. var block = jQuery("<div>", {
  294. "class": "ganttview-block",
  295. "title": $series_name,
  296. "css": {
  297. "width": ((size * cellWidth) - 9) + "px",
  298. "left": ((offset * cellWidth) + 3) + "px"
  299. }
  300. });
  301. addBlockData(block, data[i], series);
  302. if (data[i].series[j].color) {
  303. block.css("background-color", data[i].series[j].color);
  304. }
  305. var title = series.title ? series.link ? '<a href="'+series.link+'" title="'+series.link+'">' + series.title + '</a>': series.title : moment.duration(size,'days').format();
  306. if(series.link) {
  307. block.append(jQuery("<div>", { "class": "ganttview-block-text" }).html( title ));
  308. } else {
  309. block.append(jQuery("<div>", { "class": "ganttview-block-text" }).text( title ));
  310. }
  311. jQuery(rows[rowIdx]).append(block);
  312. }
  313. rowIdx++;
  314. }
  315. }
  316. jQuery(".ganttview-blocks").css({
  317. width: $(div).width()
  318. });
  319. }
  320. function addBlockData(block, data, series) {
  321. // This allows custom attributes to be added to the series data objects
  322. // and makes them available to the 'data' argument of click, resize, and drag handlers
  323. var blockData = { name: data.name };
  324. jQuery.extend(blockData, series);
  325. block.data("block-data", blockData);
  326. }
  327. function applyLastClass(div) {
  328. jQuery("div.ganttview-grid-row div.ganttview-grid-row-cell:last-child", div).addClass("last");
  329. jQuery("div.ganttview-hzheader-days div.ganttview-hzheader-day:last-child", div).addClass("last");
  330. jQuery("div.ganttview-hzheader-months div.ganttview-hzheader-month:last-child", div).addClass("last");
  331. }
  332. function toggleProjects(div) {
  333. $('div.ganttview-vtheader-group-name',div).addClass('toggle_enabled').on('click', function() {
  334. $thisId = $(this).attr('id');
  335. if(!$(this).hasClass('projectHidden')) {
  336. $(this)
  337. .addClass('projectHidden')
  338. .next('div')
  339. .children()
  340. .velocity("slideUp",{
  341. duration: 180,
  342. easing: easing_swiftOut
  343. });
  344. $('.ganttview-block-container.'+$thisId).hide();
  345. $('.ganttview-grid-row.'+$thisId)
  346. .velocity("slideUp",{
  347. duration: 180,
  348. easing: easing_swiftOut
  349. });
  350. } else {
  351. $(this)
  352. .removeClass('projectHidden')
  353. .next('div')
  354. .children()
  355. .velocity("slideDown",{
  356. duration: 180,
  357. easing: easing_swiftOut
  358. });
  359. $('.ganttview-block-container.'+$thisId).show();
  360. $('.ganttview-grid-row.'+$thisId)
  361. .velocity("slideDown",{
  362. duration: 180,
  363. easing: easing_swiftOut
  364. });
  365. }
  366. });
  367. $('div.ganttview-grid-spacer',div).on('click', function() {
  368. $('#'+$(this).attr('data-click-target')).click()
  369. });
  370. }
  371. function kineticScroll(div) {
  372. var container = jQuery("div.ganttview-slide-container", div);
  373. $(container).kinetic({
  374. y: false,
  375. filterTarget: function(target, e){
  376. return !($(target).closest(".ganttview-block").length || $(target).closest(".ganttview-grid-spacer").length);
  377. }
  378. });
  379. }
  380. return {
  381. render: render
  382. };
  383. };
  384. var Behavior = function (div, opts) {
  385. function apply() {
  386. if (opts.behavior.clickable) {
  387. bindBlockClick(div, opts.behavior.onClick);
  388. }
  389. if (opts.behavior.resizable) {
  390. bindBlockResize(div, opts.cellWidth, opts.start, opts.behavior.onResize);
  391. }
  392. if (opts.behavior.draggable) {
  393. bindBlockDrag(div, opts.cellWidth, opts.start, opts.behavior.onDrag);
  394. }
  395. }
  396. function bindBlockClick(div, callback) {
  397. jQuery("div.ganttview-block", div).on("click", function () {
  398. if (callback) { callback(jQuery(this).data("block-data")); }
  399. });
  400. }
  401. function bindBlockResize(div, cellWidth, startDate, callback) {
  402. jQuery("div.ganttview-block", div).resizable({
  403. grid: cellWidth,
  404. handles: "e,w",
  405. stop: function () {
  406. var block = jQuery(this);
  407. updateDataAndPosition(div, block, cellWidth, startDate);
  408. if (callback) { callback(block.data("block-data")); }
  409. }
  410. });
  411. }
  412. function bindBlockDrag(div, cellWidth, startDate, callback) {
  413. jQuery("div.ganttview-block", div).draggable({
  414. axis: "x",
  415. grid: [cellWidth, cellWidth],
  416. containment: "parent",
  417. stop: function () {
  418. var block = jQuery(this);
  419. updateDataAndPosition(div, block, cellWidth, startDate);
  420. if (callback) { callback(block.data("block-data")); }
  421. }
  422. });
  423. }
  424. function updateDataAndPosition(div, block, cellWidth, startDate) {
  425. var container = jQuery("div.ganttview-slide-container", div);
  426. var scroll = container.scrollLeft();
  427. var offset = block.offset().left - container.offset().left - 1 + scroll;
  428. // Set new start date
  429. var daysFromStart = Math.round(offset / cellWidth);
  430. var newStart = moment(startDate).add(daysFromStart,'days');
  431. block.data("block-data").start = newStart;
  432. // Set new end date
  433. var width = block.outerWidth();
  434. var numberOfDays = Math.round(width / cellWidth) - 1;
  435. block.data("block-data").end = moment(newStart).add(numberOfDays,'days');
  436. if(!block.data("block-data").title) {
  437. jQuery("div.ganttview-block-text", block).text( moment.duration(numberOfDays+1,'days').format());
  438. }
  439. // Remove top and left properties to avoid incorrect block positioning,
  440. // set position to relative to keep blocks relative to scrollbar when scrolling
  441. block.css("top", "").css("left", offset + "px");
  442. }
  443. return {
  444. apply: apply
  445. };
  446. };
  447. var DateUtils = {
  448. daysBetween: function (start, end) {
  449. if (!start || !end) { return 0; }
  450. start = Date.parse(start); end = Date.parse(end);
  451. if (moment(start)._d.getYear() == 1901 || moment(end)._d.getYear() == 8099) { return 0; }
  452. return moment(end).diff(moment(start),'days');
  453. },
  454. isWeekend: function (date) {
  455. return date.getDay() % 6 == 0;
  456. },
  457. getBoundaryDatesFromData: function (data, minDays) {
  458. var minStart = new Date(); maxEnd = new Date();
  459. for (var i = 0; i < data.length; i++) {
  460. for (var j = 0; j < data[i].series.length; j++) {
  461. var start = Date.parse(data[i].series[j].start);
  462. var end = Date.parse(data[i].series[j].end);
  463. if (i == 0 && j == 0) { minStart = start; maxEnd = end; }
  464. if (moment(minStart).isAfter(start)) { minStart = start; }
  465. if (moment(maxEnd).isBefore(end)) { maxEnd = end; }
  466. }
  467. }
  468. // Insure that the width of the chart is at least the slide width to avoid empty
  469. // whitespace to the right of the grid
  470. if (moment(maxEnd).diff(minStart,'days') < minDays) {
  471. maxEnd = moment(minStart).add(minDays, 'days');
  472. }
  473. return [moment(minStart)._d, moment(maxEnd)._d];
  474. }
  475. };
  476. })(jQuery);