diff --git a/src/NzbDrone.Api/Calendar/CalendarModule.cs b/src/NzbDrone.Api/Calendar/CalendarModule.cs index cd6f8d13f..22f01c6cc 100644 --- a/src/NzbDrone.Api/Calendar/CalendarModule.cs +++ b/src/NzbDrone.Api/Calendar/CalendarModule.cs @@ -3,25 +3,35 @@ using System.Collections.Generic; using System.Linq; using NzbDrone.Api.Episodes; using NzbDrone.Api.Extensions; +using NzbDrone.Api.Mapping; +using NzbDrone.Core.Datastore.Events; +using NzbDrone.Core.Download; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Tv; namespace NzbDrone.Api.Calendar { - public class CalendarModule : NzbDroneRestModule + public class CalendarModule : NzbDroneRestModuleWithSignalR, + IHandle, + IHandle { private readonly IEpisodeService _episodeService; private readonly SeriesRepository _seriesRepository; - public CalendarModule(IEpisodeService episodeService, SeriesRepository seriesRepository) - : base("/calendar") + public CalendarModule(ICommandExecutor commandExecutor, + IEpisodeService episodeService, + SeriesRepository seriesRepository) + : base(commandExecutor, "calendar") { _episodeService = episodeService; _seriesRepository = seriesRepository; - GetResourceAll = GetPaged; + GetResourceAll = GetCalendar; } - private List GetPaged() + private List GetCalendar() { var start = DateTime.Today; var end = DateTime.Today.AddDays(2); @@ -37,5 +47,24 @@ namespace NzbDrone.Api.Calendar return resources.OrderBy(e => e.AirDate).ToList(); } + + public void Handle(EpisodeGrabbedEvent message) + { + foreach (var episode in message.Episode.Episodes) + { + var resource = episode.InjectTo(); + resource.Downloading = true; + + BroadcastResourceChange(ModelAction.Updated, resource); + } + } + + public void Handle(EpisodeDownloadedEvent message) + { + foreach (var episode in message.Episode.Episodes) + { + BroadcastResourceChange(ModelAction.Updated, episode.Id); + } + } } } diff --git a/src/UI/Calendar/CalendarLayout.js b/src/UI/Calendar/CalendarLayout.js index 4314df051..31d9e4a7f 100644 --- a/src/UI/Calendar/CalendarLayout.js +++ b/src/UI/Calendar/CalendarLayout.js @@ -2,10 +2,9 @@ define( [ 'marionette', - 'Calendar/UpcomingCollection', 'Calendar/UpcomingCollectionView', - 'Calendar/CalendarView', - ], function (Marionette, UpcomingCollection, UpcomingCollectionView, CalendarView) { + 'Calendar/CalendarView' + ], function (Marionette, UpcomingCollectionView, CalendarView) { return Marionette.Layout.extend({ template: 'Calendar/CalendarLayoutTemplate', @@ -14,20 +13,13 @@ define( calendar: '#x-calendar' }, - initialize: function () { - this.upcomingCollection = new UpcomingCollection(); - this.upcomingCollection.fetch(); - }, - onShow: function () { this._showUpcoming(); this._showCalendar(); }, _showUpcoming: function () { - this.upcoming.show(new UpcomingCollectionView({ - collection: this.upcomingCollection - })); + this.upcoming.show(new UpcomingCollectionView()); }, _showCalendar: function () { diff --git a/src/UI/Calendar/CalendarLayoutTemplate.html b/src/UI/Calendar/CalendarLayoutTemplate.html index 436a68b58..37ea4276e 100644 --- a/src/UI/Calendar/CalendarLayoutTemplate.html +++ b/src/UI/Calendar/CalendarLayoutTemplate.html @@ -9,6 +9,7 @@
  • Unaired
  • On Air
  • +
  • Downloading
  • Missing
  • Downloaded
diff --git a/src/UI/Calendar/CalendarView.js b/src/UI/Calendar/CalendarView.js index 003d0a6f6..4e19f4fd9 100644 --- a/src/UI/Calendar/CalendarView.js +++ b/src/UI/Calendar/CalendarView.js @@ -7,14 +7,17 @@ define( 'moment', 'Calendar/Collection', 'System/StatusModel', + 'History/Queue/QueueCollection', + 'Mixins/backbone.signalr.mixin', 'fullcalendar' - ], function (vent, Marionette, moment, CalendarCollection, StatusModel) { + ], function (vent, Marionette, moment, CalendarCollection, StatusModel, QueueCollection) { var _instance; return Marionette.ItemView.extend({ initialize: function () { - this.collection = new CalendarCollection(); + this.collection = new CalendarCollection().bindSignalR(); + this.listenTo(this.collection, 'change', this._reloadCalendarEvents); }, render : function () { @@ -36,7 +39,7 @@ define( prev: '', next: '' }, - events : this.getEvents, + viewRender : this._getEvents, eventRender : function (event, element) { self.$(element).addClass(event.statusLevel); self.$(element).children('.fc-event-inner').addClass(event.statusLevel); @@ -53,43 +56,50 @@ define( this.$('.fc-button-today').click(); }, - getEvents: function (start, end, callback) { - var startDate = moment(start).toISOString(); - var endDate = moment(end).toISOString(); + _getEvents: function (view) { + var start = moment(view.visStart).toISOString(); + var end = moment(view.visEnd).toISOString(); + + _instance.$el.fullCalendar('removeEvents'); _instance.collection.fetch({ - data : { start: startDate, end: endDate }, - success: function (calendarCollection) { - calendarCollection.each(function (element) { - var episodeTitle = element.get('title'); - var seriesTitle = element.get('series').title; - var start = element.get('airDateUtc'); - var runtime = element.get('series').runtime; - var end = moment(start).add('minutes', runtime).toISOString(); - - - element.set({ - title : seriesTitle, - episodeTitle: episodeTitle, - start : start, - end : end, - allDay : false - }); - - element.set('statusLevel', _instance.getStatusLevel(element)); - element.set('model', element); - }); - - callback(calendarCollection.toJSON()); + data : { start: start, end: end }, + success: function (collection) { + _instance._setEventData(collection); } }); }, - getStatusLevel: function (element) { + _setEventData: function (collection) { + var events = []; + + collection.each(function (model) { + var seriesTitle = model.get('series').title; + var start = model.get('airDateUtc'); + var runtime = model.get('series').runtime; + var end = moment(start).add('minutes', runtime).toISOString(); + + var event = { + title : seriesTitle, + start : start, + end : end, + allDay : false, + statusLevel : _instance._getStatusLevel(model, end), + model : model + }; + + events.push(event); + }); + + _instance.$el.fullCalendar('addEventSource', events); + }, + + _getStatusLevel: function (element, endTime) { var hasFile = element.get('hasFile'); + var downloading = QueueCollection.findEpisode(element.get('id')) || element.get('downloading'); var currentTime = moment(); var start = moment(element.get('airDateUtc')); - var end = moment(element.get('end')); + var end = moment(endTime); var statusLevel = 'primary'; @@ -97,6 +107,10 @@ define( statusLevel = 'success'; } + if (downloading) { + statusLevel = 'purple'; + } + else if (currentTime.isAfter(start) && currentTime.isBefore(end)) { statusLevel = 'warning'; } @@ -105,13 +119,17 @@ define( statusLevel = 'danger'; } - var test = currentTime.startOf('day').format('LLLL'); - if (end.isBefore(currentTime.startOf('day'))) { statusLevel += ' past'; } return statusLevel; + }, + + _reloadCalendarEvents: function () { + window.alert('collection changed'); + this.$el.fullCalendar('removeEvents'); + this._setEventData(this.collection); } }); }); diff --git a/src/UI/Calendar/UpcomingCollectionView.js b/src/UI/Calendar/UpcomingCollectionView.js index 2a9508bba..642e56d61 100644 --- a/src/UI/Calendar/UpcomingCollectionView.js +++ b/src/UI/Calendar/UpcomingCollectionView.js @@ -3,9 +3,22 @@ define( [ 'marionette', - 'Calendar/UpcomingItemView' - ], function (Marionette, UpcomingItemView) { + 'Calendar/UpcomingCollection', + 'Calendar/UpcomingItemView', + 'Mixins/backbone.signalr.mixin' + ], function (Marionette, UpcomingCollection, UpcomingItemView) { return Marionette.CollectionView.extend({ - itemView: UpcomingItemView + itemView: UpcomingItemView, + + initialize: function () { + this.collection = new UpcomingCollection().bindSignalR(); + this.collection.fetch(); + + this.listenTo(this.collection, 'change', this._refresh); + }, + + _refresh: function () { + this.render(); + } }); }); diff --git a/src/UI/Cells/EpisodeStatusCell.js b/src/UI/Cells/EpisodeStatusCell.js index f03ad12ee..c0d8bb705 100644 --- a/src/UI/Cells/EpisodeStatusCell.js +++ b/src/UI/Cells/EpisodeStatusCell.js @@ -3,12 +3,11 @@ define( [ 'reqres', - 'underscore', 'Cells/NzbDroneCell', 'History/Queue/QueueCollection', 'moment', 'Shared/FormatHelpers' - ], function (reqres, _, NzbDroneCell, QueueCollection, Moment, FormatHelpers) { + ], function (reqres, NzbDroneCell, QueueCollection, Moment, FormatHelpers) { return NzbDroneCell.extend({ className: 'episode-status-cell', @@ -56,10 +55,7 @@ define( else { var model = this.model; - - var downloading = _.find(QueueCollection.models, function (queueModel) { - return queueModel.get('episode').id === model.get('id'); - }); + var downloading = QueueCollection.findEpisode(model.get('id')); if (downloading || this.model.get('downloading')) { icon = 'icon-nd-downloading'; diff --git a/src/UI/Content/Overrides/fullcalendar.less b/src/UI/Content/Overrides/fullcalendar.less new file mode 100644 index 000000000..3f7f29c30 --- /dev/null +++ b/src/UI/Content/Overrides/fullcalendar.less @@ -0,0 +1,11 @@ +.fc-view { + overflow: visible; +} + +.fc-event-title { + padding: 0 2px; + display: block; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} \ No newline at end of file diff --git a/src/UI/Content/fullcalendar.css b/src/UI/Content/fullcalendar.css index b7a226d74..92fe47f20 100644 --- a/src/UI/Content/fullcalendar.css +++ b/src/UI/Content/fullcalendar.css @@ -1,5 +1,5 @@ -/*! - * FullCalendar v1.6.1 Stylesheet +/*! + * FullCalendar v1.6.4 Stylesheet * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ @@ -102,11 +102,12 @@ html .fc, .fc-content { clear: both; + zoom: 1; /* for IE7, gives accurate coordinates for [un]freezeContentHeight */ } .fc-view { - width: 100%; /* needed for view switching (when view is absolute) */ - /*overflow: hidden;*/ + width: 100%; + overflow: hidden; } @@ -232,8 +233,9 @@ html .fc, .fc-state-down, .fc-state-active { - background : #cccccc none; - outline: 0; + background-color: #cccccc; + background-image: none; + outline: 0; box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); } @@ -249,6 +251,15 @@ html .fc, /* Global Event Styles ------------------------------------------------------------------------*/ + +.fc-event-container > * { + z-index: 8; + } + +.fc-event-container > .ui-draggable-dragging, +.fc-event-container > .ui-resizable-resizing { + z-index: 9; + } .fc-event { border: 1px solid #3a87ad; /* default BORDER color */ @@ -279,15 +290,8 @@ a.fc-event, .fc-event-time, .fc-event-title { - padding: 0 2px; - display: block; -} - -.fc-event-title { - text-overflow: ellipsis; - white-space: nowrap; - overflow: hidden; -} + padding: 0 1px; + } .fc .ui-resizable-handle { display: block; diff --git a/src/UI/Content/overrides.less b/src/UI/Content/overrides.less index 94e1267b2..040b76e92 100644 --- a/src/UI/Content/overrides.less +++ b/src/UI/Content/overrides.less @@ -1,3 +1,4 @@ @import "Overrides/bootstrap"; @import "Overrides/browser"; @import "Overrides/bootstrap.toggle-switch"; +@import "Overrides/fullcalendar"; diff --git a/src/UI/Episode/EpisodeDetailsLayoutTemplate.html b/src/UI/Episode/EpisodeDetailsLayoutTemplate.html index 1031118b1..d06bdf905 100644 --- a/src/UI/Episode/EpisodeDetailsLayoutTemplate.html +++ b/src/UI/Episode/EpisodeDetailsLayoutTemplate.html @@ -4,11 +4,7 @@

- {{#if episodeTitle}} - {{title}} - {{EpisodeNumber}} - {{episodeTitle}} - {{else}} - {{series.title}} - {{EpisodeNumber}} - {{title}} - {{/if}} + {{series.title}} - {{EpisodeNumber}} - {{title}}

diff --git a/src/UI/Handlebars/Helpers/Episode.js b/src/UI/Handlebars/Helpers/Episode.js index 7e0bff260..115317e7f 100644 --- a/src/UI/Handlebars/Helpers/Episode.js +++ b/src/UI/Handlebars/Helpers/Episode.js @@ -20,6 +20,7 @@ define( Handlebars.registerHelper('StatusLevel', function () { var hasFile = this.hasFile; + var downloading = require('History/Queue/QueueCollection').findEpisode(this.id) || this.downloading; var currentTime = Moment(); var start = Moment(this.airDateUtc); var end = Moment(this.end); @@ -28,6 +29,10 @@ define( return 'success'; } + if (downloading) { + return 'purple'; + } + if (currentTime.isAfter(start) && currentTime.isBefore(end)) { return 'warning'; } diff --git a/src/UI/History/Queue/QueueCollection.js b/src/UI/History/Queue/QueueCollection.js index d7340341d..a66393435 100644 --- a/src/UI/History/Queue/QueueCollection.js +++ b/src/UI/History/Queue/QueueCollection.js @@ -1,13 +1,20 @@ 'use strict'; define( [ + 'underscore', 'backbone', 'History/Queue/QueueModel', 'Mixins/backbone.signalr.mixin' - ], function (Backbone, QueueModel) { + ], function (_, Backbone, QueueModel) { var QueueCollection = Backbone.Collection.extend({ url : window.NzbDrone.ApiRoot + '/queue', - model: QueueModel + model: QueueModel, + + findEpisode: function (episodeId) { + return _.find(this.models, function (queueModel) { + return queueModel.get('episode').id === episodeId; + }); + } }); var collection = new QueueCollection().bindSignalR(); diff --git a/src/UI/JsLibraries/fullcalendar.js b/src/UI/JsLibraries/fullcalendar.js index 0d43e5866..41c50856c 100644 --- a/src/UI/JsLibraries/fullcalendar.js +++ b/src/UI/JsLibraries/fullcalendar.js @@ -1,5 +1,5 @@ /*! - * FullCalendar v1.6.1 + * FullCalendar v1.6.4 * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ @@ -86,7 +86,9 @@ var defaults = { //selectable: false, unselectAuto: true, - dropAccept: '*' + dropAccept: '*', + + handleWindowResize: true }; @@ -113,7 +115,7 @@ var rtlDefaults = { ;; -var fc = $.fullCalendar = { version: "1.6.1" }; +var fc = $.fullCalendar = { version: "1.6.4" }; var fcViews = fc.views = {}; @@ -141,7 +143,8 @@ $.fn.fullCalendar = function(options) { } return this; } - + + options = options || {}; // would like to have this logic in EventManager, but needs to happen before options are recursively extended var eventSources = options.eventSources || []; @@ -225,10 +228,8 @@ function Calendar(element, options, eventSources) { var content; var tm; // for making theme classes var currentView; - var viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; - var absoluteViewElement; var resizeUID = 0; var ignoreWindowResize = 0; var date = new Date(); @@ -247,11 +248,11 @@ function Calendar(element, options, eventSources) { function render(inc) { if (!content) { initialRender(); - }else{ + } + else if (elementVisible()) { + // mainly for the public API calcSize(); - markSizesDirty(); - markEventsDirty(); - renderView(inc); + _renderView(inc); } } @@ -268,15 +269,22 @@ function Calendar(element, options, eventSources) { if (options.theme) { element.addClass('ui-widget'); } + content = $("
") .prependTo(element); + header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } + changeView(options.defaultView); - $(window).resize(windowResize); + + if (options.handleWindowResize) { + $(window).resize(windowResize); + } + // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); @@ -296,21 +304,27 @@ function Calendar(element, options, eventSources) { function destroy() { + + if (currentView) { + trigger('viewDestroy', currentView, currentView, currentView.element); + currentView.triggerEventDestroy(); + } + $(window).unbind('resize', windowResize); + header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } - function elementVisible() { - return _element.offsetWidth !== 0; + return element.is(':visible'); } function bodyVisible() { - return $('body')[0].offsetWidth !== 0; + return $('body').is(':visible'); } @@ -318,133 +332,97 @@ function Calendar(element, options, eventSources) { /* View Rendering -----------------------------------------------------------------------------*/ - // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) - + function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { - ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached + _changeView(newViewName); + } + } + + + function _changeView(newViewName) { + ignoreWindowResize++; + if (currentView) { + trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); - - var oldView = currentView; - var newViewElement; - - if (oldView) { - (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) - setMinHeight(content, content.height()); - oldView.element.hide(); - }else{ - setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated - } - content.css('overflow', 'hidden'); - - currentView = viewInstances[newViewName]; - if (currentView) { - currentView.element.show(); - }else{ - currentView = viewInstances[newViewName] = new fcViews[newViewName]( - newViewElement = absoluteViewElement = - $("
") - .appendTo(content), - t // the calendar object - ); - } - - if (oldView) { - header.deactivateButton(oldView.name); - } - header.activateButton(newViewName); - - renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null - - content.css('overflow', ''); - if (oldView) { - setMinHeight(content, 1); - } - - if (!newViewElement) { - (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) - } - - ignoreWindowResize--; + currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event + freezeContentHeight(); + currentView.element.remove(); + header.deactivateButton(currentView.name); } + + header.activateButton(newViewName); + + currentView = new fcViews[newViewName]( + $("
") + .appendTo(content), + t // the calendar object + ); + + renderView(); + unfreezeContentHeight(); + + ignoreWindowResize--; } - - - + + function renderView(inc) { - if (elementVisible()) { - ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached + if ( + !currentView.start || // never rendered before + inc || date < currentView.start || date >= currentView.end // or new date range + ) { + if (elementVisible()) { + _renderView(inc); + } + } + } + + + function _renderView(inc) { // assumes elementVisible + ignoreWindowResize++; + if (currentView.start) { // already been rendered? + trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); - - if (suggestedViewHeight === undefined) { - calcSize(); - } - - var forceEventRender = false; - if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { - // view must render an entire new date range (and refetch/render events) - currentView.render(date, inc || 0); // responsible for clearing events - setSize(true); - forceEventRender = true; - } - else if (currentView.sizeDirty) { - // view must resize (and rerender events) - currentView.clearEvents(); - setSize(); - forceEventRender = true; - } - else if (currentView.eventsDirty) { - currentView.clearEvents(); - forceEventRender = true; - } - currentView.sizeDirty = false; - currentView.eventsDirty = false; - updateEvents(forceEventRender); - - elementOuterWidth = element.outerWidth(); - - header.updateTitle(currentView.title); - var today = new Date(); - if (today >= currentView.start && today < currentView.end) { - header.disableButton('today'); - }else{ - header.enableButton('today'); - } - - ignoreWindowResize--; - currentView.trigger('viewDisplay', _element); + clearEvents(); } + + freezeContentHeight(); + currentView.render(date, inc || 0); // the view's render method ONLY renders the skeleton, nothing else + setSize(); + unfreezeContentHeight(); + (currentView.afterRender || noop)(); + + updateTitle(); + updateTodayButton(); + + trigger('viewRender', currentView, currentView, currentView.element); + currentView.trigger('viewDisplay', _element); // deprecated + + ignoreWindowResize--; + + getAndRenderEvents(); } - + /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { - markSizesDirty(); if (elementVisible()) { + unselect(); + clearEvents(); calcSize(); setSize(); - unselect(); - currentView.clearEvents(); - currentView.renderEvents(events); - currentView.sizeDirty = false; + renderEvents(); } } - function markSizesDirty() { - $.each(viewInstances, function(i, inst) { - inst.sizeDirty = true; - }); - } - - - function calcSize() { + function calcSize() { // assumes elementVisible if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } @@ -457,15 +435,20 @@ function Calendar(element, options, eventSources) { } - function setSize(dateChanged) { // todo: dateChanged? - ignoreWindowResize++; - currentView.setHeight(suggestedViewHeight, dateChanged); - if (absoluteViewElement) { - absoluteViewElement.css('position', 'relative'); - absoluteViewElement = null; + function setSize() { // assumes elementVisible + + if (suggestedViewHeight === undefined) { + calcSize(); // for first time + // NOTE: we don't want to recalculate on every renderView because + // it could result in oscillating heights due to scrollbars. } - currentView.setWidth(content.width(), dateChanged); + + ignoreWindowResize++; + currentView.setHeight(suggestedViewHeight); + currentView.setWidth(content.width()); ignoreWindowResize--; + + elementOuterWidth = element.outerWidth(); } @@ -494,52 +477,85 @@ function Calendar(element, options, eventSources) { /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ + // TODO: going forward, most of this stuff should be directly handled by the view + + + function refetchEvents() { // can be called as an API method + clearEvents(); + fetchAndRenderEvents(); + } + + + function rerenderEvents(modifiedEventID) { // can be called as an API method + clearEvents(); + renderEvents(modifiedEventID); + } + + + function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack + if (elementVisible()) { + currentView.setEventData(events); // for View.js, TODO: unify with renderEvents + currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements + currentView.trigger('eventAfterAllRender'); + } + } + + + function clearEvents() { + currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event + currentView.clearEvents(); // actually remove the DOM elements + currentView.clearEventData(); // for View.js, TODO: unify with clearEvents + } - - // fetches events if necessary, rerenders events if necessary (or if forced) - function updateEvents(forceRender) { + + function getAndRenderEvents() { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { - refetchEvents(); + fetchAndRenderEvents(); } - else if (forceRender) { - rerenderEvents(); + else { + renderEvents(); } } - - - function refetchEvents() { - fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents + + + function fetchAndRenderEvents() { + fetchEvents(currentView.visStart, currentView.visEnd); + // ... will call reportEvents + // ... which will call renderEvents } - + // called when event data arrives function reportEvents(_events) { events = _events; - rerenderEvents(); + renderEvents(); } - - + + // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } - - - // attempts to rerenderEvents - function rerenderEvents(modifiedEventID) { - markEventsDirty(); - if (elementVisible()) { - currentView.clearEvents(); - currentView.renderEvents(events, modifiedEventID); - currentView.eventsDirty = false; - } + + + + /* Header Updating + -----------------------------------------------------------------------------*/ + + + function updateTitle() { + header.updateTitle(currentView.title); } - - - function markEventsDirty() { - $.each(viewInstances, function(i, inst) { - inst.eventsDirty = true; - }); + + + function updateTodayButton() { + var today = new Date(); + if (today >= currentView.start && today < currentView.end) { + header.disableButton('today'); + } + else { + header.enableButton('today'); + } } @@ -620,6 +636,29 @@ function Calendar(element, options, eventSources) { function getDate() { return cloneDate(date); } + + + + /* Height "Freezing" + -----------------------------------------------------------------------------*/ + + + function freezeContentHeight() { + content.css({ + width: '100%', + height: content.height(), + overflow: 'hidden' + }); + } + + + function unfreezeContentHeight() { + content.css({ + width: '', + height: '', + overflow: '' + }); + } @@ -980,7 +1019,22 @@ function EventManager(options, _sources) { var success = source.success; var error = source.error; var complete = source.complete; - var data = $.extend({}, source.data || {}); + + // retrieve any outbound GET/POST $.ajax data from the options + var customData; + if ($.isFunction(source.data)) { + // supplied as a function that returns a key/value object + customData = source.data(); + } + else { + // supplied as a straight key/value object + customData = source.data; + } + + // use a copy of the custom data so we can modify the parameters + // and not affect the passed-in object. + var data = $.extend({}, customData || {}); + var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { @@ -989,6 +1043,7 @@ function EventManager(options, _sources) { if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } + pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, @@ -1088,7 +1143,7 @@ function EventManager(options, _sources) { e.className = event.className; e.editable = event.editable; e.color = event.color; - e.backgroudColor = event.backgroudColor; + e.backgroundColor = event.backgroundColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); @@ -1161,14 +1216,14 @@ function EventManager(options, _sources) { function pushLoading() { if (!loadingLevel++) { - trigger('loading', null, true); + trigger('loading', null, true, getView()); } } function popLoading() { if (!--loadingLevel) { - trigger('loading', null, false); + trigger('loading', null, false, getView()); } } @@ -1347,15 +1402,6 @@ function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1 } -function skipWeekend(date, inc, excl) { - inc = inc || 1; - while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { - addDays(date, inc); - } - return date; -} - - function dayDiff(d1, d2) { // d1 - d2 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS); } @@ -1611,8 +1657,8 @@ fc.dateFormatters = dateFormatters; /* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js) * * Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. - * @param date Date - the date to get the week for - * @return number - the number of the week within the year that contains this date + * `date` - the date to get the week for + * `number` - the number of the week within the year that contains this date */ function iso8601Week(date) { var time; @@ -1649,95 +1695,7 @@ function exclEndDay(event) { function _exclEndDay(end, allDay) { end = cloneDate(end); return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); -} - - -function segCmp(a, b) { - return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); -} - - -function segsCollide(seg1, seg2) { - return seg1.end > seg2.start && seg1.start < seg2.end; -} - - - -/* Event Sorting ------------------------------------------------------------------------------*/ - - -// event rendering utilities -function sliceSegs(events, visEventEnds, start, end) { - var segs = [], - i, len=events.length, event, - eventStart, eventEnd, - segStart, segEnd, - isStart, isEnd; - for (i=0; i start && eventStart < end) { - if (eventStart < start) { - segStart = cloneDate(start); - isStart = false; - }else{ - segStart = eventStart; - isStart = true; - } - if (eventEnd > end) { - segEnd = cloneDate(end); - isEnd = false; - }else{ - segEnd = eventEnd; - isEnd = true; - } - segs.push({ - event: event, - start: segStart, - end: segEnd, - isStart: isStart, - isEnd: isEnd, - msLength: segEnd - segStart - }); - } - } - return segs.sort(segCmp); -} - - -// event rendering calculation utilities -function stackSegs(segs) { - var levels = [], - i, len = segs.length, seg, - j, collide, k; - for (i=0; i") + $("
") .appendTo(element); } - - function buildTable(showNumbers) { - var html = ''; - var i, j; + function buildTable() { + var html = buildTableHTML(); + + if (table) { + table.remove(); + } + table = $(html).appendTo(element); + + head = table.find('thead'); + headCells = head.find('.fc-day-header'); + body = table.find('tbody'); + bodyRows = body.find('tr'); + bodyCells = body.find('.fc-day'); + bodyFirstCells = bodyRows.find('td:first-child'); + + firstRowCellInners = bodyRows.eq(0).find('.fc-day > div'); + firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div'); + + markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's + markFirstLast(bodyRows); // marks first+last td's + bodyRows.eq(0).addClass('fc-first'); + bodyRows.filter(':last').addClass('fc-last'); + + bodyCells.each(function(i, _cell) { + var date = cellToDate( + Math.floor(i / colCnt), + i % colCnt + ); + trigger('dayRender', t, date, $(_cell)); + }); + + dayBind(bodyCells); + } + + + + /* HTML Building + -----------------------------------------------------------*/ + + + function buildTableHTML() { + var html = + "" + + buildHeadHTML() + + buildBodyHTML() + + "
"; + + return html; + } + + + function buildHeadHTML() { var headerClass = tm + "-widget-header"; - var contentClass = tm + "-widget-content"; - var month = t.start.getMonth(); - var today = clearTime(new Date()); - var cellDate; // not to be confused with local function. TODO: better names - var cellClasses; - var cell; + var html = ''; + var col; + var date; - html += "" + - "" + - ""; + html += ""; if (showWeekNumbers) { - html += ""; } - for (i=0; i"; + for (col=0; col" + + htmlEscape(formatDate(date, colFormat)) + + ""; } - html += "" + - "" + - ""; + html += ""; + + return html; + } + + + function buildBodyHTML() { + var contentClass = tm + "-widget-content"; + var html = ''; + var row; + var col; + var date; + + html += ""; + + for (row=0; row" + - "
" + - ""; + date = cellToDate(row, 0); + html += + "
"; } - for (j=0; j" + - "
"; - if (showNumbers) { - html += "
" + cellDate.getDate() + "
"; - } - html += "
" + - "
 
" + - "
" + - "
" + - ""; + for (col=0; col"; - lockHeight(); // the unlock happens later, in setHeight()... - if (table) { - table.remove(); - } - table = $(html).appendTo(element); + html += "
"; - head = table.find('thead'); - headCells = head.find('.fc-day-header'); - body = table.find('tbody'); - bodyRows = body.find('tr'); - bodyCells = body.find('.fc-day'); - bodyFirstCells = bodyRows.find('td:first-child'); - bodyCellTopInners = bodyRows.eq(0).find('.fc-day-content > div'); - - markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's - markFirstLast(bodyRows); // marks first+last td's - bodyRows.eq(0).addClass('fc-first'); - bodyRows.filter(':last').addClass('fc-last'); - - if (showWeekNumbers) { - head.find('.fc-week-number').text(weekNumberTitle); + return html; + } + + + function buildCellHTML(date) { + var contentClass = tm + "-widget-content"; + var month = t.start.getMonth(); + var today = clearTime(new Date()); + var html = ''; + var classNames = [ + 'fc-day', + 'fc-' + dayIDs[date.getDay()], + contentClass + ]; + + if (date.getMonth() != month) { + classNames.push('fc-other-month'); + } + if (+date == +today) { + classNames.push( + 'fc-today', + tm + '-state-highlight' + ); + } + else if (date < today) { + classNames.push('fc-past'); + } + else { + classNames.push('fc-future'); } - headCells.each(function(i, _cell) { - var date = indexDate(i); - $(_cell).text(formatDate(date, colFormat)); - }); + html += + "" + + "
"; - if (showWeekNumbers) { - body.find('.fc-week-number > div').each(function(i, _cell) { - var weekStart = _cellDate(i, 0); - $(_cell).text(formatDate(weekStart, weekNumberFormat)); - }); + if (showNumbers) { + html += "
" + date.getDate() + "
"; } - - bodyCells.each(function(i, _cell) { - var date = indexDate(i); - trigger('dayRender', t, date, $(_cell)); - }); - dayBind(bodyCells); + html += + "
" + + "
 
" + + "
" + + "
" + + ""; + + return html; } - + + + + /* Dimensions + -----------------------------------------------------------*/ function setHeight(height) { @@ -2416,19 +2420,19 @@ function BasicView(element, calendar, viewName) { bodyFirstCells.each(function(i, _cell) { if (i < rowCnt) { cell = $(_cell); - setMinHeight( - cell.find('> div'), + cell.find('> div').css( + 'min-height', (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); - unlockHeight(); } function setWidth(width) { viewWidth = width; + colPositions.clear(); colContentPositions.clear(); weekNumberWidth = 0; @@ -2463,35 +2467,30 @@ function BasicView(element, calendar, viewName) { /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ - - + // TODO: should be consolidated with AgendaView's methods + + function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive + if (refreshCoordinateGrid) { coordinateGrid.build(); } - var rowStart = cloneDate(t.visStart); - var rowEnd = addDays(cloneDate(rowStart), colCnt); - for (var i=0; i" + - "
" + - ""; - - if (showWeekNumbers) { - s += ""; - } - - for (i=0; i"; // fc- needed for setDayID - } - s += - "" + - "" + - "" + - "" + - "" + - ""; - for (i=0; i" + // fc- needed for setDayID - "
" + - "
" + - "
 
" + - "
" + - "
" + - ""; - } - s += - "
" + - "" + - "" + - "
"; + html += + "" + + htmlEscape(weekNumberTitle) + + "
" + + "
" + + htmlEscape(formatDate(date, weekNumberFormat)) + + "
" + + "
"; - } - else { - s += "  
  
"; - dayTable = $(s).appendTo(element); - dayHead = dayTable.find('thead'); - dayHeadCells = dayHead.find('th').slice(1, -1); - dayBody = dayTable.find('tbody'); - dayBodyCells = dayBody.find('td').slice(0, -1); - dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); - dayBodyFirstCell = dayBodyCells.eq(0); - dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); - - markFirstLast(dayHead.add(dayHead.find('tr'))); - markFirstLast(dayBody.add(dayBody.find('tr'))); - - axisFirstCells = dayHead.find('th:first'); - gutterCells = dayTable.find('.fc-agenda-gutter'); + buildDayTable(); slotLayer = $("
") @@ -3156,7 +2947,7 @@ function AgendaView(element, calendar, viewName) { if (opt('allDaySlot')) { daySegmentContainer = - $("
") + $("
") .appendTo(slotLayer); s = @@ -3174,9 +2965,6 @@ function AgendaView(element, calendar, viewName) { dayBind(allDayRow.find('td')); - axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); - gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); - slotLayer.append( "
" + "
" + @@ -3193,13 +2981,13 @@ function AgendaView(element, calendar, viewName) { $("
") .appendTo(slotLayer); - slotContent = + slotContainer = $("
") .appendTo(slotScroller); slotSegmentContainer = - $("
") - .appendTo(slotContent); + $("
") + .appendTo(slotContainer); s = "" + @@ -3225,64 +3013,183 @@ function AgendaView(element, calendar, viewName) { s += "" + "
"; - slotTable = $(s).appendTo(slotContent); - slotTableFirstInner = slotTable.find('div:first'); + slotTable = $(s).appendTo(slotContainer); slotBind(slotTable.find('td')); + } + + + + /* Build Day Table + -----------------------------------------------------------------------*/ + + + function buildDayTable() { + var html = buildDayTableHTML(); + + if (dayTable) { + dayTable.remove(); + } + dayTable = $(html).appendTo(element); + + dayHead = dayTable.find('thead'); + dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter + dayBody = dayTable.find('tbody'); + dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter + dayBodyCellInners = dayBodyCells.find('> div'); + dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div'); + + dayBodyFirstCell = dayBodyCells.eq(0); + dayBodyFirstCellStretcher = dayBodyCellInners.eq(0); - axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); + markFirstLast(dayHead.add(dayHead.find('tr'))); + markFirstLast(dayBody.add(dayBody.find('tr'))); + + // TODO: now that we rebuild the cells every time, we should call dayRender } - - - - function updateCells() { - var i; - var headCell; - var bodyCell; + + + function buildDayTableHTML() { + var html = + "" + + buildDayTableHeadHTML() + + buildDayTableBodyHTML() + + "
"; + + return html; + } + + + function buildDayTableHeadHTML() { + var headerClass = tm + "-widget-header"; var date; - var today = clearTime(new Date()); + var html = ''; + var weekText; + var col; + + html += + "" + + ""; if (showWeekNumbers) { - var weekText = formatDate(colDate(0), weekNumberFormat); + date = cellToDate(0, 0); + weekText = formatDate(date, weekNumberFormat); if (rtl) { - weekText = weekText + weekNumberTitle; + weekText += weekNumberTitle; } else { weekText = weekNumberTitle + weekText; } - dayHead.find('.fc-week-number').text(weekText); + html += + "" + + htmlEscape(weekText) + + ""; + } + else { + html += " "; } - for (i=0; i" + + htmlEscape(formatDate(date, colFormat)) + + ""; } + + html += + " " + + "" + + ""; + + return html; } - - - - function setHeight(height, dateChanged) { - if (height === undefined) { - height = viewHeight; - } - viewHeight = height; - slotTopCache = {}; - - var headHeight = dayBody.position().top; - var allDayHeight = slotScroller.position().top; // including divider - var bodyHeight = Math.min( // total body height, including borders - height - headHeight, // when scrollbars - slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border + + + function buildDayTableBodyHTML() { + var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called + var contentClass = tm + "-widget-content"; + var date; + var today = clearTime(new Date()); + var col; + var cellsHTML; + var cellHTML; + var classNames; + var html = ''; + + html += + "" + + "" + + " "; + + cellsHTML = ''; + + for (col=0; col" + + "
" + + "
" + + "
 
" + + "
" + + "
" + + ""; + + cellsHTML += cellHTML; + } + + html += cellsHTML; + html += + " " + + "" + + ""; + + return html; + } + + + // TODO: data-date on the cells + + + + /* Dimensions + -----------------------------------------------------------------------*/ + + + function setHeight(height) { + if (height === undefined) { + height = viewHeight; + } + viewHeight = height; + slotTopCache = {}; + + var headHeight = dayBody.position().top; + var allDayHeight = slotScroller.position().top; // including divider + var bodyHeight = Math.min( // total body height, including borders + height - headHeight, // when scrollbars + slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border ); - + dayBodyFirstCellStretcher .height(bodyHeight - vsides(dayBodyFirstCell)); @@ -3290,21 +3197,25 @@ function AgendaView(element, calendar, viewName) { slotScroller.height(bodyHeight - allDayHeight - 1); - slotHeight = slotTableFirstInner.height() + 1; // +1 for border + // the stylesheet guarantees that the first row has no border. + // this allows .height() to work well cross-browser. + slotHeight = slotTable.find('tr:first').height() + 1; // +1 for bottom border snapRatio = opt('slotMinutes') / snapMinutes; snapHeight = slotHeight / snapRatio; - - if (dateChanged) { - resetScroll(); - } } - function setWidth(width) { viewWidth = width; + colPositions.clear(); colContentPositions.clear(); + + var axisFirstCells = dayHead.find('th:first'); + if (allDayTable) { + axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); + } + axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); axisWidth = 0; setOuterWidth( @@ -3316,8 +3227,12 @@ function AgendaView(element, calendar, viewName) { axisWidth ); + var gutterCells = dayTable.find('.fc-agenda-gutter'); + if (allDayTable) { + gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); + } + var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) - //slotTable.width(slotTableWidth); gutterWidth = slotScroller.width() - slotTableWidth; if (gutterWidth) { @@ -3339,6 +3254,10 @@ function AgendaView(element, calendar, viewName) { + /* Scrolling + -----------------------------------------------------------------------*/ + + function resetScroll() { var d0 = zeroDate(); var scrollDate = cloneDate(d0); @@ -3350,15 +3269,10 @@ function AgendaView(element, calendar, viewName) { scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } - - - function beforeHide() { - savedScrollTop = slotScroller.scrollTop(); - } - - - function afterShow() { - slotScroller.scrollTop(savedScrollTop); + + + function afterRender() { // after the view has been freshly rendered and sized + resetScroll(); } @@ -3382,7 +3296,7 @@ function AgendaView(element, calendar, viewName) { function slotClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); - var date = colDate(col); + var date = cellToDate(0, col); var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (rowMatch) { var mins = parseInt(rowMatch[1]) * opt('slotMinutes'); @@ -3400,26 +3314,26 @@ function AgendaView(element, calendar, viewName) { /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ - + // TODO: should be consolidated with BasicView's methods + + + function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive - function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } - var visStart = cloneDate(t.visStart); - var startCol, endCol; - if (rtl) { - startCol = dayDiff(endDate, visStart)*dis+dit+1; - endCol = dayDiff(startDate, visStart)*dis+dit+1; - }else{ - startCol = dayDiff(startDate, visStart); - endCol = dayDiff(endDate, visStart); - } - startCol = Math.max(0, startCol); - endCol = Math.min(colCnt, endCol); - if (startCol < endCol) { + + var segments = rangeToSegments(overlayStart, overlayEnd); + + for (var i=0; i= 0 && col < colCnt) { // only works when times are on same day - var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords + var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords var top = timePosition(startDate, startDate); var bottom = timePosition(startDate, endDate); if (bottom > top) { // protect against selections that are entirely before or after visible range @@ -3635,10 +3533,9 @@ function AgendaView(element, calendar, viewName) { var helperRes = helperOption(startDate, endDate); if (helperRes) { rect.position = 'absolute'; - rect.zIndex = 8; selectionHelper = $(helperRes) .css(rect) - .appendTo(slotContent); + .appendTo(slotContainer); } }else{ rect.isStart = true; // conside rect a "seg" now @@ -3657,7 +3554,7 @@ function AgendaView(element, calendar, viewName) { } if (selectionHelper) { slotBind(selectionHelper); - slotContent.append(selectionHelper); + slotContainer.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } @@ -3684,15 +3581,15 @@ function AgendaView(element, calendar, viewName) { var dates; hoverListener.start(function(cell, origCell) { clearSelection(); - if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { - var d1 = cellDate(origCell); - var d2 = cellDate(cell); + if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) { + var d1 = realCellToDate(origCell); + var d2 = realCellToDate(cell); dates = [ d1, addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes d2, addMinutes(cloneDate(d2), snapMinutes) - ].sort(cmp); + ].sort(dateCompare); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; @@ -3709,10 +3606,10 @@ function AgendaView(element, calendar, viewName) { }); } } - - + + function reportDayClick(date, allDay, ev) { - trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); + trigger('dayClick', dayBodyCells[dateToCell(date).col], date, allDay, ev); } @@ -3725,10 +3622,10 @@ function AgendaView(element, calendar, viewName) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { - if (cellIsAllDay(cell)) { + if (getIsCellAllDay(cell)) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); }else{ - var d1 = cellDate(cell); + var d1 = realCellToDate(cell); var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); renderSlotOverlay(d1, d2); } @@ -3741,10 +3638,10 @@ function AgendaView(element, calendar, viewName) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { - trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); + trigger('drop', _dragElement, realCellToDate(cell), getIsCellAllDay(cell), ev, ui); } } - + } @@ -3756,22 +3653,17 @@ function AgendaEventRenderer() { // exports t.renderEvents = renderEvents; - t.compileDaySegs = compileDaySegs; // for DayEventRenderer t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; - t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; - //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; - var reportEvents = t.reportEvents; - var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; @@ -3780,15 +3672,15 @@ function AgendaEventRenderer() { var getMaxMinute = t.getMaxMinute; var getMinMinute = t.getMinMinute; var timePosition = t.timePosition; + var getIsCellAllDay = t.getIsCellAllDay; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; - var renderDaySegs = t.renderDaySegs; - var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture + var cellToDate = t.cellToDate; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSnapHeight = t.getSnapHeight; var getSnapMinutes = t.getSnapMinutes; - var getBodyContent = t.getBodyContent; + var getSlotContainer = t.getSlotContainer; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; @@ -3796,10 +3688,15 @@ function AgendaEventRenderer() { var eventResize = t.eventResize; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; + var renderDayEvents = t.renderDayEvents; var calendar = t.calendar; var formatDate = calendar.formatDate; var formatDates = calendar.formatDates; - + + + // overrides + t.draggableDayEvent = draggableDayEvent; + /* Rendering @@ -3807,7 +3704,6 @@ function AgendaEventRenderer() { function renderEvents(events, modifiedEventId) { - reportEvents(events); var i, len=events.length, dayEvents=[], slotEvents=[]; @@ -3818,68 +3714,96 @@ function AgendaEventRenderer() { slotEvents.push(events[i]); } } + if (opt('allDaySlot')) { - renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); + renderDayEvents(dayEvents, modifiedEventId); setHeight(); // no params means set to viewHeight } + renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); - trigger('eventAfterAllRender'); } function clearEvents() { - reportEventClear(); getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } - - - function compileDaySegs(events) { - var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), - i, levelCnt=levels.length, level, - j, seg, - segs=[]; - for (i=0; i start && eventStart < end) { + if (eventStart < start) { + segStart = cloneDate(start); + isStart = false; + }else{ + segStart = eventStart; + isStart = true; + } + if (eventEnd > end) { + segEnd = cloneDate(end); + isEnd = false; + }else{ + segEnd = eventEnd; + isEnd = true; + } + segs.push({ + event: event, + start: segStart, + end: segEnd, + isStart: isStart, + isEnd: isEnd + }); + } + } + return segs.sort(compareSlotSegs); + } + + function slotEventEnd(event) { if (event.end) { return cloneDate(event.end); @@ -3890,38 +3814,29 @@ function AgendaEventRenderer() { // renders events in the 'time slots' at the bottom + // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space + // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp) function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, - classes, - top, bottom, - colI, levelI, forward, - leftmost, - availWidth, - outerWidth, + top, + bottom, + columnLeft, + columnRight, + columnWidth, + width, left, - html='', + right, + html = '', eventElements, eventElement, triggerRes, - vsideCache={}, - hsideCache={}, - key, val, titleElement, height, slotSegmentContainer = getSlotSegmentContainer(), - rtl, dis, dit, - colCnt = getColCnt(); - - if (rtl = opt('isRTL')) { - dis = -1; - dit = colCnt - 1; - }else{ - dis = 1; - dit = 0; - } + isRTL = opt('isRTL'); // calculate position/dimensions, create html for (i=0; i" + "
" + "
" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "
" + "
" + - htmlEscape(event.title) + + htmlEscape(event.title || '') + "
" + "
" + "
"; @@ -4073,18 +4007,6 @@ function AgendaEventRenderer() { } - function bindDaySeg(event, eventElement, seg) { - if (isEventDraggable(event)) { - draggableDayEvent(event, eventElement, seg.isStart); - } - if (seg.isEnd && isEventResizable(event)) { - resizableDayEvent(event, eventElement, seg); - } - eventElementHandlers(event, eventElement); - // needs to be after, because resizableDayEvent might stopImmediatePropagation on click - } - - function bindSlotSeg(event, eventElement, seg) { var timeElement = eventElement.find('div.fc-event-time'); if (isEventDraggable(event)) { @@ -4103,32 +4025,34 @@ function AgendaEventRenderer() { // when event starts out FULL-DAY + // overrides DayEventRenderer's version because it needs to account for dragging elements + // to and from the slot area. - function draggableDayEvent(event, eventElement, isStart) { + function draggableDayEvent(event, eventElement, seg) { + var isStart = seg.isStart; var origWidth; var revert; - var allDay=true; + var allDay = true; var dayDelta; - var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapMinutes = getSnapMinutes(); var minMinute = getMinMinute(); eventElement.draggable({ - zIndex: 9, opacity: opt('dragOpacity', 'month'), // use whatever the month view was using revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origWidth = eventElement.width(); - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { + hoverListener.start(function(cell, origCell) { clearOverlays(); if (cell) { - //setOverflowHidden(true); revert = false; - dayDelta = colDelta * dis; + var origDate = cellToDate(0, origCell.col); + var date = cellToDate(0, cell.col); + dayDelta = dayDiff(date, origDate); if (!cell.row) { // on full-days renderDayOverlay( @@ -4159,7 +4083,6 @@ function AgendaEventRenderer() { revert = revert || (allDay && !dayDelta); }else{ resetElement(); - //setOverflowHidden(false); revert = true; } eventElement.draggable('option', 'revert', revert); @@ -4178,14 +4101,13 @@ function AgendaEventRenderer() { // changed! var minuteDelta = 0; if (!allDay) { - minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / snapHeight) + minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight) * snapMinutes + minMinute - (event.start.getHours() * 60 + event.start.getMinutes()); } eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); } - //setOverflowHidden(false); } }); function resetElement() { @@ -4203,79 +4125,147 @@ function AgendaEventRenderer() { // when event starts out IN TIMESLOTS function draggableSlotEvent(event, eventElement, timeElement) { - var origPosition; - var allDay=false; - var dayDelta; - var minuteDelta; - var prevMinuteDelta; - var dis = opt('isRTL') ? -1 : 1; - var hoverListener = getHoverListener(); + var coordinateGrid = t.getCoordinateGrid(); var colCnt = getColCnt(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapMinutes = getSnapMinutes(); + + // states + var origPosition; // original position of the element, not the mouse + var origCell; + var isInBounds, prevIsInBounds; + var isAllDay, prevIsAllDay; + var colDelta, prevColDelta; + var dayDelta; // derived from colDelta + var minuteDelta, prevMinuteDelta; + eventElement.draggable({ - zIndex: 9, scroll: false, - grid: [colWidth, snapHeight], + grid: [ colWidth, snapHeight ], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { + trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); + + coordinateGrid.build(); + + // initialize states origPosition = eventElement.position(); + origCell = coordinateGrid.cell(ev.pageX, ev.pageY); + isInBounds = prevIsInBounds = true; + isAllDay = prevIsAllDay = getIsCellAllDay(origCell); + colDelta = prevColDelta = 0; + dayDelta = 0; minuteDelta = prevMinuteDelta = 0; - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - eventElement.draggable('option', 'revert', !cell); - clearOverlays(); - if (cell) { - dayDelta = colDelta * dis; - if (opt('allDaySlot') && !cell.row) { - // over full days - if (!allDay) { - // convert to temporary all-day event - allDay = true; - timeElement.hide(); - eventElement.draggable('option', 'grid', null); - } - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - }else{ - // on slots - resetElement(); - } - } - }, ev, 'drag'); + }, drag: function(ev, ui) { - minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes; - if (minuteDelta != prevMinuteDelta) { - if (!allDay) { - updateTimeText(minuteDelta); + + // NOTE: this `cell` value is only useful for determining in-bounds and all-day. + // Bad for anything else due to the discrepancy between the mouse position and the + // element position while snapping. (problem revealed in PR #55) + // + // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event. + // We should overhaul the dragging system and stop relying on jQuery UI. + var cell = coordinateGrid.cell(ev.pageX, ev.pageY); + + // update states + isInBounds = !!cell; + if (isInBounds) { + isAllDay = getIsCellAllDay(cell); + + // calculate column delta + colDelta = Math.round((ui.position.left - origPosition.left) / colWidth); + if (colDelta != prevColDelta) { + // calculate the day delta based off of the original clicked column and the column delta + var origDate = cellToDate(0, origCell.col); + var col = origCell.col + colDelta; + col = Math.max(0, col); + col = Math.min(colCnt-1, col); + var date = cellToDate(0, col); + dayDelta = dayDiff(date, origDate); + } + + // calculate minute delta (only if over slots) + if (!isAllDay) { + minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes; } + } + + // any state changes? + if ( + isInBounds != prevIsInBounds || + isAllDay != prevIsAllDay || + colDelta != prevColDelta || + minuteDelta != prevMinuteDelta + ) { + + updateUI(); + + // update previous states for next time + prevIsInBounds = isInBounds; + prevIsAllDay = isAllDay; + prevColDelta = colDelta; prevMinuteDelta = minuteDelta; } + + // if out-of-bounds, revert when done, and vice versa. + eventElement.draggable('option', 'revert', !isInBounds); + }, stop: function(ev, ui) { - var cell = hoverListener.stop(); + clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); - if (cell && (dayDelta || minuteDelta || allDay)) { - // changed! - eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); - }else{ - // either no change or out-of-bounds (draggable has already reverted) - resetElement(); + + if (isInBounds && (isAllDay || dayDelta || minuteDelta)) { // changed! + eventDrop(this, event, dayDelta, isAllDay ? 0 : minuteDelta, isAllDay, ev, ui); + } + else { // either no change or out-of-bounds (draggable has already reverted) + + // reset states for next time, and for updateUI() + isInBounds = true; + isAllDay = false; + colDelta = 0; + dayDelta = 0; + minuteDelta = 0; + + updateUI(); eventElement.css('filter', ''); // clear IE opacity side-effects - eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position - updateTimeText(0); + + // sometimes fast drags make event revert to wrong position, so reset. + // also, if we dragged the element out of the area because of snapping, + // but the *mouse* is still in bounds, we need to reset the position. + eventElement.css(origPosition); + showEvents(event, eventElement); } } }); + + function updateUI() { + clearOverlays(); + if (isInBounds) { + if (isAllDay) { + timeElement.hide(); + eventElement.draggable('option', 'grid', null); // disable grid snapping + renderDayOverlay( + addDays(cloneDate(event.start), dayDelta), + addDays(exclEndDay(event), dayDelta) + ); + } + else { + updateTimeText(minuteDelta); + timeElement.css('display', ''); // show() was causing display=inline + eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping + } + } + } + function updateTimeText(minuteDelta) { var newStart = addMinutes(cloneDate(event.start), minuteDelta); var newEnd; @@ -4284,14 +4274,7 @@ function AgendaEventRenderer() { } timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); } - function resetElement() { - // convert back to original slot-event - if (allDay) { - timeElement.css('display', ''); // show() was causing display=inline - eventElement.draggable('option', 'grid', [colWidth, snapHeight]); - allDay = false; - } - } + } @@ -4312,7 +4295,6 @@ function AgendaEventRenderer() { start: function(ev, ui) { snapDelta = prevSnapDelta = 0; hideEvents(event, eventElement); - eventElement.css('z-index', 9); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { @@ -4335,7 +4317,6 @@ function AgendaEventRenderer() { if (snapDelta) { eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui); }else{ - eventElement.css('z-index', 8); showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } @@ -4347,23 +4328,211 @@ function AgendaEventRenderer() { } -function countForwardSegs(levels) { - var i, j, k, level, segForward, segBack; - for (i=levels.length-1; i>0; i--) { - level = levels[i]; - for (j=0; j seg2.start && seg1.start < seg2.end; +} + + +// A cmp function for determining which forward segment to rely on more when computing coordinates. +function compareForwardSlotSegs(seg1, seg2) { + // put higher-pressure first + return seg2.forwardPressure - seg1.forwardPressure || + // put segments that are closer to initial edge first (and favor ones with no coords yet) + (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) || + // do normal sorting... + compareSlotSegs(seg1, seg2); +} + + +// A cmp function for determining which segment should be closer to the initial edge +// (the left edge on a left-to-right calendar). +function compareSlotSegs(seg1, seg2) { + return seg1.start - seg2.start || // earlier start time goes first + (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first + (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title +} + ;; @@ -4378,13 +4547,13 @@ function View(element, calendar, viewName) { t.name = viewName; t.opt = opt; t.trigger = trigger; - //t.setOverflowHidden = setOverflowHidden; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; - t.reportEvents = reportEvents; + t.setEventData = setEventData; + t.clearEventData = clearEventData; t.eventEnd = eventEnd; t.reportEventElement = reportEventElement; - t.reportEventClear = reportEventClear; + t.triggerEventDestroy = triggerEventDestroy; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; @@ -4402,16 +4571,16 @@ function View(element, calendar, viewName) { // locals - var eventsByID = {}; - var eventElements = []; - var eventElementsByID = {}; + var eventsByID = {}; // eventID mapped to array of events (there can be multiple b/c of repeating events) + var eventElementsByID = {}; // eventID mapped to array of jQuery elements + var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system var options = calendar.options; function opt(name, viewNameOverride) { var v = options[name]; - if (typeof v == 'object') { + if ($.isPlainObject(v)) { return smartProperty(v, viewNameOverride || viewName); } return v; @@ -4425,26 +4594,37 @@ function View(element, calendar, viewName) { ); } - - /* - function setOverflowHidden(bool) { - element.css('overflow', bool ? 'hidden' : ''); - } - */ - + + + /* Event Editable Boolean Calculations + ------------------------------------------------------------------------------*/ + function isEventDraggable(event) { - return isEventEditable(event) && !opt('disableDragging'); + var source = event.source || {}; + return firstDefined( + event.startEditable, + source.startEditable, + opt('eventStartEditable'), + event.editable, + source.editable, + opt('editable') + ) + && !opt('disableDragging'); // deprecated } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true - return isEventEditable(event) && !opt('disableResizing'); - } - - - function isEventEditable(event) { - return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); + var source = event.source || {}; + return firstDefined( + event.durationEditable, + source.durationEditable, + opt('eventDurationEditable'), + event.editable, + source.editable, + opt('editable') + ) + && !opt('disableResizing'); // deprecated } @@ -4453,8 +4633,7 @@ function View(element, calendar, viewName) { ------------------------------------------------------------------------------*/ - // report when view receives new events - function reportEvents(events) { // events are already normalized at this point + function setEventData(events) { // events are already normalized at this point eventsByID = {}; var i, len=events.length, event; for (i=0; i