turbograft 0.0.5 → 0.0.6

Sign up to get free protection for your applications and to get access to all the features.
data/lib/turbograft.js ADDED
@@ -0,0 +1,991 @@
1
+ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2
+ window.Click = (function() {
3
+ Click.installHandlerLast = function(event) {
4
+ if (!event.defaultPrevented) {
5
+ document.removeEventListener('click', Click.handle, false);
6
+ return document.addEventListener('click', Click.handle, false);
7
+ }
8
+ };
9
+
10
+ Click.handle = function(event) {
11
+ return new Click(event);
12
+ };
13
+
14
+ function Click(event) {
15
+ this.event = event;
16
+ if (this.event.defaultPrevented) {
17
+ return;
18
+ }
19
+ this._extractLink();
20
+ if (this._validForTurbolinks()) {
21
+ if (!this._pageChangePrevented()) {
22
+ Turbolinks.visit(this.link.href);
23
+ }
24
+ this.event.preventDefault();
25
+ }
26
+ }
27
+
28
+ Click.prototype._pageChangePrevented = function() {
29
+ return !triggerEvent('page:before-change');
30
+ };
31
+
32
+ Click.prototype._extractLink = function() {
33
+ var link;
34
+ link = this.event.target;
35
+ while (!(!link.parentNode || link.nodeName === 'A')) {
36
+ link = link.parentNode;
37
+ }
38
+ if (link.nodeName === 'A' && link.href.length !== 0) {
39
+ return this.link = new Link(link);
40
+ }
41
+ };
42
+
43
+ Click.prototype._validForTurbolinks = function() {
44
+ return (this.link != null) && !(this.link.shouldIgnore() || this._nonStandardClick());
45
+ };
46
+
47
+ Click.prototype._nonStandardClick = function() {
48
+ return this.event.which > 1 || this.event.metaKey || this.event.ctrlKey || this.event.shiftKey || this.event.altKey;
49
+ };
50
+
51
+ return Click;
52
+
53
+ })();
54
+
55
+
56
+
57
+ },{}],2:[function(require,module,exports){
58
+ window.ComponentUrl = (function() {
59
+ function ComponentUrl(original) {
60
+ this.original = original != null ? original : document.location.href;
61
+ if (this.original.constructor === ComponentUrl) {
62
+ return this.original;
63
+ }
64
+ this._parse();
65
+ }
66
+
67
+ ComponentUrl.prototype.withoutHash = function() {
68
+ return this.href.replace(this.hash, '');
69
+ };
70
+
71
+ ComponentUrl.prototype.withoutHashForIE10compatibility = function() {
72
+ return this.withoutHash();
73
+ };
74
+
75
+ ComponentUrl.prototype.hasNoHash = function() {
76
+ return this.hash.length === 0;
77
+ };
78
+
79
+ ComponentUrl.prototype._parse = function() {
80
+ var _ref;
81
+ (this.link != null ? this.link : this.link = document.createElement('a')).href = this.original;
82
+ _ref = this.link, this.href = _ref.href, this.protocol = _ref.protocol, this.host = _ref.host, this.hostname = _ref.hostname, this.port = _ref.port, this.pathname = _ref.pathname, this.search = _ref.search, this.hash = _ref.hash;
83
+ this.origin = [this.protocol, '//', this.hostname].join('');
84
+ if (this.port.length !== 0) {
85
+ this.origin += ":" + this.port;
86
+ }
87
+ this.relative = [this.pathname, this.search, this.hash].join('');
88
+ return this.absolute = this.href;
89
+ };
90
+
91
+ return ComponentUrl;
92
+
93
+ })();
94
+
95
+
96
+
97
+ },{}],3:[function(require,module,exports){
98
+ window.CSRFToken = (function() {
99
+ function CSRFToken() {}
100
+
101
+ CSRFToken.get = function(doc) {
102
+ var tag;
103
+ if (doc == null) {
104
+ doc = document;
105
+ }
106
+ return {
107
+ node: tag = doc.querySelector('meta[name="csrf-token"]'),
108
+ token: tag != null ? typeof tag.getAttribute === "function" ? tag.getAttribute('content') : void 0 : void 0
109
+ };
110
+ };
111
+
112
+ CSRFToken.update = function(latest) {
113
+ var current;
114
+ current = this.get();
115
+ if ((current.token != null) && (latest != null) && current.token !== latest) {
116
+ return current.node.setAttribute('content', latest);
117
+ }
118
+ };
119
+
120
+ return CSRFToken;
121
+
122
+ })();
123
+
124
+
125
+
126
+ },{}],4:[function(require,module,exports){
127
+ var documentListenerForButtons, hasClass, nodeIsDisabled;
128
+
129
+ window.TurboGraft = {
130
+ handlers: {}
131
+ };
132
+
133
+ hasClass = function(node, search) {
134
+ return node.classList.contains(search);
135
+ };
136
+
137
+ nodeIsDisabled = function(node) {
138
+ return node.getAttribute('disabled') || hasClass(node, 'disabled');
139
+ };
140
+
141
+ TurboGraft.handlers.partialGraftClickHandler = function(ev) {
142
+ var href, keys, partialGraft, refresh, target;
143
+ target = ev.target;
144
+ partialGraft = target.getAttribute("partial-graft");
145
+ if (partialGraft == null) {
146
+ return;
147
+ }
148
+ ev.preventDefault();
149
+ href = target.getAttribute("href");
150
+ refresh = target.getAttribute("refresh");
151
+ if (href == null) {
152
+ throw "TurboGraft developer error: href is not defined on node " + target;
153
+ }
154
+ if (refresh == null) {
155
+ throw "TurboGraft developer error: refresh is not defined on node " + target;
156
+ }
157
+ keys = refresh.trim().split(" ");
158
+ return Page.refresh({
159
+ url: href,
160
+ onlyKeys: keys
161
+ });
162
+ };
163
+
164
+ TurboGraft.handlers.remoteMethodHandler = function(ev) {
165
+ var httpRequestType, httpUrl, onlyOnce, options, remote, target;
166
+ target = ev.target;
167
+ if (!target.getAttribute('remote-method')) {
168
+ return;
169
+ }
170
+ ev.preventDefault();
171
+ httpUrl = target.getAttribute('href');
172
+ httpRequestType = target.getAttribute('remote-method');
173
+ if (!httpRequestType) {
174
+ throw "Turbograft developer error: You did not provide a request type for remote-method";
175
+ }
176
+ if (!httpUrl) {
177
+ throw "Turbograft developer error: You did not provide a URL for remote-method";
178
+ }
179
+ if (onlyOnce = target.getAttribute("remote-once")) {
180
+ target.removeAttribute("remote-once");
181
+ target.removeAttribute("remote-method");
182
+ }
183
+ options = {
184
+ httpRequestType: httpRequestType,
185
+ httpUrl: httpUrl,
186
+ fullRefresh: target.getAttribute('full-refresh') != null,
187
+ refreshOnSuccess: target.getAttribute('refresh-on-success'),
188
+ refreshOnError: target.getAttribute('refresh-on-error')
189
+ };
190
+ if (!options.refreshOnSuccess && !options.refreshOnError) {
191
+ options.fullRefresh = true;
192
+ }
193
+ remote = new TurboGraft.Remote(options, null, target);
194
+ };
195
+
196
+ documentListenerForButtons = function(eventType, handler, useCapture) {
197
+ if (useCapture == null) {
198
+ useCapture = false;
199
+ }
200
+ return document.addEventListener(eventType, function(ev) {
201
+ var target;
202
+ target = ev.target;
203
+ if (!(target.nodeName === "A" || target.nodeName === "BUTTON") || nodeIsDisabled(target)) {
204
+ return;
205
+ }
206
+ return handler(ev);
207
+ });
208
+ };
209
+
210
+ documentListenerForButtons('click', TurboGraft.handlers.partialGraftClickHandler, true);
211
+
212
+ documentListenerForButtons('click', TurboGraft.handlers.remoteMethodHandler, true);
213
+
214
+
215
+
216
+ },{}],5:[function(require,module,exports){
217
+ var __hasProp = {}.hasOwnProperty,
218
+ __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
219
+ __slice = [].slice;
220
+
221
+ window.Link = (function(_super) {
222
+ __extends(Link, _super);
223
+
224
+ Link.HTML_EXTENSIONS = ['html'];
225
+
226
+ Link.allowExtensions = function() {
227
+ var extension, extensions, _i, _len;
228
+ extensions = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
229
+ for (_i = 0, _len = extensions.length; _i < _len; _i++) {
230
+ extension = extensions[_i];
231
+ Link.HTML_EXTENSIONS.push(extension);
232
+ }
233
+ return Link.HTML_EXTENSIONS;
234
+ };
235
+
236
+ function Link(link) {
237
+ this.link = link;
238
+ if (this.link.constructor === Link) {
239
+ return this.link;
240
+ }
241
+ this.original = this.link.href;
242
+ Link.__super__.constructor.apply(this, arguments);
243
+ }
244
+
245
+ Link.prototype.shouldIgnore = function() {
246
+ return this._crossOrigin() || this._anchored() || this._nonHtml() || this._optOut() || this._target();
247
+ };
248
+
249
+ Link.prototype._crossOrigin = function() {
250
+ return this.origin !== (new ComponentUrl).origin;
251
+ };
252
+
253
+ Link.prototype._anchored = function() {
254
+ var current;
255
+ return ((this.hash && this.withoutHash()) === (current = new ComponentUrl).withoutHash()) || (this.href === current.href + '#');
256
+ };
257
+
258
+ Link.prototype._nonHtml = function() {
259
+ return this.pathname.match(/\.[a-z]+$/g) && !this.pathname.match(new RegExp("\\.(?:" + (Link.HTML_EXTENSIONS.join('|')) + ")?$", 'g'));
260
+ };
261
+
262
+ Link.prototype._optOut = function() {
263
+ var ignore, link;
264
+ link = this.link;
265
+ while (!(ignore || link === document || link === null)) {
266
+ ignore = link.getAttribute('data-no-turbolink') != null;
267
+ link = link.parentNode;
268
+ }
269
+ return ignore;
270
+ };
271
+
272
+ Link.prototype._target = function() {
273
+ return this.link.target.length !== 0;
274
+ };
275
+
276
+ return Link;
277
+
278
+ })(ComponentUrl);
279
+
280
+
281
+
282
+ },{}],6:[function(require,module,exports){
283
+ if (!window.Page) {
284
+ window.Page = {};
285
+ }
286
+
287
+ Page.visit = function(url, opts) {
288
+ if (opts == null) {
289
+ opts = {};
290
+ }
291
+ if (opts.reload) {
292
+ return window.location = url;
293
+ } else {
294
+ return Turbolinks.visit(url);
295
+ }
296
+ };
297
+
298
+ Page.refresh = function(options, callback) {
299
+ var newUrl, paramString;
300
+ if (options == null) {
301
+ options = {};
302
+ }
303
+ newUrl = options.url ? options.url : options.queryParams ? (paramString = $.param(options.queryParams), paramString ? paramString = "?" + paramString : void 0, location.pathname + paramString) : location.href;
304
+ if (options.response) {
305
+ return Turbolinks.loadPage(null, options.response, true, callback, options.onlyKeys || []);
306
+ } else {
307
+ return Turbolinks.visit(newUrl, true, options.onlyKeys || [], function() {
308
+ return typeof callback === "function" ? callback() : void 0;
309
+ });
310
+ }
311
+ };
312
+
313
+ Page.open = function() {
314
+ return window.open.apply(window, arguments);
315
+ };
316
+
317
+
318
+
319
+ },{}],7:[function(require,module,exports){
320
+ window.PageCache = (function() {
321
+ var simultaneousAdditionOffset, storage;
322
+
323
+ storage = {};
324
+
325
+ simultaneousAdditionOffset = 0;
326
+
327
+ function PageCache(cacheSize) {
328
+ this.cacheSize = cacheSize != null ? cacheSize : 10;
329
+ storage = {};
330
+ return this;
331
+ }
332
+
333
+ PageCache.prototype.get = function(key) {
334
+ return storage[key];
335
+ };
336
+
337
+ PageCache.prototype.set = function(key, value) {
338
+ if (typeof value !== "object") {
339
+ throw "Developer error: You must store objects in this cache";
340
+ }
341
+ value['cachedAt'] = new Date().getTime() + (simultaneousAdditionOffset += 1);
342
+ storage[key] = value;
343
+ return this.constrain();
344
+ };
345
+
346
+ PageCache.prototype.clear = function() {
347
+ return storage = {};
348
+ };
349
+
350
+ PageCache.prototype.setCacheSize = function(newSize) {
351
+ if (/^[\d]+$/.test(newSize)) {
352
+ this.cacheSize = parseInt(newSize, 10);
353
+ return this.constrain();
354
+ } else {
355
+ throw "Developer error: Invalid parameter '" + newSize + "' for PageCache; must be integer";
356
+ }
357
+ };
358
+
359
+ PageCache.prototype.constrain = function() {
360
+ var cacheTimesRecentFirst, key, pageCacheKeys, _i, _len, _results;
361
+ pageCacheKeys = Object.keys(storage);
362
+ cacheTimesRecentFirst = pageCacheKeys.map((function(_this) {
363
+ return function(url) {
364
+ return storage[url].cachedAt;
365
+ };
366
+ })(this)).sort(function(a, b) {
367
+ return b - a;
368
+ });
369
+ _results = [];
370
+ for (_i = 0, _len = pageCacheKeys.length; _i < _len; _i++) {
371
+ key = pageCacheKeys[_i];
372
+ if (!(storage[key].cachedAt <= cacheTimesRecentFirst[this.cacheSize])) {
373
+ continue;
374
+ }
375
+ triggerEvent('page:expire', storage[key]);
376
+ _results.push(delete storage[key]);
377
+ }
378
+ return _results;
379
+ };
380
+
381
+ PageCache.prototype.length = function() {
382
+ return Object.keys(storage).length;
383
+ };
384
+
385
+ return PageCache;
386
+
387
+ })();
388
+
389
+
390
+
391
+ },{}],8:[function(require,module,exports){
392
+ TurboGraft.Remote = (function() {
393
+ function Remote(opts, form, target) {
394
+ var actualRequestType, formData, xhr;
395
+ this.opts = opts;
396
+ formData = form ? new FormData(form) : new FormData();
397
+ this.initiator = target;
398
+ actualRequestType = this.opts.httpRequestType.toLowerCase() === 'get' ? 'GET' : 'POST';
399
+ formData.append("_method", this.opts.httpRequestType);
400
+ if (this.opts.refreshOnSuccess) {
401
+ this.refreshOnSuccess = this.opts.refreshOnSuccess.split(" ");
402
+ }
403
+ if (this.opts.refreshOnError) {
404
+ this.refreshOnError = this.opts.refreshOnError.split(" ");
405
+ }
406
+ xhr = new XMLHttpRequest;
407
+ xhr.open(actualRequestType, this.opts.httpUrl, true);
408
+ xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml');
409
+ xhr.addEventListener('loadstart', (function(_this) {
410
+ return function() {
411
+ return triggerEvent('turbograft:remote:start', {
412
+ xhr: xhr,
413
+ initiator: _this.initiator
414
+ });
415
+ };
416
+ })(this));
417
+ xhr.addEventListener('error', this.onError);
418
+ xhr.addEventListener('load', (function(_this) {
419
+ return function(event) {
420
+ if (xhr.status < 400) {
421
+ return _this.onSuccess(event);
422
+ } else {
423
+ return _this.onError(event);
424
+ }
425
+ };
426
+ })(this));
427
+ xhr.addEventListener('loadend', (function(_this) {
428
+ return function() {
429
+ return triggerEvent('turbograft:remote:always', {
430
+ xhr: xhr,
431
+ initiator: _this.initiator
432
+ });
433
+ };
434
+ })(this));
435
+ xhr.send(formData);
436
+ return xhr;
437
+ }
438
+
439
+ Remote.prototype.onSuccess = function(ev) {
440
+ var redirect, xhr;
441
+ xhr = ev.target;
442
+ triggerEvent('turbograft:remote:success', {
443
+ xhr: xhr,
444
+ initiator: this.initiator
445
+ });
446
+ if (redirect = xhr.getResponseHeader('X-Next-Redirect')) {
447
+ Page.visit(redirect, {
448
+ reload: true
449
+ });
450
+ return;
451
+ }
452
+ if (this.opts.fullRefresh && this.refreshOnSuccess) {
453
+ return Page.refresh({
454
+ onlyKeys: this.refreshOnSuccess
455
+ });
456
+ } else if (this.opts.fullRefresh) {
457
+ return Page.refresh();
458
+ } else if (this.refreshOnSuccess) {
459
+ return Page.refresh({
460
+ response: xhr,
461
+ onlyKeys: this.refreshOnSuccess
462
+ });
463
+ }
464
+ };
465
+
466
+ Remote.prototype.onError = function(ev) {
467
+ var xhr;
468
+ xhr = ev.target;
469
+ triggerEvent('turbograft:remote:fail', {
470
+ xhr: xhr,
471
+ initiator: this.initiator
472
+ });
473
+ if (this.refreshOnError) {
474
+ return Page.refresh({
475
+ response: xhr,
476
+ onlyKeys: this.refreshOnError
477
+ });
478
+ } else {
479
+ return triggerEvent('turbograft:remote:fail:unhandled', {
480
+ xhr: xhr,
481
+ initiator: this.initiator
482
+ });
483
+ }
484
+ };
485
+
486
+ return Remote;
487
+
488
+ })();
489
+
490
+
491
+
492
+ },{}],9:[function(require,module,exports){
493
+ var browserIsntBuggy, browserSupportsCustomEvents, browserSupportsPushState, browserSupportsTurbolinks, historyStateIsDefined, installDocumentReadyPageEventTriggers, installJqueryAjaxSuccessPageUpdateTrigger, popCookie, requestMethodIsSafe, xhr, _ref,
494
+ __slice = [].slice,
495
+ __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
496
+
497
+ xhr = null;
498
+
499
+ installDocumentReadyPageEventTriggers = function() {
500
+ return document.addEventListener('DOMContentLoaded', (function() {
501
+ triggerEvent('page:change');
502
+ return triggerEvent('page:update');
503
+ }), true);
504
+ };
505
+
506
+ installJqueryAjaxSuccessPageUpdateTrigger = function() {
507
+ if (typeof jQuery !== 'undefined') {
508
+ return jQuery(document).on('ajaxSuccess', function(event, xhr, settings) {
509
+ if (!jQuery.trim(xhr.responseText)) {
510
+ return;
511
+ }
512
+ return triggerEvent('page:update');
513
+ });
514
+ }
515
+ };
516
+
517
+ historyStateIsDefined = window.history.state !== void 0 || navigator.userAgent.match(/Firefox\/2[6|7]/);
518
+
519
+ browserSupportsPushState = window.history && window.history.pushState && window.history.replaceState && historyStateIsDefined;
520
+
521
+ browserIsntBuggy = !navigator.userAgent.match(/CriOS\//);
522
+
523
+ window.triggerEvent = function(name, data) {
524
+ var event;
525
+ event = document.createEvent('Events');
526
+ if (data) {
527
+ event.data = data;
528
+ }
529
+ event.initEvent(name, true, true);
530
+ return document.dispatchEvent(event);
531
+ };
532
+
533
+ popCookie = function(name) {
534
+ var value, _ref;
535
+ value = ((_ref = document.cookie.match(new RegExp(name + "=(\\w+)"))) != null ? _ref[1].toUpperCase() : void 0) || '';
536
+ document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
537
+ return value;
538
+ };
539
+
540
+ requestMethodIsSafe = (_ref = popCookie('request_method')) === 'GET' || _ref === '';
541
+
542
+ browserSupportsTurbolinks = browserSupportsPushState && browserIsntBuggy && requestMethodIsSafe;
543
+
544
+ browserSupportsCustomEvents = document.addEventListener && document.createEvent;
545
+
546
+ if (browserSupportsCustomEvents) {
547
+ installDocumentReadyPageEventTriggers();
548
+ installJqueryAjaxSuccessPageUpdateTrigger();
549
+ }
550
+
551
+ window.Turbolinks = (function() {
552
+ var browserCompatibleDocumentParser, bypassOnLoadPopstate, changePage, createDocument, currentState, deleteRefreshNeverNodes, executeScriptTag, executeScriptTags, extractTitleAndBody, fetch, fetchHistory, fetchReplacement, installHistoryChangeHandler, loadedAssets, pageCache, pageChangePrevented, processResponse, recallScrollPosition, referer, reflectNewUrl, reflectRedirectedUrl, refreshNodesWithKeys, rememberReferer, removeNoscriptTags, resetScrollPosition, transitionCacheFor, usePageCache;
553
+
554
+ function Turbolinks() {}
555
+
556
+ createDocument = null;
557
+
558
+ currentState = null;
559
+
560
+ loadedAssets = null;
561
+
562
+ referer = null;
563
+
564
+ usePageCache = false;
565
+
566
+ Turbolinks.pageCache = pageCache = new PageCache();
567
+
568
+ fetch = function(url, partialReplace, replaceContents, callback) {
569
+ var cachedPage;
570
+ if (partialReplace == null) {
571
+ partialReplace = false;
572
+ }
573
+ if (replaceContents == null) {
574
+ replaceContents = [];
575
+ }
576
+ url = new ComponentUrl(url);
577
+ rememberReferer();
578
+ if (usePageCache) {
579
+ Turbolinks.cacheCurrentPage();
580
+ }
581
+ if (usePageCache && (cachedPage = transitionCacheFor(url.absolute))) {
582
+ fetchHistory(cachedPage);
583
+ return fetchReplacement(url, partialReplace, null, replaceContents);
584
+ } else {
585
+ return fetchReplacement(url, partialReplace, function() {
586
+ if (!replaceContents.length) {
587
+ resetScrollPosition();
588
+ }
589
+ return typeof callback === "function" ? callback() : void 0;
590
+ }, replaceContents);
591
+ }
592
+ };
593
+
594
+ Turbolinks.pageCacheEnabled = function() {
595
+ return usePageCache;
596
+ };
597
+
598
+ Turbolinks.usePageCache = function(status) {
599
+ return usePageCache = status;
600
+ };
601
+
602
+ transitionCacheFor = function(url) {
603
+ var cachedPage;
604
+ cachedPage = pageCache.get(url);
605
+ if (cachedPage && !cachedPage.transitionCacheDisabled) {
606
+ return cachedPage;
607
+ }
608
+ };
609
+
610
+ Turbolinks.pushState = function(state, title, url) {
611
+ return window.history.pushState(state, title, url);
612
+ };
613
+
614
+ Turbolinks.replaceState = function(state, title, url) {
615
+ return window.history.replaceState(state, title, url);
616
+ };
617
+
618
+ fetchReplacement = function(url, partialReplace, onLoadFunction, replaceContents) {
619
+ triggerEvent('page:fetch', {
620
+ url: url.absolute
621
+ });
622
+ if (xhr != null) {
623
+ xhr.abort();
624
+ }
625
+ xhr = new XMLHttpRequest;
626
+ xhr.open('GET', url.withoutHashForIE10compatibility(), true);
627
+ xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml');
628
+ xhr.setRequestHeader('X-XHR-Referer', referer);
629
+ xhr.onload = function() {
630
+ if (xhr.status >= 500) {
631
+ return document.location.href = url.absolute;
632
+ } else {
633
+ return Turbolinks.loadPage(url, xhr, partialReplace, onLoadFunction, replaceContents);
634
+ }
635
+ };
636
+ xhr.onloadend = function() {
637
+ return xhr = null;
638
+ };
639
+ xhr.onerror = function() {
640
+ return document.location.href = url.absolute;
641
+ };
642
+ xhr.send();
643
+ };
644
+
645
+ Turbolinks.loadPage = function(url, xhr, partialReplace, onLoadFunction, replaceContents) {
646
+ var doc, nodes;
647
+ if (partialReplace == null) {
648
+ partialReplace = false;
649
+ }
650
+ if (onLoadFunction == null) {
651
+ onLoadFunction = (function() {});
652
+ }
653
+ if (replaceContents == null) {
654
+ replaceContents = [];
655
+ }
656
+ triggerEvent('page:receive');
657
+ if (doc = processResponse(xhr, partialReplace)) {
658
+ reflectNewUrl(url);
659
+ nodes = changePage.apply(null, __slice.call(extractTitleAndBody(doc)).concat([partialReplace], [replaceContents]));
660
+ reflectRedirectedUrl(xhr);
661
+ triggerEvent('page:load', nodes);
662
+ if (typeof onLoadFunction === "function") {
663
+ onLoadFunction();
664
+ }
665
+ } else {
666
+ document.location.href = url.absolute;
667
+ }
668
+ };
669
+
670
+ fetchHistory = function(cachedPage) {
671
+ if (xhr != null) {
672
+ xhr.abort();
673
+ }
674
+ changePage(cachedPage.title, cachedPage.body, false);
675
+ recallScrollPosition(cachedPage);
676
+ return triggerEvent('page:restore');
677
+ };
678
+
679
+ Turbolinks.cacheCurrentPage = function() {
680
+ var currentStateUrl;
681
+ currentStateUrl = new ComponentUrl(currentState.url);
682
+ pageCache.set(currentStateUrl.absolute, {
683
+ url: currentStateUrl.relative,
684
+ body: document.body,
685
+ title: document.title,
686
+ positionY: window.pageYOffset,
687
+ positionX: window.pageXOffset,
688
+ transitionCacheDisabled: document.querySelector('[data-no-transition-cache]') != null
689
+ });
690
+ };
691
+
692
+ changePage = function(title, body, csrfToken, runScripts, partialReplace, replaceContents) {
693
+ if (replaceContents == null) {
694
+ replaceContents = [];
695
+ }
696
+ if (title) {
697
+ document.title = title;
698
+ }
699
+ if (replaceContents.length) {
700
+ return refreshNodesWithKeys(replaceContents, body);
701
+ } else {
702
+ deleteRefreshNeverNodes(body);
703
+ triggerEvent('page:before-replace');
704
+ document.documentElement.replaceChild(body, document.body);
705
+ if (csrfToken != null) {
706
+ CSRFToken.update(csrfToken);
707
+ }
708
+ if (runScripts) {
709
+ executeScriptTags();
710
+ }
711
+ currentState = window.history.state;
712
+ triggerEvent('page:change');
713
+ triggerEvent('page:update');
714
+ }
715
+ };
716
+
717
+ deleteRefreshNeverNodes = function(body) {
718
+ var node, _i, _len, _ref1;
719
+ _ref1 = body.querySelectorAll('[refresh-never]');
720
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
721
+ node = _ref1[_i];
722
+ node.parentNode.removeChild(node);
723
+ }
724
+ };
725
+
726
+ refreshNodesWithKeys = function(keys, body) {
727
+ var allNodesToBeRefreshed, existingNode, key, newNode, node, nodeId, parentIsRefreshing, refreshedNodes, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref1, _ref2;
728
+ allNodesToBeRefreshed = [];
729
+ _ref1 = document.querySelectorAll("[refresh-always]");
730
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
731
+ node = _ref1[_i];
732
+ allNodesToBeRefreshed.push(node);
733
+ }
734
+ for (_j = 0, _len1 = keys.length; _j < _len1; _j++) {
735
+ key = keys[_j];
736
+ _ref2 = document.querySelectorAll("[refresh=" + key + "]");
737
+ for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
738
+ node = _ref2[_k];
739
+ allNodesToBeRefreshed.push(node);
740
+ }
741
+ }
742
+ triggerEvent('page:before-partial-replace', allNodesToBeRefreshed);
743
+ parentIsRefreshing = function(node) {
744
+ var potentialParent, _l, _len3;
745
+ for (_l = 0, _len3 = allNodesToBeRefreshed.length; _l < _len3; _l++) {
746
+ potentialParent = allNodesToBeRefreshed[_l];
747
+ if (node !== potentialParent) {
748
+ if (potentialParent.contains(node)) {
749
+ return true;
750
+ }
751
+ }
752
+ }
753
+ return false;
754
+ };
755
+ refreshedNodes = [];
756
+ for (_l = 0, _len3 = allNodesToBeRefreshed.length; _l < _len3; _l++) {
757
+ existingNode = allNodesToBeRefreshed[_l];
758
+ if (parentIsRefreshing(existingNode)) {
759
+ continue;
760
+ }
761
+ if (!(nodeId = existingNode.getAttribute('id'))) {
762
+ throw new Error("Turbolinks refresh: Refresh key elements must have an id.");
763
+ }
764
+ if (newNode = body.querySelector("#" + nodeId)) {
765
+ existingNode.parentNode.replaceChild(newNode, existingNode);
766
+ if (newNode.nodeName === 'SCRIPT' && newNode.getAttribute("data-turbolinks-eval") !== "false") {
767
+ executeScriptTag(newNode);
768
+ } else {
769
+ refreshedNodes.push(newNode);
770
+ }
771
+ } else if (existingNode.getAttribute("refresh-always") === null) {
772
+ existingNode.parentNode.removeChild(existingNode);
773
+ }
774
+ }
775
+ return refreshedNodes;
776
+ };
777
+
778
+ executeScriptTags = function() {
779
+ var script, scripts, _i, _len, _ref1;
780
+ scripts = Array.prototype.slice.call(document.body.querySelectorAll('script:not([data-turbolinks-eval="false"])'));
781
+ for (_i = 0, _len = scripts.length; _i < _len; _i++) {
782
+ script = scripts[_i];
783
+ if ((_ref1 = script.type) === '' || _ref1 === 'text/javascript') {
784
+ executeScriptTag(script);
785
+ }
786
+ }
787
+ };
788
+
789
+ executeScriptTag = function(script) {
790
+ var attr, copy, nextSibling, parentNode, _i, _len, _ref1;
791
+ copy = document.createElement('script');
792
+ _ref1 = script.attributes;
793
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
794
+ attr = _ref1[_i];
795
+ copy.setAttribute(attr.name, attr.value);
796
+ }
797
+ copy.appendChild(document.createTextNode(script.innerHTML));
798
+ parentNode = script.parentNode, nextSibling = script.nextSibling;
799
+ parentNode.removeChild(script);
800
+ parentNode.insertBefore(copy, nextSibling);
801
+ };
802
+
803
+ removeNoscriptTags = function(node) {
804
+ node.innerHTML = node.innerHTML.replace(/<noscript[\S\s]*?<\/noscript>/ig, '');
805
+ return node;
806
+ };
807
+
808
+ reflectNewUrl = function(url) {
809
+ if ((url = new ComponentUrl(url)).absolute !== referer) {
810
+ Turbolinks.pushState({
811
+ turbolinks: true,
812
+ url: url.absolute
813
+ }, '', url.absolute);
814
+ }
815
+ };
816
+
817
+ reflectRedirectedUrl = function(xhr) {
818
+ var location, preservedHash;
819
+ if (location = xhr.getResponseHeader('X-XHR-Redirected-To')) {
820
+ location = new ComponentUrl(location);
821
+ preservedHash = location.hasNoHash() ? document.location.hash : '';
822
+ Turbolinks.replaceState(currentState, '', location.href + preservedHash);
823
+ }
824
+ };
825
+
826
+ rememberReferer = function() {
827
+ return referer = document.location.href;
828
+ };
829
+
830
+ Turbolinks.rememberCurrentUrl = function() {
831
+ return Turbolinks.replaceState({
832
+ turbolinks: true,
833
+ url: document.location.href
834
+ }, '', document.location.href);
835
+ };
836
+
837
+ Turbolinks.rememberCurrentState = function() {
838
+ return currentState = window.history.state;
839
+ };
840
+
841
+ recallScrollPosition = function(page) {
842
+ return window.scrollTo(page.positionX, page.positionY);
843
+ };
844
+
845
+ resetScrollPosition = function() {
846
+ if (document.location.hash) {
847
+ return document.location.href = document.location.href;
848
+ } else {
849
+ return window.scrollTo(0, 0);
850
+ }
851
+ };
852
+
853
+ pageChangePrevented = function() {
854
+ return !triggerEvent('page:before-change');
855
+ };
856
+
857
+ processResponse = function(xhr, partial) {
858
+ var assetsChanged, changed, clientOrServerError, doc, extractTrackAssets, intersection, validContent;
859
+ if (partial == null) {
860
+ partial = false;
861
+ }
862
+ clientOrServerError = function() {
863
+ var _ref1;
864
+ if (xhr.status === 422) {
865
+ return false;
866
+ }
867
+ return (400 <= (_ref1 = xhr.status) && _ref1 < 600);
868
+ };
869
+ validContent = function() {
870
+ return xhr.getResponseHeader('Content-Type').match(/^(?:text\/html|application\/xhtml\+xml|application\/xml)(?:;|$)/);
871
+ };
872
+ extractTrackAssets = function(doc) {
873
+ var node, _i, _len, _ref1, _results;
874
+ _ref1 = doc.head.childNodes;
875
+ _results = [];
876
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
877
+ node = _ref1[_i];
878
+ if ((typeof node.getAttribute === "function" ? node.getAttribute('data-turbolinks-track') : void 0) != null) {
879
+ _results.push(node.getAttribute('src') || node.getAttribute('href'));
880
+ }
881
+ }
882
+ return _results;
883
+ };
884
+ assetsChanged = function(doc) {
885
+ var fetchedAssets;
886
+ loadedAssets || (loadedAssets = extractTrackAssets(document));
887
+ fetchedAssets = extractTrackAssets(doc);
888
+ return fetchedAssets.length !== loadedAssets.length || intersection(fetchedAssets, loadedAssets).length !== loadedAssets.length;
889
+ };
890
+ intersection = function(a, b) {
891
+ var value, _i, _len, _ref1, _results;
892
+ if (a.length > b.length) {
893
+ _ref1 = [b, a], a = _ref1[0], b = _ref1[1];
894
+ }
895
+ _results = [];
896
+ for (_i = 0, _len = a.length; _i < _len; _i++) {
897
+ value = a[_i];
898
+ if (__indexOf.call(b, value) >= 0) {
899
+ _results.push(value);
900
+ }
901
+ }
902
+ return _results;
903
+ };
904
+ if (!clientOrServerError() && validContent()) {
905
+ doc = createDocument(xhr.responseText);
906
+ changed = assetsChanged(doc);
907
+ if (doc && (!changed || partial)) {
908
+ return doc;
909
+ }
910
+ }
911
+ };
912
+
913
+ extractTitleAndBody = function(doc) {
914
+ var title;
915
+ title = doc.querySelector('title');
916
+ return [title != null ? title.textContent : void 0, removeNoscriptTags(doc.body), CSRFToken.get(doc).token, 'runScripts'];
917
+ };
918
+
919
+ installHistoryChangeHandler = function(event) {
920
+ var cachedPage, _ref1;
921
+ if ((_ref1 = event.state) != null ? _ref1.turbolinks : void 0) {
922
+ if (cachedPage = pageCache.get((new ComponentUrl(event.state.url)).absolute)) {
923
+ Turbolinks.cacheCurrentPage();
924
+ return fetchHistory(cachedPage);
925
+ } else {
926
+ return Turbolinks.visit(event.target.location.href);
927
+ }
928
+ }
929
+ };
930
+
931
+ bypassOnLoadPopstate = function(fn) {
932
+ return setTimeout(fn, 500);
933
+ };
934
+
935
+ browserCompatibleDocumentParser = function() {
936
+ var createDocumentUsingDOM, createDocumentUsingParser, createDocumentUsingWrite, e, testDoc, _ref1;
937
+ createDocumentUsingParser = function(html) {
938
+ return (new DOMParser).parseFromString(html, 'text/html');
939
+ };
940
+ createDocumentUsingDOM = function(html) {
941
+ var doc;
942
+ doc = document.implementation.createHTMLDocument('');
943
+ doc.documentElement.innerHTML = html;
944
+ return doc;
945
+ };
946
+ createDocumentUsingWrite = function(html) {
947
+ var doc;
948
+ doc = document.implementation.createHTMLDocument('');
949
+ doc.open('replace');
950
+ doc.write(html);
951
+ doc.close();
952
+ return doc;
953
+ };
954
+ try {
955
+ if (window.DOMParser) {
956
+ testDoc = createDocumentUsingParser('<html><body><p>test');
957
+ return createDocumentUsingParser;
958
+ }
959
+ } catch (_error) {
960
+ e = _error;
961
+ testDoc = createDocumentUsingDOM('<html><body><p>test');
962
+ return createDocumentUsingDOM;
963
+ } finally {
964
+ if ((testDoc != null ? (_ref1 = testDoc.body) != null ? _ref1.childNodes.length : void 0 : void 0) !== 1) {
965
+ return createDocumentUsingWrite;
966
+ }
967
+ }
968
+ };
969
+
970
+ if (browserSupportsTurbolinks) {
971
+ Turbolinks.visit = fetch;
972
+ Turbolinks.rememberCurrentUrl();
973
+ Turbolinks.rememberCurrentState();
974
+ createDocument = browserCompatibleDocumentParser();
975
+ document.addEventListener('click', Click.installHandlerLast, true);
976
+ bypassOnLoadPopstate(function() {
977
+ return window.addEventListener('popstate', installHistoryChangeHandler, false);
978
+ });
979
+ } else {
980
+ Turbolinks.visit = function(url) {
981
+ return document.location.href = url;
982
+ };
983
+ }
984
+
985
+ return Turbolinks;
986
+
987
+ })();
988
+
989
+
990
+
991
+ },{}]},{},[1,2,3,5,6,7,9,4,8]);