-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajaxify.js
471 lines (395 loc) · 14.3 KB
/
ajaxify.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
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
/**
* Setting the class 'ajaxify' on a hyperlink will open the target URL inline in the current document,
* without an IFrame, either as a bootstrap modal or in a specified container element (the 'target').
* The hyperlinks' click will be converted into an ajax request, and the contents of the response patched into the target element.
*
* By default, the <main> element of the requested page will be cut out. You can override this by specifying 'data-content-selector'.
*
* This library attempts to provide a bridge between opening responses in IFrames and going full SPA (single-page-application).
*
* Note that this approach has certain limitations:
* - the document.ready event will not be fired again for the requested page
* - none of the requested page's link, script or style tags will be loaded
*/
(function () {
let modalTarget;
let panelTarget;
/**
* Gets the target element, to which we add the contents of the response.
* This is either a bootstrap modal, or a simple div.
* The target object provides an abstraction of those 2 cases with an element property and a fill, show and clear function.
*/
function getTarget(useModal) {
if (useModal) {
return modalTarget || (modalTarget = createModalTarget());
} else {
return panelTarget || (panelTarget = createPanelTarget());
}
}
/**
* Creates an interface target object for loading the response in a bootstrap modal.
*
* @returns {object} The interface object.
*/
function createModalTarget() {
const boostrapVersion = typeof window.bootstrap === 'undefined'
? typeof $.fn === 'undefined' || typeof $.fn.tooltip === 'undefined'
? undefined
: $.fn.tooltip.Constructor.VERSION
: window.bootstrap.Tooltip.VERSION;
if (!boostrapVersion || typeof boostrapVersion !== 'string') {
throw new Error('Bootstrap version could not be identified.');
}
const isBootstrap3 = boostrapVersion.substring(0, 1) === '3';
const isBootstrap4 = boostrapVersion.substring(0, 1) === '4';
// we only have one modal and reuse it
// this keeps the page clean of duplicate IDs and events on nodes that will never again been shown
// the contents of the modal will be removed, when the modal is closed
const modal = createModal();
$('body').append(modal);
function createModalCloseButton() {
if (isBootstrap3 || isBootstrap4) {
return $('<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>')
} else {
return $('<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>')
}
}
/**
* Creates a bootstrap modal.
*
* @returns The modal.
*/
function createModal() {
const modal = $('<div class="modal fade ajax-response-target" role="dialog">'),
modalDialog = $('<div class="modal-dialog">'),
modalContent = $('<div class="modal-content">'),
modalBody = $('<div class="modal-body">'),
modalHeader = $('<div class="modal-header">'),
modalCloseButton = createModalCloseButton();
// bootstrap 3 uses float layout, so it makes sense to add the close button first
if (isBootstrap3) {
modalHeader.append(modalCloseButton);
modalContent.append(modalHeader);
} else {
modalContent.append(modalHeader);
modalHeader.append(modalCloseButton);
}
modalContent.append(modalBody);
modalDialog.append(modalContent);
modal.append(modalDialog);
return modal;
}
/**
* Clear the bootstrap modal content after the hide event was issued, in order to avoid unnecessary event registrations, duplicate IDs and such.
*/
modal.on('hidden.bs.modal', function () {
const args = {
target: that
};
$('body').trigger('ajaxify:closing', args);
that.clear(args);
$('body').trigger('ajaxify:closed', args);
});
/**
* Handles a user request to close the panel.
*/
modal.on(
'ajaxify:close',
() => that.hide({
target: that
}));
const that = {
element: modal.get(0),
/**
* Puts HTML content into the modal.
*
* @param {string} bodyContent The HTML content to add.
* @param {string} title The title text (only applies to modals).
* @param {string} size The size (either nothing for default size, large or small, only applies to modals).
*/
fill: function (bodyContent, title, size, args) {
that.clear(args);
const modalHeader = modal.find('.modal-header');
const modalBody = modal.find('.modal-body');
const modalDialog = modal.find('.modal-dialog');
if (isBootstrap3) {
// restore the close button
modalHeader.append(createModalCloseButton());
}
if (title) {
const titleHeader = $('<h5>');
titleHeader.text(title);
modalHeader.append(titleHeader);
}
if (!isBootstrap3) {
// restore the close button
modalHeader.append(createModalCloseButton());
}
if (size === 'large') {
modalDialog.addClass('modal-lg');
} else if (size === 'small') {
modalDialog.addClass('modal-sm');
}
modalBody.append(bodyContent);
},
/**
* Lazily adds the modal to the page, if necessary.
*/
append: function (_, args) {
// nothing to do, we have one modal and we reuse it
},
/**
* Displays the modal, if it is not already visible.
*/
show: function (_, args) {
// show the modal, if it is not already visible
modal.modal('show');
$('body').trigger('ajaxify:opened', args);
},
/**
* Hides the modal and clears it.
*/
hide: function (args) {
$('body').trigger('ajaxify:closing', args);
modal.modal('hide');
that.clear(args);
$('body').trigger('ajaxify:closed', args);
},
/**
* We call this when the current modal is being closed, or before its content is being replaced.
*/
clear: function (args) {
const modalHeader = modal.find('.modal-header');
const modalBody = modal.find('.modal-body');
const modalDialog = modal.find('.modal-dialog');
modalHeader.empty();
modalBody.empty();
modalDialog.removeClass('modal-sm');
modalDialog.removeClass('modal-lg');
$('body').trigger('ajaxify:cleared', args);
}
};
return that;
}
/**
* Creates an interface target object for loading the response in a div.
*
* @returns {object} The interface object.
*/
function createPanelTarget() {
const panel = $('<div class="ajax-response-target">');
/**
* Handles a user request to close the panel.
*/
panel.on(
'ajaxify:close',
() => that.hide({
target: that
}));
const that = {
element: panel.get(0),
/**
* Puts HTML content into the panel.
*
* @param {string} bodyContent The HTML content to add.
* @param {string} title The title text (only applies to modals).
* @param {string} size The size (either nothing for default size, large or small, only applies to modals).
*/
fill: function (bodyContent, title, size, args) {
that.clear(args);
panel.append(bodyContent);
},
/**
* Lazily adds the panel into the target container, if necessary.
*
* @param {string} targetContainerSelector A DOM selector that determines where the request content should be placed on the page.
*/
append: function (targetContainerSelector, args) {
if (!targetContainerSelector) {
console.error('ajaxify: Target element must be specified when modals are disabled.');
return;
}
const targetContainer = $(targetContainerSelector);
if (targetContainer.length !== 1) {
console.error('ajaxify: Target element not found or ambiguous selector.');
return;
}
panel.parent().removeClass('in');
targetContainer.append(panel);
},
/**
* Displays the panel, if it is not already visible.
*
* @param {string} targetContainerSelector A DOM selector that determines where the request content should be placed on the page.
*/
show: function (targetContainerSelector, args) {
if (!targetContainerSelector) {
console.error('ajaxify: Target element must be specified when modals are disabled.');
return;
}
const targetContainer = $(targetContainerSelector);
if (targetContainer.length !== 1) {
console.error('ajaxify: Target element not found or ambiguous selector.');
return;
}
targetContainer.addClass('in');
$('body').trigger('ajaxify:opened', args);
},
/**
* Hides the panel and clears it.
*/
hide: function (args) {
$('body').trigger('ajaxify:closing', args);
panel.parent().removeClass('in');
// let animaions run through
setTimeout(function () {
that.clear();
$('body').trigger('ajaxify:closed', args);
}, 300);
},
/**
* We call this when the current panel is being closed, or before its content is being replaced.
*/
clear: function (args) {
panel.empty();
$('body').trigger('ajaxify:cleared', args);
}
};
return that;
}
/**
* Parses a response and gets the HTML contents of the body, if it exists.
*
* @param {string} responseText The HTML code of the response we want to parse.
* @param {string} contentSelector The DOM selector that selects the part of the page that should be rendered.
* @return The contents of the response document's body as a jQuery.
*/
function parseBody(responseText, contentSelector) {
const bodyMatchArray = responseText.match(/<body[^>]*>[\s\S]*<\/body>/gi);
if (!bodyMatchArray || bodyMatchArray.length === 0) {
return undefined;
}
// search the body for a fitting content element -
// either the specified contentSelector, the < main > element or the whole body, if nothing was specified
// important: add contents to an empty div, otherwise find won't find anything if the main is the direct child
const body = $('<div>').append(bodyMatchArray[0]);
if (contentSelector) {
return body.find(contentSelector).children();
} else {
const main = body.find('main');
if (main.length === 1) {
return main.children();
} else {
return body.children();
}
}
}
/**
* Reads the HTML contents from a response, and puts it into the target element.
*
* @param {object} response The AJAX response, as in the ajax success callback.
*/
function openResponse(response, args) {
const responseText = response.responseText;
const target = args.target;
const settings = args.settings;
if (!responseText) {
console.error('ajaxify: The page could not be displayed (responseText was empty).');
const errorMessage = $('<p>');
errorMessage.text('' + response.status + ': ' + response.statusText);
target.fill(errorMessage, settings.title, settings.size, args);
target.append(settings.targetContainerSelector, args);
target.show(settings.targetContainerSelector, args);
return;
}
const bodyContent = parseBody(responseText, settings.contentSelector);
if (!bodyContent) {
console.error('ajaxify: The page could not be displayed (no body content found).');
target.fill($('<p>The page could not be displayed.</p>'), settings.title, settings.size, args);
target.append(settings.targetContainerSelector, args);
target.show(settings.targetContainerSelector, args);
return;
}
target.fill(bodyContent, settings.title, settings.size, args);
if (settings.handleFormSubmit) {
// if the content contains a form, we put the response of the form submission into this modal as well
// this allows for forms to be put in modals
function ajaxSubmitHandler(event) {
const form = $(event.currentTarget);
// cancel the form submit and submit the form via ajax
// idea being, that we wanna patch the response in the modal
event.preventDefault();
const url = form.attr('action') || '';
const method = form.attr('method') || 'get';
if (!url) {
console.error('ajaxify: Form submit could not be ajax-ified, because the form action is empty.');
return false;
}
const args = {
url: url,
target: target,
settings: settings
};
$('body').trigger('ajaxify:opening', args);
$.ajax({
url: url,
method: method,
data: form.serialize(),
dataType: 'text/html',
complete: function (data) {
openResponse(data, args);
}
});
}
// if the body content is the form, register the event on it, otherwise search for the form
const directFormChilds = bodyContent.toArray().filter(aContent => aContent.tagName.toLowerCase() === 'form');
if (directFormChilds.length > 0) {
$(directFormChilds).on('submit', ajaxSubmitHandler);
} else {
bodyContent.on('submit', 'form', ajaxSubmitHandler);
}
}
target.append(settings.targetContainerSelector, args);
$('body').trigger('ajaxify:ajax-content-loaded', args);
target.show(settings.targetContainerSelector, args);
}
/**
* Registers an event handler on all links that should be opened inline.
*/
$(document).on('click', '.ajaxify', function (event) {
const size = $(event.currentTarget).data('modal-size'),
title = $(event.currentTarget).attr('title'),
url = $(event.currentTarget).attr('href') || $(event.currentTarget).data('target'),
contentSelector = $(event.currentTarget).data('content-selector'),
handleFormSubmit = !!$(event.currentTarget).data('handle-form-submit'),
targetContainerSelector = $(event.currentTarget).data('target-container-selector');
if (!url) {
console.error('ajaxify: Element cannot be ajaxified, because neither a href nor a data-target are specified.');
return false;
}
const settings = {
title: title,
size: size,
contentSelector: contentSelector,
handleFormSubmit: handleFormSubmit,
targetContainerSelector: targetContainerSelector
};
// whether we use a modal or a panel
const useModal = !targetContainerSelector;
const target = getTarget(useModal);
const args = {
url: url,
target: target,
settings: settings
};
$('body').trigger('ajaxify:opening', args);
$.ajax({
url: url,
complete: function (data) {
openResponse(data, args);
}
});
// disable href link behaviour
return false;
});
}());