/
limberjax.js
600 lines (518 loc) · 18.3 KB
/
limberjax.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
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
/*!
* limberjax
* https://github.com/0b10011/limberjax/
*
* Copyright 2017 Brandon Frohs
* Released under the MIT license
* https://github.com/0b10011/limberjax/LICENSE
*/
/* global FormData, jQuery, URL, console */
(function ($) {
'use strict'
let disabled = false
let mainContainerSelector
let mainContainer
let version
const Limberjax = function (containerSelector) {
// While limberjax shouldn't interfere with other code too much,
// it does rely on classes on the dom that are global
// and could cause weird things to happen
// if multiple instances were running alongside eachother.
if (!(this instanceof Limberjax)) {
throw new Error('Attemping to call `Limberjax()` directly. Use `new Limberjax()` instead.')
} else if (window.Limberjax) {
throw new Error('Attempting to create a second instance of `Limberjax()`. Call `Limberjax.watchAll()` instead.')
}
window.Limberjax = this
if (containerSelector instanceof String) {
throw new Error('containerSelector must be a string selector')
}
mainContainerSelector = containerSelector
mainContainer = $(containerSelector)
if (mainContainer.length !== 1) {
throw new Error('containerSelector must match a single element')
}
$.fn.Limberjax = this.watch
version = $("meta[http-equiv='x-limberjax']").attr('content')
this.watchAll()
$(document).on('limberjax:success', function () {
window.Limberjax.watchAll()
})
$(window).on('popstate.limberjax', popstate)
window.history.scrollRestoration = 'manual'
window.history.replaceState(buildState({
'parents': [],
'mode': 'replace',
'containerSelector': 'body',
'contents': $('<div/>').append($('body').contents().clone()),
'scripts': undefined,
'scrollLeft': $(window).scrollLeft(),
'scrollTop': $(window).scrollTop(),
'styles': undefined,
'title': $('title').first(),
'url': window.location.href
}), '', window.location.href)
}
const Request = function (options) {
if (!(this instanceof Request)) {
throw new Error('Attemping to call `Request()` directly. Use `new Request()` instead.')
} else if (disabled) {
throw new Error('Limberjax is disabled due to an error')
}
function parse (html, xhr, providedData) {
let data = {
'parents': [],
'mode': providedData.mode,
'base': undefined,
'containerSelector': providedData.containerSelector,
'contents': undefined,
'links': undefined,
'meta': undefined,
'scripts': undefined,
'scrollLeft': 0,
'scrollTop': 0,
'styles': undefined,
'title': undefined,
'url': providedData.url
}
providedData = undefined // Avoid accidentally using this instead of `data`
// If this request does something
// other than replace on the main container,
// add the current state as a parent state.
if (mainContainerSelector !== data.containerSelector || data.mode !== 'replace') {
const currentState = window.history.state
$.each(currentState.parents, function () {
data.parents.push(parseState(this))
})
currentState.parents = []
data.parents.push(parseState(currentState))
}
// jQuery's
if (/<html/i.test(html)) {
data.contents = findAll(fromHtml(html.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]), data.containerSelector)
let head = fromHtml(html.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0])
// Get allowed <head> elements
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head
data.title = head.filter('title').first()
data.base = head.filter('base').first()
data.links = head.filter('link[rel="stylesheet"][type]:not([type="text/css"])')
data.meta = head.filter('meta:not([charset])')
data.scripts = head.filter('script[src]')
data.styles = head.filter('link[rel="stylesheet"]:not([type]), link[rel="stylesheet"][type="text/css"]')
// Warn about
head.filter('script:not([src])').each(function () {
console.warn(
'Inline script found in <head>. Must add to limberjax.mainContainer\'s element for it to be executed.',
this.textContent.split('\n')
)
})
head.filter('style').each(function () {
console.warn(
'Inline stylesheet found in <head>. Must add to limberjax.mainContainer\'s element for it to be used.',
this.textContent.split('\n')
)
})
} else {
html = fromHtml(html)
data.contents = findAll(fromHtml(html), data.containerSelector)
data.title = findAll(html, 'title').last().text()
}
return data
}
function xhrBeforeSend (xhr, settings) {
const event = trigger(options.target, 'beforeSend', [xhr, settings])
if (event.isDefaultPrevented()) {
// Cancel the request
return false
}
}
function xhrError (xhr, status, error) {
trigger(options.target, 'error', [xhr, status, error])
}
function xhrOutdated (xhr, status, error) {
trigger(options.target, 'outdated', [xhr, status, error])
}
function xhrSuccess (html, status, xhr) {
let currentState = window.history.state
if (currentState.limberjax) {
currentState = parseState(currentState)
currentState.scrollLeft = $(window).scrollLeft()
currentState.scrollTop = $(window).scrollTop()
window.history.replaceState(buildState(currentState), '', currentState.url.toString())
}
const redirect = xhr.getResponseHeader('X-Limberjax-Cross-Domain-Redirect')
if (redirect) {
window.location = redirect
}
const contentType = xhr.getResponseHeader('Content-Type')
if (contentType.indexOf('text/html') !== 0) {
throw new Error('Invalid content type `' + contentType + '`')
}
const contentDisposition = xhr.getResponseHeader('Content-Disposition')
if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
throw new Error('Attachment loaded inline')
}
trigger(options.target, 'beforeParse', [html, xhr, options])
const state = parse(html, xhr, options)
loadState(state)
window.history.pushState(buildState(state), '', state.url)
trigger($(state.containerSelector), 'success', [state, status, xhr])
}
function xhrComplete (xhr, status) {
trigger($('body'), 'complete', [xhr, status])
}
const defaultOptions = {
// Method for HTTP request (see https://api.jquery.com/jQuery.ajax/).
// - "GET"
// - "POST"
'method': undefined,
// URL to be requested.
// Can be partial or fully formed.
'url': undefined,
// How the fetched content will be inserted into the document.
// - "replace": Replaces the contents of the container
// - "append": Appended to the end of the container
'mode': 'replace',
// Target for fetched content to be inserted in relation to.
// See `option.mode` for more information.
'containerSelector': mainContainerSelector,
'container': mainContainer,
// Target that user interacted with.
// Used for events, managing classes, etc during the request.
// - jQuery object
target: undefined,
// Form data (GET or POST)
// See https://developer.mozilla.org/en-US/docs/Web/API/FormData
// - FormData
data: undefined
}
const defaultXhrSettings = {
'accepts': 'text/html',
'async': true,
'cache': true,
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
'crossDomain': false,
'data': undefined, // `options.data`
'dataType': 'html',
'global': true,
'headers': {
'X-Requested-With': 'limberjax'
},
'ifModified': false,
'isLocal': false,
'method': undefined, // `options.method`
'processData': true,
'timeout': 0, // No timeout, we'll handle internally
'traditional': false,
'url': undefined, // `options.url`
// Callbacks
'beforeSend': xhrBeforeSend,
'error': xhrError,
'statusCode': {
412: xhrOutdated
},
'success': xhrSuccess,
'complete': xhrComplete
}
// Clone options (and inject default values)
options = $.extend(defaultOptions, options)
// Verify provided option values
if (options.method === undefined) {
throw new Error('No method provided')
}
if (options.url === undefined) {
throw new Error('No url provided')
}
switch (options.mode) {
case 'append':
case 'replace':
break
default:
throw new Error('Invalid mode `' + options.mode + '`')
}
if (options.target === undefined) {
throw new Error('No target provided')
}
if (options.data !== undefined && (
options.method === 'POST'
? !(options.data instanceof FormData)
: !(options.data instanceof Array)
)) {
throw new Error('Data must be undefined or an instance of FormData for POST requests and Array for GET requests')
}
// Add limberjax version to url.
// This forces the browser to cache it separately from other responses
// and allows the server to return HTTP 412
// if there's a version mismatch.
options.url = new URL(options.url, window.location.href)
options.limberjax_url = new URL(options.url, window.location.href)
options.limberjax_url.searchParams.set('limberjax', version)
return $.ajax($.extend(defaultXhrSettings, {
'data': options.data,
'method': options.method,
'url': options.limberjax_url,
// Required with data
'processData': options.method !== 'POST',
'contentType': options.method === 'POST' ? false : undefined
})).fail(function (xhr, status, err) {
// Mark limberjax as disabled (will throw new Error(if any methods are called))
disabled = true
// Remove all limberjax listeners
// https://stackoverflow.com/questions/3569393/how-to-unbind-all-event-using-jquery#comment21077312_12053827
$(document).add('*').off('.limberjax')
// Log error
console.error('limberjax request failed')
console.error(err)
})
}
function trigger (target, eventType, extraParameters) {
const event = $.Event('limberjax:' + eventType)
target.trigger(event, extraParameters)
return event
}
// Find all `els` (top level and children) that match `selector`
function findAll (els, selector) {
return els.filter(selector).add(els.find(selector))
}
function fromHtml (html) {
return $($.parseHTML(html, document, true))
}
function toHtml (jqueryObject) {
if (jqueryObject === undefined || jqueryObject.length === 0) {
return undefined
}
return $('<div/>').append(jqueryObject.clone()).html()
}
function parseState (state) {
// Build parents
const parents = []
$.each(state.parents, function () {
parents.push(parseState(this))
})
return {
'parents': parents,
'mode': state.mode,
'base': fromHtml(state.base),
'containerSelector': state.containerSelector,
'contents': fromHtml(state.contents),
'links': fromHtml(state.links),
'meta': fromHtml(state.meta),
'scripts': fromHtml(state.scripts),
'scrollLeft': state.scrollLeft,
'scrollTop': state.scrollTop,
'styles': fromHtml(state.styles),
'title': fromHtml(state.title),
'url': new URL(state.url)
}
}
function buildState (data) {
// Build parents
const parents = []
$.each(data.parents, function () {
parents.push(buildState(this))
})
return {
'limberjax': true,
'parents': parents,
'mode': data.mode,
'base': toHtml(data.base),
'containerSelector': data.containerSelector,
'contents': toHtml(data.contents),
'links': toHtml(data.links),
'meta': toHtml(data.meta),
'scripts': toHtml(data.scripts),
'scrollLeft': data.scrollLeft,
'scrollTop': data.scrollTop,
'styles': toHtml(data.styles),
'title': toHtml(data.title),
'url': data.url.toString()
}
}
function loadState (state, parentsNeedLoading) {
if (parentsNeedLoading) {
$.each(state.parents, function () {
loadState(this)
})
}
const container = $(state.containerSelector)
trigger(container, 'beforeLoad', {
state: state,
parentsNeedLoading: parentsNeedLoading
})
// Remove head elements from previous page
$('head').find('title, base, link[rel="stylesheet"][type]:not([type="text/css"]), meta:not([charset])').remove()
// Add head elements for new page
$('head').append(
state.title,
state.base,
state.links,
state.meta
)
// Loop through scripts and add new ones
const existingScripts = $('script[src]')
state.scripts.each(function () {
const newScript = $(this)
var matchedScripts = existingScripts.filter(function () {
const existingScript = $(this)
return existingScript.attr('src') === newScript.attr('src') &&
existingScript.attr('type') === newScript.attr('type')
})
if (matchedScripts.length) return
$('head').append(newScript)
})
// Loop through styles and add new ones
const existingStyles = $('link[rel="stylesheet"][type="text/css"], link[rel="stylesheet"]:not([type])')
state.styles.each(function () {
const newStyle = $(this)
var matchedStyles = existingStyles.filter(function () {
const existingStyle = $(this)
return existingStyle.attr('href') === newStyle.attr('href') &&
existingStyle.attr('media') === newStyle.attr('media')
})
if (matchedStyles.length) return
$('head').append(newStyle)
})
switch (state.mode) {
case 'replace':
container.html(toHtml(state.contents.contents()))
break
case 'append':
container.append(state.contents.contents())
break
}
$(window).scrollLeft(state.scrollLeft)
$(window).scrollTop(state.scrollTop)
}
function popstate (event) {
const rawState = event.originalEvent.state
// Not a limberjax state, ignore
if (!rawState || !rawState.limberjax) {
return
}
const state = parseState(rawState)
loadState(state, true)
trigger($(state.containerSelector), 'success', [state])
}
function handleClick (event) {
const link = event.currentTarget
const $link = $(link)
const options = {
'method': 'GET'
}
// Ensure the clicked element is an anchor
if (!$link.is('a')) {
throw new Error('Clicked element must be an achor element')
}
if (
// Ignore clicks that aren't regular clicks
event.which > 1 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey ||
// Ignore cross origin links
window.location.protocol !== link.protocol ||
window.location.hostname !== link.hostname
) {
return
}
// Add class for styling link while it loads
$link.addClass('limberjax-loading')
// Set options
options.mode = $link.data('limberjax-mode') || undefined
options.url = $link.attr('href')
options.target = $link
// Prevent default behavior of click event.
// If an error is thrown,
// we can handle later.
event.preventDefault()
// Make the request!
new Request(options).fail(function (xhr, status, err) {
console.log('Failed link click')
console.log($link)
link.click() // $link.click() did nothing in (at least) Firefox 54.0
})
}
function handleSubmit (event) {
const form = event.currentTarget
const $form = $(form)
const href = form.action || window.location.href
const url = new URL(href)
const options = {
'contentType': form.enctype,
'method': form.method.toUpperCase() || 'GET'
}
// Ensure the submitted element is a form
if (!$form.is('form')) {
throw new Error('Submitted element must be a form element')
}
if (
// Ignore if we can't handle
window.FormData === undefined ||
// Ignore cross origin links
window.location.protocol !== url.protocol ||
window.location.hostname !== url.hostname
) {
return
}
// Can't handle buttons with name/value pair
if ($(form).find('button[name]').length) {
return
}
// Add class for styling link while it loads
$form.addClass('limberjax-loading')
// Set options
options.mode = $form.data('limberjax-mode') || undefined
options.url = url.toString()
options.target = $form
options.data = options.method === 'POST' ? new FormData(form) : $(form).serializeArray()
// Prevent default behavior of click event.
// If an error is thrown,
// we can handle later.
event.preventDefault()
// Make the request!
new Request(options).fail(function (xhr, status, err) {
console.log('Failed form submit')
console.log($form)
form.submit()
})
}
Limberjax.prototype.watchAll = function () {
this.watchLinks()
this.watchForms()
}
Limberjax.prototype.watchLinks = function () {
const limberjack = this
$('a:not(.limberjax-watched):not([download]):not([data-ignore-limberjax]):not([target="_blank"])').each(function () {
limberjack.watchLink(this)
})
}
Limberjax.prototype.watchLink = function (el) {
var $el = $(el)
$el.addClass('limberjax-watched')
$el.on('click.limberjax', handleClick)
}
Limberjax.prototype.watchForms = function () {
const limberjack = this
$('form:not(.limberjax-watched):not([data-ignore-limberjax]):not([target=_blank])').each(function () {
limberjack.watchForm(this)
})
}
Limberjax.prototype.watchForm = function (el) {
var $el = $(el)
$el.addClass('limberjax-watched')
$el.on('submit.limberjax', handleSubmit)
}
Limberjax.prototype.watch = function (el) {
var $el = $(el)
if ($el.is('a')) {
this.watchLink(el)
} else if ($el.is('form')) {
this.watchForm(el)
} else {
throw new Error('Only <a> and <form> elements can be watched. `' + $el.prop('tagName') + '` provided')
}
}
$.Limberjax = Limberjax
}(jQuery))
new jQuery.Limberjax('#layout-main') // eslint-disable-line no-new