forked from timekit-io/booking-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.js
More file actions
695 lines (519 loc) · 20.8 KB
/
Copy pathrender.js
File metadata and controls
695 lines (519 loc) · 20.8 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
'use strict';
var interpolate = require('sprintf-js');
var $ = require('jquery');
var moment = window.moment = require('moment');
var stringify = require('json-stringify-safe');
window.fullcalendar = require('fullcalendar');
require('moment-timezone/builds/moment-timezone-with-data-2012-2022.js');
require('fullcalendar/dist/fullcalendar.css');
require('./styles/fullcalendar.scss');
require('./styles/utils.scss');
require('./styles/main.scss');
require('./styles/testmoderibbon.scss');
function InitRender(deps) {
var utils = deps.utils;
var sdk = deps.sdk;
var getConfig = deps.config.retrieve;
// DOM nodes
var rootTarget;
var calendarTarget;
var bookingPageTarget;
var loadingTarget;
var errorTarget;
// Make sure DOM element is ready and clean it
var prepareDOM = function(suppliedConfig) {
var targetElement = suppliedConfig.el || getConfig().el;
rootTarget = $(targetElement);
if (rootTarget.length === 0) {
throw triggerError('No target DOM element was found (' + targetElement + ')');
}
rootTarget.addClass('bookingjs');
rootTarget.children(':not(script)').remove();
};
// Fetch availabile time through Timekit SDK
var timekitFetchAvailability = function() {
var args = {};
if (getConfig().project_id) args.project_id = getConfig().project_id
if (getConfig().resources) args.resources = getConfig().resources
if (getConfig().availability_constraints) args.constraints = getConfig().availability_constraints
$.extend(args, getConfig().availability);
utils.doCallback('fetchAvailabilityStarted', args);
sdk
.makeRequest({
method: 'post',
url: '/availability',
data: args
})
.then(function(response){
utils.doCallback('fetchAvailabilitySuccessful', response);
hideLoadingScreen();
// Render available timeslots in FullCalendar
if(response.data.length > 0) renderCalendarEvents(response.data);
// Render test ribbon if enabled
if (response.headers['timekit-testmode']) renderTestModeRibbon();
}).catch(function(response){
utils.doCallback('fetchAvailabilityFailed', response);
hideLoadingScreen();
triggerError(['An error with Timekit Fetch Availability occured', response]);
});
};
// Fetch availabile time through Timekit SDK
var timekitGetBookingSlots = function() {
utils.doCallback('GetBookingSlotsStarted');
var requestData = {
url: '/bookings/groups',
method: 'get'
}
// scope group booking slots by widget ID if possible
if (getConfig().project_id) requestData.params = {
search: 'project.id:' + getConfig().project_id
}
sdk
.makeRequest(requestData)
.then(function(response){
var slots = response.data.map(function(item) {
return {
title: item.attributes.event_info.what,
start: item.attributes.event_info.start,
end: item.attributes.event_info.end,
booking: item
}
})
// Make sure to sort the slots chronologically,
// otherwise FullCalendar might skip rendering some of them
slots.sort(function(a, b) {
return moment(a.start) - moment(b.start);
})
utils.doCallback('getBookingSlotsSuccessful', response);
hideLoadingScreen();
// Render available timeslots in FullCalendar
if(slots.length > 0) renderCalendarEvents(slots);
// Render test ribbon if enabled
if (response.headers['timekit-testmode']) renderTestModeRibbon();
}).catch(function(response){
utils.doCallback('getBookingSlotsFailed', response);
hideLoadingScreen();
triggerError(['An error with Timekit Get Booking Slots occured', response]);
});
};
// Universal functional to retrieve availability through either findtime or group booking slots
var getAvailability = function() {
showLoadingScreen();
calendarTarget.fullCalendar('removeEventSources');
if (getConfig().booking.graph === 'group_customer' || getConfig().booking.graph === 'group_customer_payment') {
// If in group bookings mode, fetch slots
timekitGetBookingSlots();
} else {
// If in normal single-participant mode, call findtime
timekitFetchAvailability();
}
};
// Go to the first timeslot in a list of timeslots
var goToFirstEvent = function(firstEventStart) {
calendarTarget.fullCalendar('gotoDate', firstEventStart);
var firstEventStartHour = moment(firstEventStart).format('H');
scrollToTime(firstEventStartHour);
};
// Scrolls fullcalendar to the specified hour
var scrollToTime = function(time) {
// Only proceed for agendaWeek view
if (calendarTarget.fullCalendar('getView').name !== 'agendaWeek'){
return;
}
// Get height of each hour row
var slotDuration = calendarTarget.fullCalendar('option', 'slotDuration');
var slotDurationMinutes = 30;
if (slotDuration) slotDurationMinutes = slotDuration.slice(3, 5);
var hours = calendarTarget.find('.fc-slats .fc-minor');
var hourHeight = $(hours[0]).height() * (60 / slotDurationMinutes);
// If minTime is set in fullCalendar config, subtract that from the scollTo calculationn
var minTimeHeight = 0;
if (getConfig().fullcalendar.minTime) {
var minTime = moment(getConfig().fullcalendar.minTime, 'HH:mm:ss').format('H');
minTimeHeight = hourHeight * minTime;
}
// Calculate scrolling location and container sizes
var scrollTo = (hourHeight * time) - minTimeHeight;
var scrollable = calendarTarget.find('.fc-scroller');
var scrollableHeight = scrollable.height();
var scrollableScrollTop = scrollable.scrollTop();
var maximumHeight = scrollable.find('.fc-time-grid').height();
// Only perform the scroll if the scrollTo is outside the current visible boundary
if (scrollTo > scrollableScrollTop && scrollTo < scrollableScrollTop + scrollableHeight) {
return;
}
// If scrollTo point is past the maximum height, then scroll to maximum possible while still animating
if (scrollTo > maximumHeight - scrollableHeight) {
scrollTo = maximumHeight - scrollableHeight;
}
// Perform the scrollTo animation
scrollable.animate({scrollTop: scrollTo});
};
// Display ribbon if in testmode
var renderTestModeRibbon = function() {
var template = require('./templates/testmoderibbon.html');
var testModeRibbonTarget = $(template.render({
ribbonText: 'Test Mode',
}));
rootTarget.append(testModeRibbonTarget);
};
// Setup and render FullCalendar
var initializeCalendar = function() {
var sizing = decideCalendarSize(getConfig().fullcalendar.defaultView);
var args = {
height: sizing.height,
eventClick: clickTimeslot,
windowResize: function() {
var sizing = decideCalendarSize();
calendarTarget.fullCalendar('changeView', sizing.view);
calendarTarget.fullCalendar('option', 'height', sizing.height);
}
};
$.extend(true, args, getConfig().fullcalendar);
args.defaultView = sizing.view;
calendarTarget = $('<div class="bookingjs-calendar empty-calendar">');
rootTarget.append(calendarTarget);
calendarTarget.fullCalendar(args);
utils.doCallback('fullCalendarInitialized');
};
// Clicking a timeslot
var clickTimeslot = function(eventData) {
if (!getConfig().disable_confirm_page) {
showBookingPage(eventData)
} else {
$('.fc-event-clicked').removeClass('fc-event-clicked');
$(this).addClass('fc-event-clicked');
utils.doCallback('clickTimeslot', eventData);
}
};
// Fires when window is resized and calendar must adhere
var decideCalendarSize = function(currentView) {
currentView = currentView || calendarTarget.fullCalendar('getView').name
var view = getConfig().fullcalendar.defaultView
var height = 385;
if (rootTarget.width() < 480) {
rootTarget.addClass('is-small');
if (getConfig().ui.avatar) height -= 15;
if (currentView === 'agendaWeek' || currentView === 'basicDay') {
view = 'basicDay';
}
} else {
rootTarget.removeClass('is-small');
}
$.each(getConfig().customer_fields, function(key, field) {
if (field.format === 'textarea') height += 98;
else if (field.format === 'checkbox') height += 51;
else height += 66;
})
return {
height: height,
view: view
};
};
// Render the supplied calendar events in FullCalendar
var renderCalendarEvents = function(eventData) {
var firstEventStart = moment(eventData[0].start)
var firstEventEnd = moment(eventData[0].end)
var firstEventDuration = firstEventEnd.diff(firstEventStart, 'minutes')
if (firstEventDuration <= 90) {
calendarTarget.fullCalendar('option', 'slotDuration', '00:15:00')
}
calendarTarget.fullCalendar('addEventSource', {
events: eventData
});
calendarTarget.removeClass('empty-calendar');
// Go to first event if enabled
goToFirstEvent(eventData[0].start);
};
// Render the avatar image
var renderAvatarImage = function() {
var template = require('./templates/user-avatar.html');
var avatarTarget = $(template.render({
image: getConfig().ui.avatar
}));
rootTarget.addClass('has-avatar');
rootTarget.append(avatarTarget);
};
// Render the avatar image
var renderDisplayName = function() {
var template = require('./templates/user-displayname.html');
var displayNameTarget = $(template.render({
name: getConfig().ui.display_name
}));
rootTarget.addClass('has-displayname');
rootTarget.append(displayNameTarget);
};
// Show loading spinner screen
var showLoadingScreen = function() {
utils.doCallback('showLoadingScreen');
var template = require('./templates/loading.html');
loadingTarget = $(template.render({
loadingIcon: require('!svg-inline!./assets/loading-spinner.svg')
}));
rootTarget.append(loadingTarget);
};
// Remove the booking page DOM node
var hideLoadingScreen = function() {
utils.doCallback('hideLoadingScreen');
loadingTarget.removeClass('show');
setTimeout(function(){
loadingTarget.remove();
}, 500);
};
// Show error and warning screen
var triggerError = function(message) {
// If an error already has been thrown, exit
if (errorTarget) return message
utils.doCallback('errorTriggered', message);
utils.logError(message)
// If no target DOM element exists, only do the logging
if (!rootTarget) return message
var messageProcessed = message
var contextProcessed = null
if (utils.isArray(message)) {
messageProcessed = message[0]
if (message[1].data) {
contextProcessed = stringify(message[1].data.errors || message[1].data.error || message[1].data)
} else {
contextProcessed = stringify(message[1])
}
}
var template = require('./templates/error.html');
errorTarget = $(template.render({
errorWarningIcon: require('!svg-inline!./assets/error-warning-icon.svg'),
message: messageProcessed,
context: contextProcessed
}));
rootTarget.append(errorTarget);
return message
};
// Render customer fields
var renderCustomerFields = function () {
var textTemplate = require('./templates/fields/text.html');
var textareaTemplate = require('./templates/fields/textarea.html');
var selectTemplate = require('./templates/fields/select.html');
var checkboxTemplate = require('./templates/fields/checkbox.html');
var fieldsTarget = []
$.each(getConfig().customer_fields, function(key, field) {
var tmpl = textTemplate
if (field.format === 'textarea') tmpl = textareaTemplate
if (field.format === 'select') tmpl = selectTemplate
if (field.format === 'checkbox') tmpl = checkboxTemplate
if (!field.format) field.format = 'text'
if (key === 'email') field.format = 'email'
var data = $.extend({
key: key,
arrowDownIcon: require('!svg-inline!./assets/arrow-down-icon.svg')
}, field)
var fieldTarget = $(tmpl.render(data))
fieldsTarget.push(fieldTarget)
})
return fieldsTarget
}
// Event handler when a timeslot is clicked in FullCalendar
var showBookingPage = function(eventData) {
utils.doCallback('showBookingPage', eventData);
var template = require('./templates/booking-page.html');
var dateFormat = getConfig().ui.booking_date_format || moment.localeData().longDateFormat('LL');
var timeFormat = getConfig().ui.booking_time_format || moment.localeData().longDateFormat('LT');
var allocatedResource = eventData.resources ? eventData.resources[0].name : false;
bookingPageTarget = $(template.render({
chosenDate: moment(eventData.start).format(dateFormat),
chosenTime: moment(eventData.start).format(timeFormat) + ' - ' + moment(eventData.end).format(timeFormat),
allocatedResourcePrefix: getConfig().ui.localization.allocated_resource_prefix,
allocatedResource: allocatedResource,
closeIcon: require('!svg-inline!./assets/close-icon.svg'),
checkmarkIcon: require('!svg-inline!./assets/checkmark-icon.svg'),
loadingIcon: require('!svg-inline!./assets/loading-spinner.svg'),
errorIcon: require('!svg-inline!./assets/error-icon.svg'),
submitText: getConfig().ui.localization.submit_button,
successMessage: interpolate.sprintf(getConfig().ui.localization.success_message, '<span class="booked-email"></span>')
}));
var formFields = bookingPageTarget.find('.bookingjs-form-fields');
$(formFields).append(renderCustomerFields());
var form = bookingPageTarget.children('.bookingjs-form');
bookingPageTarget.children('.bookingjs-bookpage-close').click(function(e) {
e.preventDefault();
var bookingHasBeenCreated = $(form).hasClass('success');
if (bookingHasBeenCreated) getAvailability();
hideBookingPage();
});
if (eventData.resources) {
utils.logDebug(['Available resources for chosen timeslot:', eventData.resources]);
}
form.find('.bookingjs-form-input').on('input', function() {
var field = $(this).closest('.bookingjs-form-field');
if (this.value) field.addClass('bookingjs-form-field--dirty');
else field.removeClass('bookingjs-form-field--dirty');
});
form.submit(function(e) {
submitBookingForm(this, e, eventData);
});
// Show powered by Timekit message
if (getConfig().ui.show_credits) {
renderPoweredByMessage(bookingPageTarget);
}
$(document).on('keyup', function(e) {
// escape key maps to keycode `27`
if (e.keyCode === 27) { hideBookingPage(); }
});
rootTarget.append(bookingPageTarget);
setTimeout(function(){
bookingPageTarget.addClass('show');
}, 100);
};
// Remove the booking page DOM node
var hideBookingPage = function() {
utils.doCallback('closeBookingPage');
bookingPageTarget.removeClass('show');
setTimeout(function(){
bookingPageTarget.remove();
}, 200);
$(document).off('keyup');
};
// Event handler on form submit
var submitBookingForm = function(form, e, eventData) {
e.preventDefault();
var formElement = $(form);
if(formElement.hasClass('success')) {
getAvailability();
hideBookingPage();
return;
}
// Abort if form is submitting, have submitted or does not validate
if(formElement.hasClass('loading') || formElement.hasClass('error') || !e.target.checkValidity()) {
var submitButton = formElement.find('.bookingjs-form-button');
submitButton.addClass('button-shake');
setTimeout(function() {
submitButton.removeClass('button-shake');
}, 500);
return;
}
var formData = {};
$.each(formElement.serializeArray(), function(i, field) {
formData[field.name] = field.value;
});
formElement.addClass('loading');
utils.doCallback('submitBookingForm', formData);
// Call create event endpoint
timekitCreateBooking(formData, eventData).then(function(response){
formElement.find('.booked-email').html(formData.email);
formElement.removeClass('loading').addClass('success');
}).catch(function(response){
showBookingFailed(formElement)
});
};
var showBookingFailed = function (formElement) {
var submitButton = formElement.find('.bookingjs-form-button');
submitButton.addClass('button-shake');
setTimeout(function() {
submitButton.removeClass('button-shake');
}, 500);
formElement.removeClass('loading').addClass('error');
setTimeout(function() {
formElement.removeClass('error');
}, 2000);
}
// Create new booking
var timekitCreateBooking = function(formData, eventData) {
var nativeFields = ['name', 'email', 'location', 'comment', 'phone', 'voip']
var args = {
start: eventData.start.format(),
end: eventData.end.format(),
description: '',
customer: {
name: formData.name,
email: formData.email,
timezone: moment.tz.guess()
},
participants: [formData.email]
};
if (getConfig().project_id) {
args.project_id = getConfig().project_id
} else {
$.extend(true, args, {
what: 'Meeting with ' + formData.name,
where: 'TBD'
});
}
if (getConfig().customer_fields.location) {
args.customer.where = formData.location;
args.where = formData.location;
}
if (getConfig().customer_fields.comment) {
args.customer.comment = formData.comment;
args.description += (getConfig().customer_fields.comment.title || 'Comment') + ': ' + formData.comment + '\n';
}
if (getConfig().customer_fields.phone) {
args.customer.phone = formData.phone;
args.description += (getConfig().customer_fields.phone.title || 'Phone') + ': ' + formData.phone + '\n';
}
if (getConfig().customer_fields.voip) {
args.customer.voip = formData.voip;
args.description += (getConfig().customer_fields.voip.title || 'Voip') + ': ' + formData.voip + '\n';
}
// Save custom fields in meta object
$.each(getConfig().customer_fields, function(key, field) {
if (nativeFields.includes(key)) return
if (field.format === 'checkbox') formData[key] = !!formData[key]
args.customer[key] = formData[key]
args.description += (getConfig().customer_fields[key].title || key) + ': ' + formData[key] + '\n';
})
if (getConfig().booking.graph === 'group_customer' || getConfig().booking.graph === 'group_customer_payment') {
args.related = { owner_booking_id: eventData.booking.id }
args.resource_id = eventData.booking.resource.id
} else if (typeof eventData.resources === 'undefined' || eventData.resources.length === 0) {
throw triggerError(['No resources to pick from when creating booking']);
} else {
args.resource_id = eventData.resources[0].id
}
$.extend(true, args, getConfig().booking);
utils.doCallback('createBookingStarted', args);
var requestHeaders = {
'Timekit-OutputTimestampFormat': 'Y-m-d ' + getConfig().ui.localization.email_time_format + ' (P e)'
};
var request = sdk
.include(getConfig().create_booking_response_include)
.headers(requestHeaders)
.createBooking(args);
request
.then(function(response){
utils.doCallback('createBookingSuccessful', response);
}).catch(function(response){
utils.doCallback('createBookingFailed', response);
triggerError(['An error with Timekit Create Booking occured', response]);
});
return request;
};
// Render the powered by Timekit message
var renderPoweredByMessage = function(pageTarget) {
var campaignName = 'widget'
var campaignSource = window.location.hostname.replace(/\./g, '-')
if (getConfig().project_id) { campaignName = 'embedded-widget'; }
if (getConfig().project_slug) { campaignName = 'hosted-widget'; }
var template = require('./templates/poweredby.html');
var timekitLogo = require('!svg-inline!./assets/timekit-logo.svg');
var poweredTarget = $(template.render({
timekitLogo: timekitLogo,
campaignName: campaignName,
campaignSource: campaignSource
}));
pageTarget.append(poweredTarget);
};
// The fullCalendar object for advanced puppeting
var fullCalendar = function() {
if (calendarTarget.fullCalendar === undefined) { return undefined; }
return calendarTarget.fullCalendar.apply(calendarTarget, arguments);
};
return {
prepareDOM: prepareDOM,
getAvailability: getAvailability,
initializeCalendar: initializeCalendar,
renderAvatarImage: renderAvatarImage,
renderDisplayName: renderDisplayName,
triggerError: triggerError,
timekitCreateBooking: timekitCreateBooking,
fullCalendar: fullCalendar
}
}
module.exports = InitRender