// jQuery Gantt Chart // ================== // Basic usage: // $(".selector").gantt({ // source: "ajax/data.json", // scale: "weeks", // minScale: "weeks", // maxScale: "months", // onItemClick: function(data) { // alert("Item clicked - show some details"); // }, // onAddClick: function(dt, rowId) { // alert("Empty space clicked - add an item!"); // }, // onRender: function() { // console.log("chart rendered"); // } // }); // /*jshint shadow:true, unused:false, laxbreak:true, evil:true*/ /*globals jQuery, alert*/ (function ($) { "use strict"; $.fn.gantt = function (options) { var cookieKey = "jquery.fn.gantt"; var scales = ["hours", "days", "weeks", "months"]; //Default settings var settings = { source: [], itemsPerPage: 7, months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], dow: ["S", "M", "T", "W", "T", "F", "S"], startPos: new Date(), navigate: "buttons", scale: "days", useCookie: false, maxScale: "months", minScale: "hours", waitText: "Please wait...", onItemClick: function (data) { return; }, onAddClick: function (data) { return; }, onRender: function() { return; }, onDataLoadFailed: function(data) { return; }, scrollToToday: true }; /** * Extend options with default values */ if (options) { $.extend(settings, options); } // can't use cookie if don't have `$.cookie` settings.useCookie = settings.useCookie && $.isFunction($.cookie); // custom selector `:findday` used to match on specified day in ms. // // The selector is passed a date in ms and elements are added to the // selection filter if the element date matches, as determined by the // id attribute containing a parsable date in ms. $.extend($.expr[":"], { findday: function (a, i, m) { var cd = new Date(parseInt(m[3], 10)); var id = $(a).attr("id"); id = id ? id : ""; var si = id.indexOf("-") + 1; var ed = new Date(parseInt(id.substring(si, id.length), 10)); cd = new Date(cd.getFullYear(), cd.getMonth(), cd.getDate()); ed = new Date(ed.getFullYear(), ed.getMonth(), ed.getDate()); return cd.getTime() === ed.getTime(); } }); // custom selector `:findweek` used to match on specified week in ms. $.extend($.expr[":"], { findweek: function (a, i, m) { var cd = new Date(parseInt(m[3], 10)); var id = $(a).attr("id"); id = id ? id : ""; var si = id.indexOf("-") + 1; cd = cd.getFullYear() + "-" + cd.getDayForWeek().getWeekOfYear(); var ed = id.substring(si, id.length); return cd === ed; } }); // custom selector `:findmonth` used to match on specified month in ms. $.extend($.expr[":"], { findmonth: function (a, i, m) { var cd = new Date(parseInt(m[3], 10)); cd = cd.getFullYear() + "-" + cd.getMonth(); var id = $(a).attr("id"); id = id ? id : ""; var si = id.indexOf("-") + 1; var ed = id.substring(si, id.length); return cd === ed; } }); // Date prototype helpers // ====================== // `getWeekId` returns a string in the form of 'dh-YYYY-WW', where WW is // the week # for the year. // It is used to add an id to the week divs Date.prototype.getWeekId = function () { var y = this.getFullYear(); var w = this.getDayForWeek().getWeekOfYear(); var m = this.getMonth(); if (m === 11 && w === 1) { y++; } return 'dh-' + y + "-" + w; }; // `getRepDate` returns the seconds since the epoch for a given date // depending on the active scale Date.prototype.getRepDate = function () { switch (settings.scale) { case "hours": return this.getTime(); case "weeks": return this.getDayForWeek().getTime(); case "months": return new Date(this.getFullYear(), this.getMonth(), 1).getTime(); default: return this.getTime(); } }; // `getDayOfYear` returns the day number for the year Date.prototype.getDayOfYear = function () { var fd = new Date(this.getFullYear(), 0, 0); var sd = new Date(this.getFullYear(), this.getMonth(), this.getDate()); return Math.ceil((sd - fd) / 86400000); }; // `getWeekOfYear` returns the week number for the year Date.prototype.getWeekOfYear = function () { var ys = new Date(this.getFullYear(), 0, 1); var sd = new Date(this.getTime()); // Find Thursday of this week starting on Monday sd.setDate(sd.getDate() + 4 - (sd.getDay() || 7)); return Math.floor(Math.round((sd - ys) / 86400000) / 7) + 1; }; // `getDaysInMonth` returns the number of days in a month Date.prototype.getDaysInMonth = function () { return 32 - new Date(this.getFullYear(), this.getMonth(), 32).getDate(); }; // `hasWeek` returns `true` if the date resides on a week boundary // **????????????????? Don't know if this is true** Date.prototype.hasWeek = function () { var df = new Date(this.valueOf()); df.setDate(df.getDate() - df.getDay()); var dt = new Date(this.valueOf()); dt.setDate(dt.getDate() + (6 - dt.getDay())); if (df.getMonth() === dt.getMonth()) { return true; } else { return (df.getMonth() === this.getMonth() && dt.getDate() < 4) || (df.getMonth() !== this.getMonth() && dt.getDate() >= 4); } }; // `getDayForWeek` returns the Date object for the starting date of // the week # for the year Date.prototype.getDayForWeek = function () { var df = new Date(this.valueOf()); df.setDate(df.getDate() - df.getDay()); var dt = new Date(this.valueOf()); dt.setDate(dt.getDate() + (6 - dt.getDay())); if ((df.getMonth() === dt.getMonth()) || (df.getMonth() !== dt.getMonth() && dt.getDate() >= 4)) { return new Date(dt.setDate(dt.getDate() - 3)); } else { return new Date(df.setDate(df.getDate() + 3)); } }; // fixes https://github.com/taitems/jQuery.Gantt/issues/62 function ktkGetNextDate(currentDate, scaleStep) { for(var minIncrements = 1;; minIncrements++) { var nextDate = new Date(currentDate); nextDate.setHours(currentDate.getHours() + scaleStep * minIncrements); if (nextDate.getTime() !== currentDate.getTime()) { return nextDate; } // If code reaches here, it's because current didn't really increment (invalid local time) because of daylight-saving adjustments // => retry adding 2, 3, 4 hours, and so on (until nextDate > current) } } // Grid management // =============== // Core object is responsible for navigation and rendering var core = { // Return the element whose topmost point lies under the given point // Normalizes for IE elementFromPoint: function (x, y) { if (!$.support.boxModel) { x -= $(document).scrollLeft(); y -= $(document).scrollTop(); } else { x -= window.pageXOffset; y -= window.pageYOffset; } return document.elementFromPoint(x, y); }, // **Create the chart** create: function (element) { // Initialize data with a json object or fetch via an xhr // request depending on `settings.source` if (typeof settings.source !== "string") { element.data = settings.source; core.init(element); } else { $.getJSON(settings.source, function (jsData) { element.data = jsData; core.init(element); }); } }, // **Setup the initial view** // Here we calculate the number of rows, pages and visible start // and end dates once the data is ready init: function (element) { try { element.rowsNum = element.data.length; element.pageCount = Math.ceil(element.rowsNum / settings.itemsPerPage); element.rowsOnLastPage = element.rowsNum - (Math.floor(element.rowsNum / settings.itemsPerPage) * settings.itemsPerPage); element.dateStart = tools.getMinDate(element); element.dateEnd = tools.getMaxDate(element); /* core.render(element); */ core.waitToggle(element, true, function () { core.render(element); }); } catch(e) { if ( element.data === null || (typeof element.data === 'object' && element.data.length === 0 ) ) settings.onDataLoadFailed($(this).data("dataObj")); } }, // **Render the grid** render: function (element) { var content = $('
'); var $leftPanel = core.leftPanel(element); content.append($leftPanel); var $rightPanel = core.rightPanel(element, $leftPanel); var mLeft, hPos; content.append($rightPanel); content.append(core.navigation(element)); var $dataPanel = $rightPanel.find(".dataPanel"); element.gantt = $('
').append(content); $(element).html(element.gantt); element.scrollNavigation.panelMargin = parseInt($dataPanel.css("margin-left").replace("px", ""), 10); element.scrollNavigation.panelMaxPos = ($dataPanel.width() - $rightPanel.width()); element.scrollNavigation.canScroll = ($dataPanel.width() > $rightPanel.width()); core.markNow(element); core.fillData(element, $dataPanel, $leftPanel); // Set a cookie to record current position in the view if (settings.useCookie) { var sc = $.cookie(this.cookieKey + "ScrollPos"); if (sc) { element.hPosition = sc; } } // Scroll the grid to today's date if (settings.scrollToToday) { core.navigateTo(element, 'now'); core.scrollPanel(element, 0); // or, scroll the grid to the left most date in the panel } else { if (element.hPosition !== 0) { if (element.scaleOldWidth) { mLeft = ($dataPanel.width() - $rightPanel.width()); hPos = mLeft * element.hPosition / element.scaleOldWidth; hPos = hPos > 0 ? 0 : hPos; $dataPanel.css({ "margin-left": hPos + "px" }); element.scrollNavigation.panelMargin = hPos; element.hPosition = hPos; element.scaleOldWidth = null; } else { $dataPanel.css({ "margin-left": element.hPosition + "px" }); element.scrollNavigation.panelMargin = element.hPosition; } core.repositionLabel(element); } } $dataPanel.css({ height: $leftPanel.height() }); core.waitToggle(element, false); settings.onRender(); }, // Create and return the left panel with labels leftPanel: function (element) { /* Left panel */ var ganttLeftPanel = $('
') .append($('
') .css("height", tools.getCellSize() * element.headerRows + "px") .css("width", "100%")); var entries = []; $.each(element.data, function (i, entry) { if (i >= element.pageNum * settings.itemsPerPage && i < (element.pageNum * settings.itemsPerPage + settings.itemsPerPage)) { entries.push('
'); entries.push('' + (entry.name || '') + ''); entries.push('
'); if (entry.desc) { entries.push('
'); entries.push('' + entry.desc + ''); entries.push('
'); } } }); ganttLeftPanel.append(entries.join("")); return ganttLeftPanel; }, // Create and return the data panel element dataPanel: function (element, width) { var dataPanel = $('
'); // Handle mousewheel events for scrolling the data panel var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"; if (document.attachEvent) { element.attachEvent("on" + mousewheelevt, function (e) { core.wheelScroll(element, e); }); } else if (document.addEventListener) { element.addEventListener(mousewheelevt, function (e) { core.wheelScroll(element, e); }, false); } // Handle click events and dispatch to registered `onAddClick` // function dataPanel.click(function (e) { e.stopPropagation(); var corrX/* <- never used? */, corrY; var leftpanel = $(element).find(".fn-gantt .leftPanel"); var datapanel = $(element).find(".fn-gantt .dataPanel"); switch (settings.scale) { case "weeks": corrY = tools.getCellSize() * 2; break; case "months": corrY = tools.getCellSize(); break; case "hours": corrY = tools.getCellSize() * 4; break; case "days": corrY = tools.getCellSize() * 3; break; default: corrY = tools.getCellSize() * 2; break; } /* Adjust, so get middle of elm corrY -= Math.floor(tools.getCellSize() / 2); */ // Find column where click occurred var col = core.elementFromPoint(e.pageX, datapanel.offset().top + corrY); // Was the label clicked directly? if (col.className === "fn-label") { col = $(col.parentNode); } else { col = $(col); } var dt = col.attr("repdate"); // Find row where click occurred var row = core.elementFromPoint(leftpanel.offset().left + leftpanel.width() - 10, e.pageY); // Was the lable clicked directly? if (row.className.indexOf("fn-label") === 0) { row = $(row.parentNode); } else { row = $(row); } var rowId = row.data().id; // Dispatch user registered function with the DateTime in ms // and the id if the clicked object is a row settings.onAddClick(dt, rowId); }); return dataPanel; }, // Creates and return the right panel containing the year/week/day // header rightPanel: function (element, leftPanel /* <- never used? */) { var range = null; // Days of the week have a class of one of // `sn` (Sunday), `sa` (Saturday), or `wd` (Weekday) var dowClass = ["sn", "wd", "wd", "wd", "wd", "wd", "sa"]; //TODO: was someone planning to allow styles to stretch to the bottom of the chart? //var gridDowClass = [" sn", "", "", "", "", "", " sa"]; var yearArr = ['
']; var daysInYear = 0; var monthArr = ['
']; var daysInMonth = 0; var dayArr = []; var hoursInDay = 0; var dowArr = []; var horArr = []; var today = new Date(); today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); var holidays = settings.holidays ? settings.holidays.join() : ''; // Setup the headings based on the chosen `settings.scale` switch (settings.scale) { // **Hours** case "hours": range = tools.parseTimeRange(element.dateStart, element.dateEnd, element.scaleStep); var year = range[0].getFullYear(); var month = range[0].getMonth(); var day = range[0]; for (var i = 0, len = range.length; i < len; i++) { var rday = range[i]; // Fill years var rfy = rday.getFullYear(); if (rfy !== year) { yearArr.push( ('
' + year + '
')); year = rfy; daysInYear = 0; } daysInYear++; // Fill months var rm = rday.getMonth(); if (rm !== month) { monthArr.push( ('
' + settings.months[month] + '
')); month = rm; daysInMonth = 0; } daysInMonth++; // Fill days & hours var rgetDay = rday.getDay(); var getDay = day.getDay(); var day_class = dowClass[rgetDay]; var getTime = day.getTime(); if (holidays.indexOf((new Date(rday.getFullYear(), rday.getMonth(), rday.getDate())).getTime()) > -1) { day_class = "holiday"; } if (rgetDay !== getDay) { var day_class2 = (today - day === 0) ? ' today' : (holidays.indexOf(getTime) > -1) ? "holiday" : dowClass[getDay]; dayArr.push('
' + '
' + day.getDate() + '
'); dowArr.push('
' + '
' + settings.dow[getDay] + '
'); day = rday; hoursInDay = 0; } hoursInDay++; horArr.push('
' + rday.getHours() + '
'); } // Last year yearArr.push( '
' + year + '
'); // Last month monthArr.push( '
' + settings.months[month] + '
'); var day_class = dowClass[day.getDay()]; if (holidays.indexOf((new Date(day.getFullYear(), day.getMonth(), day.getDate())).getTime()) > -1) { day_class = "holiday"; } dayArr.push('
' + '
' + day.getDate() + '
'); dowArr.push('
' + '
' + settings.dow[day.getDay()] + '
'); var dataPanel = core.dataPanel(element, range.length * tools.getCellSize()); // Append panel elements dataPanel.append(yearArr.join("")); dataPanel.append(monthArr.join("")); dataPanel.append($('
').html(dayArr.join(""))); dataPanel.append($('
').html(dowArr.join(""))); dataPanel.append($('
').html(horArr.join(""))); break; // **Weeks** case "weeks": range = tools.parseWeeksRange(element.dateStart, element.dateEnd); yearArr = ['
']; monthArr = ['
']; var year = range[0].getFullYear(); var month = range[0].getMonth(); var day = range[0]; for (var i = 0, len = range.length; i < len; i++) { var rday = range[i]; // Fill years if (rday.getFullYear() !== year) { yearArr.push( ('
' + year + '
')); year = rday.getFullYear(); daysInYear = 0; } daysInYear++; // Fill months if (rday.getMonth() !== month) { monthArr.push( ('
' + settings.months[month] + '
')); month = rday.getMonth(); daysInMonth = 0; } daysInMonth++; // Fill weeks dayArr.push('
' + '
' + rday.getWeekOfYear() + '
'); } // Last year yearArr.push( '
' + year + '
'); // Last month monthArr.push( '
' + settings.months[month] + '
'); var dataPanel = core.dataPanel(element, range.length * tools.getCellSize()); dataPanel.append(yearArr.join("") + monthArr.join("") + dayArr.join("") + (dowArr.join(""))); break; // **Months** case 'months': range = tools.parseMonthsRange(element.dateStart, element.dateEnd); var year = range[0].getFullYear(); var month = range[0].getMonth(); var day = range[0]; for (var i = 0, len = range.length; i < len; i++) { var rday = range[i]; // Fill years if (rday.getFullYear() !== year) { yearArr.push( ('
' + year + '
')); year = rday.getFullYear(); daysInYear = 0; } daysInYear++; monthArr.push('
' + (1 + rday.getMonth()) + '
'); } // Last year yearArr.push( '
' + year + '
'); // Last month monthArr.push( '
' + settings.months[month] + '
'); var dataPanel = core.dataPanel(element, range.length * tools.getCellSize()); // Append panel elements dataPanel.append(yearArr.join("")); dataPanel.append(monthArr.join("")); dataPanel.append($('
').html(dayArr.join(""))); dataPanel.append($('
').html(dowArr.join(""))); break; // **Days (default)** default: range = tools.parseDateRange(element.dateStart, element.dateEnd); var dateBefore = ktkGetNextDate(range[0], -1); var year = dateBefore.getFullYear(); var month = dateBefore.getMonth(); var day = dateBefore; // <- never used? for (var i = 0, len = range.length; i < len; i++) { var rday = range[i]; // Fill years if (rday.getFullYear() !== year) { yearArr.push( ('
' + year + '
')); year = rday.getFullYear(); daysInYear = 0; } daysInYear++; // Fill months if (rday.getMonth() !== month) { monthArr.push( ('
' + settings.months[month] + '
')); month = rday.getMonth(); daysInMonth = 0; } daysInMonth++; var getDay = rday.getDay(); var day_class = dowClass[getDay]; if (holidays.indexOf((new Date(rday.getFullYear(), rday.getMonth(), rday.getDate())).getTime()) > -1) { day_class = "holiday"; } dayArr.push('
' + '
' + rday.getDate() + '
'); dowArr.push('
' + '
' + settings.dow[getDay] + '
'); } //for // Last year yearArr.push( '
' + year + '
'); // Last month monthArr.push( '
' + settings.months[month] + '
'); var dataPanel = core.dataPanel(element, range.length * tools.getCellSize()); // Append panel elements dataPanel.append(yearArr.join("")); dataPanel.append(monthArr.join("")); dataPanel.append($('
').html(dayArr.join(""))); dataPanel.append($('
').html(dowArr.join(""))); break; } return $('
').append(dataPanel); }, // **Navigation** navigation: function (element) { var ganttNavigate = null; // Scrolling navigation is provided by setting // `settings.navigate='scroll'` if (settings.navigate === "scroll") { ganttNavigate = $('