This repository has been archived by the owner on Sep 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 728
/
calendar.js
365 lines (324 loc) · 15.9 KB
/
calendar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
* AngularJs Fullcalendar Wrapper for the JQuery FullCalendar
* API @ http://arshaw.com/fullcalendar/
*
* Angular Calendar Directive that takes in the [eventSources] nested array object as the ng-model and watches it deeply changes.
* Can also take in multiple event urls as a source object(s) and feed the events per view.
* The calendar will watch any eventSource array and update itself when a change is made.
*
*/
angular.module('ui.calendar', [])
.constant('uiCalendarConfig', {
calendars : {}
})
.controller('uiCalendarCtrl', ['$scope', '$locale',
function ($scope, $locale) {
var sources = $scope.eventSources;
var extraEventSignature = $scope.calendarWatchEvent ? $scope.calendarWatchEvent : angular.noop;
var wrapFunctionWithScopeApply = function (functionToWrap) {
return function () {
// This may happen outside of angular context, so create one if outside.
if ($scope.$root.$$phase) {
return functionToWrap.apply(this, arguments);
}
var args = arguments;
var that = this;
return $scope.$root.$apply(
function () {
return functionToWrap.apply(that, args);
}
);
};
};
var eventSerialId = 1;
// @return {String} fingerprint of the event object and its properties
this.eventFingerprint = function (e) {
if (!e._id) {
e._id = eventSerialId++;
}
var extraSignature = extraEventSignature({
event : e
}) || '';
var start = moment.isMoment(e.start) ? e.start.unix() : (e.start ? moment(e.start).unix() : '');
var end = moment.isMoment(e.end) ? e.end.unix() : (e.end ? moment(e.end).unix() : '');
// This extracts all the information we need from the event. http://jsperf.com/angular-calendar-events-fingerprint/3
return [e._id, e.id || '', e.title || '', e.url || '', start, end, e.allDay || '', e.className || '', extraSignature].join('');
};
var sourceSerialId = 1;
var sourceEventsSerialId = 1;
// @return {String} fingerprint of the source object and its events array
this.sourceFingerprint = function (source) {
var fp = '' + (source.__id || (source.__id = sourceSerialId++));
var events = angular.isObject(source) && source.events;
if (events) {
fp = fp + '-' + (events.__id || (events.__id = sourceEventsSerialId++));
}
return fp;
};
// @return {Array} all events from all sources
this.allEvents = function () {
return Array.prototype.concat.apply(
[],
(sources || []).reduce(
function (previous, source) {
if (angular.isArray(source)) {
previous.push(source);
} else if (angular.isObject(source) && angular.isArray(source.events)) {
var extEvent = Object.keys(source).filter(
function (key) {
return (key !== '_id' && key !== 'events');
}
);
source.events.forEach(
function (event) {
angular.extend(event, extEvent);
}
);
previous.push(source.events);
}
return previous;
},
[]
)
);
};
// Track changes in array of objects by assigning id tokens to each element and watching the scope for changes in the tokens
// @param {Array|Function} arraySource array of objects to watch
// @param tokenFn {Function} that returns the token for a given object
// @return {Object}
// subscribe: function(scope, function(newTokens, oldTokens))
// called when source has changed. return false to prevent individual callbacks from firing
// onAdded/Removed/Changed:
// when set to a callback, called each item where a respective change is detected
this.changeWatcher = function (arraySource, tokenFn) {
var self;
var getTokens = function () {
return ((angular.isFunction(arraySource) ? arraySource() : arraySource) || []).reduce(
function (rslt, el) {
var token = tokenFn(el);
map[token] = el;
rslt.push(token);
return rslt;
},
[]
);
};
// @param {Array} a
// @param {Array} b
// @return {Array} elements in that are in a but not in b
// @example
// subtractAsSets([6, 100, 4, 5], [4, 5, 7]) // [6, 100]
var subtractAsSets = function (a, b) {
var obj = (b || []).reduce(
function (rslt, val) {
rslt[val] = true;
return rslt;
},
Object.create(null)
);
return (a || []).filter(
function (val) {
return !obj[val];
}
);
};
// Map objects to tokens and vice-versa
var map = {};
// Compare newTokens to oldTokens and call onAdded, onRemoved, and onChanged handlers for each affected event respectively.
var applyChanges = function (newTokens, oldTokens) {
var i;
var token;
var replacedTokens = {};
var removedTokens = subtractAsSets(oldTokens, newTokens);
for (i = 0; i < removedTokens.length; i++) {
var removedToken = removedTokens[i];
var el = map[removedToken];
delete map[removedToken];
var newToken = tokenFn(el);
// if the element wasn't removed but simply got a new token, its old token will be different from the current one
if (newToken === removedToken) {
self.onRemoved(el);
} else {
replacedTokens[newToken] = removedToken;
self.onChanged(el);
}
}
var addedTokens = subtractAsSets(newTokens, oldTokens);
for (i = 0; i < addedTokens.length; i++) {
token = addedTokens[i];
if (!replacedTokens[token]) {
self.onAdded(map[token]);
}
}
};
self = {
subscribe : function (scope, onArrayChanged) {
scope.$watch(getTokens, function (newTokens, oldTokens) {
var notify = !(onArrayChanged && onArrayChanged(newTokens, oldTokens) === false);
if (notify) {
applyChanges(newTokens, oldTokens);
}
}, true);
},
onAdded : angular.noop,
onChanged : angular.noop,
onRemoved : angular.noop
};
return self;
};
this.getFullCalendarConfig = function (calendarSettings, uiCalendarConfig) {
var config = {};
angular.extend(config, uiCalendarConfig);
angular.extend(config, calendarSettings);
angular.forEach(config, function (value, key) {
if (typeof value === 'function') {
config[key] = wrapFunctionWithScopeApply(config[key]);
}
});
return config;
};
this.getLocaleConfig = function (fullCalendarConfig) {
if (!fullCalendarConfig.lang && !fullCalendarConfig.locale || fullCalendarConfig.useNgLocale) {
// Configure to use locale names by default
var tValues = function (data) {
// convert {0: "Jan", 1: "Feb", ...} to ["Jan", "Feb", ...]
return (Object.keys(data) || []).reduce(
function (rslt, el) {
rslt.push(data[el]);
return rslt;
},
[]
);
};
var dtf = $locale.DATETIME_FORMATS;
return {
monthNames : tValues(dtf.MONTH),
monthNamesShort : tValues(dtf.SHORTMONTH),
dayNames : tValues(dtf.DAY),
dayNamesShort : tValues(dtf.SHORTDAY)
};
}
return {};
};
}
])
.directive('uiCalendar', ['uiCalendarConfig',
function (uiCalendarConfig) {
return {
restrict : 'A',
scope : {
eventSources : '=ngModel',
calendarWatchEvent : '&'
},
controller : 'uiCalendarCtrl',
link : function (scope, elm, attrs, controller) {
var sources = scope.eventSources;
var sourcesChanged = false;
var calendar;
var eventSourcesWatcher = controller.changeWatcher(sources, controller.sourceFingerprint);
var eventsWatcher = controller.changeWatcher(controller.allEvents, controller.eventFingerprint);
var options = null;
function getOptions () {
var calendarSettings = attrs.uiCalendar ? scope.$parent.$eval(attrs.uiCalendar) : {};
var fullCalendarConfig = controller.getFullCalendarConfig(calendarSettings, uiCalendarConfig);
var localeFullCalendarConfig = controller.getLocaleConfig(fullCalendarConfig);
angular.extend(localeFullCalendarConfig, fullCalendarConfig);
options = {
eventSources : sources
};
angular.extend(options, localeFullCalendarConfig);
//remove calendars from options
options.calendars = null;
var options2 = {};
for (var o in options) {
if (o !== 'eventSources') {
options2[o] = options[o];
}
}
return JSON.stringify(options2);
}
scope.destroyCalendar = function () {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar('destroy');
}
if (attrs.calendar) {
calendar = uiCalendarConfig.calendars[attrs.calendar] = angular.element(elm).html('');
} else {
calendar = angular.element(elm).html('');
}
};
scope.initCalendar = function () {
if (!calendar) {
calendar = $(elm).html('');
}
calendar.fullCalendar(options);
if (attrs.calendar) {
uiCalendarConfig.calendars[attrs.calendar] = calendar;
}
};
scope.$on('$destroy', function () {
scope.destroyCalendar();
});
eventSourcesWatcher.onAdded = function (source) {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar(options);
if (attrs.calendar) {
uiCalendarConfig.calendars[attrs.calendar] = calendar;
}
calendar.fullCalendar('addEventSource', source);
sourcesChanged = true;
}
};
eventSourcesWatcher.onRemoved = function (source) {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar('removeEventSource', source);
sourcesChanged = true;
}
};
eventSourcesWatcher.onChanged = function () {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar('refetchEvents');
sourcesChanged = true;
}
};
eventsWatcher.onAdded = function (event) {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar('renderEvent', event, !!event.stick);
}
};
eventsWatcher.onRemoved = function (event) {
if (calendar && calendar.fullCalendar) {
calendar.fullCalendar('removeEvents', event._id);
}
};
eventsWatcher.onChanged = function (event) {
if (calendar && calendar.fullCalendar) {
var clientEvents = calendar.fullCalendar('clientEvents', event._id);
for (var i = 0; i < clientEvents.length; i++) {
var clientEvent = clientEvents[i];
clientEvent = angular.extend(clientEvent, event);
calendar.fullCalendar('updateEvent', clientEvent);
}
}
};
eventSourcesWatcher.subscribe(scope);
eventsWatcher.subscribe(scope, function () {
if (sourcesChanged === true) {
sourcesChanged = false;
// return false to prevent onAdded/Removed/Changed handlers from firing in this case
return false;
}
});
scope.$watch(getOptions, function (newValue, oldValue) {
if (newValue !== oldValue) {
scope.destroyCalendar();
scope.initCalendar();
} else if ((newValue && angular.isUndefined(calendar))) {
scope.initCalendar();
}
});
}
};
}
]
);