forked from esleducation/week-planner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.week-planner.js
445 lines (361 loc) · 13.1 KB
/
jquery.week-planner.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* jQuery Week Planner - v0.1
* Display a full week as a table and allow to add reserved time on it.
* http://www.esl-education.org
*
* Made by Luca Pillonel - ESL Education
* Under MIT License
*/
;(function ($, window, document, undefined) {
"use strict";
// Create the defaults once
var pluginName = "weekPlanner",
defaults = {
weekDays : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
timeSlotsPerHour : 2,
slotHeight : 15,
minimumDurationInSlot : 4,
startHour : 7,
endHour : 20,
columnsHeaderHeight : 30,
preventOverlapping : true,
slots : [],
removeClass: 'icon-remove-sign',
hourFormat: 'HH:mm'
};
// The actual plugin constructor
function Plugin (element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
if (typeof this.settings.slotClass == 'undefined' && $(element).data('slotClass')){
this.settings.slotClass = $(element).data('slotClass');
}
this._defaults = defaults;
this._name = pluginName;
// Internal vars
this.columnsWrapper = null;
this.drawingSlot = null;
this.slots = {};
this.changedCallbacks = [];
this.initCallbacks = [];
this.initialized = false;
// Start plugin
this.init();
}
Plugin.prototype = {
init : function () {
// Create element structure
this.createDOMStructure();
// Populate existings slots
this.setSlots();
// Set zone creation events
this.setEvents();
this.fireInit();
this.initialized = true;
},
createDOMStructure : function(){
var totalSlots = (this.settings.endHour - this.settings.startHour) * this.settings.timeSlotsPerHour + 1;
// Create wrapper for columns
this.columnsWrapper = $('<div class="week-planner-columns-wrapper"><div class="week-planner-slots-header" /></div>')
.appendTo(this.element)
.css({ height : (totalSlots-1) * this.settings.slotHeight + this.settings.columnsHeaderHeight + 'px'});
// Create wrapper for slots
var slotsWrapper = $('<div class="week-planner-grid-wrapper"></div>').appendTo(this.element);
var columnsHeader = $('<div class="week-planner-slot-header"><div /></div>').appendTo(slotsWrapper);
// Create time slot in background
var line = $('<div class="week-planner-grid-line" />').css({height : this.settings.slotHeight});
for (var i = 0; i < totalSlots-1; i++) {
var iLine = line.clone().appendTo(slotsWrapper);
if(i%this.settings.timeSlotsPerHour == 0) {
iLine.addClass('hour');
$('<span>'+(this.settings.startHour + i/this.settings.timeSlotsPerHour)+':00</span>').appendTo(iLine);
}
};
// Create column for each
for(var i = 1; i <= this.settings.weekDays.length; i++) {
$('<div class="day-name">'+this.settings.weekDays[i-1]+'</div>').appendTo(columnsHeader);
var column = $('<div class="week-planner-column-day day-'+i+'" />').data('day', i).appendTo(this.columnsWrapper);
}
},
setEvents : function(){
this.columnsWrapper
.bind('mousedown', function(e){
var $target = $(e.target),
posY = e.originalEvent.layerY - this.settings.columnsHeaderHeight;
if(posY > 0 && $target.hasClass('week-planner-column-day')) {
// Determine closest Y value snaped to grid
posY -= posY%this.settings.slotHeight;
// Create slot
this.drawingSlot = this.createSlot(posY + this.settings.columnsHeaderHeight, this.settings.slotHeight * this.settings.minimumDurationInSlot, $target.data('day')).addClass("drawing").appendTo($target);
// Detect overlapping
this.detectOverlapping();
// Update info display
this.updateInfo();
}
}.bind(this))
.bind('mousemove', function(e){
if(this.drawingSlot) {
// Get position relative to current slot
var posY = e.pageY - this.drawingSlot.offset().top;
// Snap posY to grid
posY += (this.settings.slotHeight / 2) - posY%this.settings.slotHeight < 0 ? (this.settings.slotHeight / 2) - Math.abs((this.settings.slotHeight / 2) - posY%this.settings.slotHeight) : ((this.settings.slotHeight / 2) - Math.abs((this.settings.slotHeight / 2) - posY%this.settings.slotHeight)) * -1;
var height = posY;
// fix min height
if(height / this.settings.slotHeight < this.settings.minimumDurationInSlot) height = this.settings.slotHeight * this.settings.minimumDurationInSlot;
// Draw corrected height
this.drawingSlot.css({ height : height});
// Detect overlapping
this.detectOverlapping();
// Update info display
this.updateInfo();
}
}.bind(this))
.bind('mouseup', function(e){
if(this.drawingSlot) {
if( ! this.drawingSlot.hasClass('overlapping') || ! this.settings.preventOverlapping) {
// Get time values
var time = this.getTimeForSlot();
time.slot = this.drawingSlot;
// Save values somewhere
this.slots[this.drawingSlot.data('day')] = this.slots[this.drawingSlot.data('day')] || [];
var pos = this.slots[this.drawingSlot.data('day')].push(time) - 1;
// Save a reference in slot itself
this.drawingSlot.data('slotPos', pos);
// Enable controls
this.setControls();
// Enable events
this.drawingSlot.removeClass('drawing');
this.fireChanged();
} else {
this.drawingSlot.remove();
this.drawingSlot = null;
}
// Clear temp element
this.drawingSlot = null;
}
}.bind(this))
.bind('mouseleave', function(e){
if(this.drawingSlot) {
this.drawingSlot.remove();
this.drawingSlot = null;
}
}.bind(this));
},
updateInfo : function(slot){
slot = slot || this.drawingSlot;
// Get date
var date = this.getDateForSlot(slot);
// Update display
$('.slot-info', slot).html(date.start.format(this.settings.hourFormat) + ' - ' + date.end.format(this.settings.hourFormat));
},
setControls : function(slot){
slot = slot || this.drawingSlot;
// Add controls
var controls = $('<div class="controls"></div>').appendTo(slot),
close = $('<i class="'+this.settings.removeClass+'" />').appendTo(controls);
close.bind('click', function(){
// Get day
var day = slot.data('day'),
id = null;
// Look for slot id in slots list
var id = $.map(this.slots[day], function(otherSlot, i){
if(otherSlot.slot[0] == slot[0])
return id = i;
}.bind(this))[0];
// Remove slot
this.slots[day].splice(id, 1);
slot.remove();
$.each(this.slots[day], function(i, otherSlot){
this.detectOverlapping(otherSlot.slot);
}.bind(this));
this.fireChanged();
}.bind(this));
},
getTimeForSlot : function(slot) {
slot = slot || this.drawingSlot;
// Get values from dimension :)
return {
start : parseInt((this.settings.startHour * 60) + (slot.position().top - this.settings.columnsHeaderHeight) / this.settings.slotHeight * (60 / this.settings.timeSlotsPerHour)),
duration : slot.outerHeight() / this.settings.slotHeight * (60 / this.settings.timeSlotsPerHour)
}
},
getDateForSlot: function(slot){
return(this.getDateForTime(this.getTimeForSlot(slot)));
},
getDateForTime: function(time){
return {
start : moment(this.minutesToHourString(time.start), 'HH:mm'),
end : moment(this.minutesToHourString(time.start + time.duration), 'HH:mm')
}
},
minutesToHourString(minutes){
var str = '';
var hours = parseInt(minutes/60);
if (hours < 10){
str += '0';
}
str += hours+":";
if (minutes - (hours * 60) < 10){
str += "0";
}
str += (minutes - (hours * 60));
return str;
},
detectOverlapping : function(slot){
slot = slot || this.drawingSlot;
// Get time for slot
var time = this.getTimeForSlot(slot),
timeEnd = time.start + time.duration,
overlapping = false;
// Overlap an other slot
if(this.slots[slot.data('day')]) {
// Look for each slots of same day
$.each(this.slots[slot.data('day')], function(i, otherSlot){
if(slot[0] == otherSlot.slot[0] && this.slots[slot.data('day')].length == 1) {
slot.removeClass('overlapped');
} else if(slot[0] != otherSlot.slot[0]) {
var slotEnd = otherSlot.start + otherSlot.duration;
// Beginning or ending is overlapping
if(time.start >= otherSlot.start && time.start < slotEnd || timeEnd > otherSlot.start && timeEnd <= slotEnd || time.start <= otherSlot.start && timeEnd >= slotEnd) {
overlapping = true;
! this.settings.preventOverlapping && otherSlot.slot.addClass('overlapped');
} else {
otherSlot.slot.removeClass('overlapped');
}
}
}.bind(this));
}
// Overlap end of period
if(timeEnd > this.settings.endHour * 60) {
overlapping = true;
}
if(overlapping) {
if(this.settings.preventOverlapping) {
slot.addClass('overlapping').removeClass('overlapper');
} else {
slot.addClass('overlapper').removeClass('overlapping');
}
} else {
slot.removeClass('overlapping').removeClass('overlapper');
}
return overlapping;
},
createSlot : function(top, height, day){
return $('<div class="slot"><div class="filler" /><div class="slot-info"></div></zone>').data('day', day).css({
top : top,
height : height
});
},
createSlotWithParam : function(params){
// Calculate start in minutes
var start = parseInt(params.start.split(':')[0]*60)+parseInt(params.start.split(':')[1]);
// Get right column
var column = $('.day-'+params.day, this.element);
// Determine elements size from time
var top = (start / 60 - this.settings.startHour) * (this.settings.timeSlotsPerHour * this.settings.slotHeight) + this.settings.columnsHeaderHeight,
height = params.duration * this.settings.timeSlotsPerHour * this.settings.slotHeight / 60;
// Create a new element with right size
var slot = this.createSlot(top, height, params.day).appendTo(column);
// Update info display
this.updateInfo(slot);
// Get time values
var time = {
start : start,
duration : params.duration,
slot : slot
}
// Save values somewhere
this.slots[params.day] = this.slots[params.day] || [];
var pos = this.slots[params.day].push(time) - 1;
// Save a reference in slot itself
slot.data('slotPos', pos);
// Enable controls
this.setControls(slot);
this.fireChanged();
},
fireChanged: function(){
this.changedCallbacks.forEach(function(callback){
callback.call(this);
});
},
fireInit: function(){
this.initCallbacks.forEach(function(callback){
callback.call(this);
});
this.initCallbacks = [];
},
// Public method as specified below
setSlots : function(slots, groupedByDay){
slots = slots || this.settings.slots;
if(groupedByDay === true) {
$.each(slots, function(i, day){
$.each(day.periods, function(j, period){
this.createSlotWithParam({
start : period.hour,
duration : period.duration,
day : day.weekday.id
});
}.bind(this));
}.bind(this));
} else {
$.each(slots, function(i, slot){
this.createSlotWithParam(slot);
}.bind(this));
}
},
// Public method as specified below
getSlots : function(){
// Clean slots
var slots = {};
var slotClass = typeof this.settings.slotClass != 'undefined' ? this.settings.slotClass : false;
var self = this;
$.each(this.slots, function(key, day){
slots[key] = {
weekday : {
id : key
},
periods : []
};
if (slotClass){
slots[key]['class'] = slotClass;
}
$.each(day, function(i, slot){
slots[key].periods.push(self.getDateForTime(slot));
});
});
return slots;
},
onSlotsChanged: function(callback){
this.changedCallbacks.push(callback);
},
onInitialized: function(callback){
this.initCallbacks.push(callback);
if (this.initialized)
this.fireInit();
},
clear: function(){
$.each(this.slots, function(){
$.each(this, function(){
this.slot.find('.icon-remove-sign').trigger('click');
});
});
}
};
// Set a list of public methods
var public_methods = ['setSlots', 'getSlots', 'onSlotsChanged', 'onInitialized', 'clear'];
// Lightweight plugin wrapper preventing multiple instantiations
$.fn[pluginName] = function(methodOrOptions, options, extraoptions){
if (public_methods.indexOf(methodOrOptions) > -1){
return this.first().data("plugin_" + pluginName)[methodOrOptions](options, extraoptions);
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return this.each(function() {
if ( ! $.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, methodOrOptions));
}
});
} else {
//$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
})(jQuery, window, document);