Modernisation du handle ajax racine. On utilise l'API html5 de l'objet history, et...
[Plinn.git] / skins / ajax_scripts / root_handlers.js
1 // © Benoît PIN 2006-2013
2 // http://plinn.org
3 // Licence GPL
4 //
5 //
6
7 /* Ajax for everything : if an click event has not been intercepted before */
8
9 var AjaxLinkHandler;
10
11 (function(){
12
13 var reProtocol = /^\s*[a-z]+:/;
14
15 AjaxLinkHandler = function() {
16 var self = this;
17 addListener(document.body, 'click', function(evt){self.handleClick(evt);});
18 addListener(window, 'popstate', function(evt){self.handlePopState(evt);});
19 };
20
21 AjaxLinkHandler.prototype.handleClick = function(evt){
22 var target = getTargetedObject(evt);
23 while (target.nodeName != 'A') {
24 target = target.parentNode;
25 if (target == document.body)
26 return;
27 }
28 target.blur();
29
30 if (target.target)
31 return;
32
33 var url;
34 var m = reProtocol.exec(target.getAttribute('href', 2));
35 if (m) {
36 var protocol = m[0];
37 if (protocol == location.protocol)
38 url = target.href;
39 else
40 return;
41 }
42 else
43 url = absolute_url() + '/' + target.getAttribute('href', 2);
44
45 if (!url) return;
46
47 var query = target.search;
48 if ((query && query.search("noajax=1") != -1) || target.name == 'noajax')
49 return;
50
51 disableDefault(evt);
52 this.loadUrl(url);
53 };
54
55 AjaxLinkHandler.prototype.handlePopState = function (evt, extra) {
56 if (evt.state)
57 this.loadUrl(evt.state, true);
58 };
59
60 AjaxLinkHandler.prototype.loadUrl = function(url, noPush) {
61 var rawUrl = url;
62 var ajaxParams='ajax=1&_browserObjectUrl=' + escape(absolute_url());
63 var urlQueryStart = url.indexOf('?');
64 if (urlQueryStart != -1)
65 url += '&' + ajaxParams;
66 else
67 url += '?' + ajaxParams;
68
69 try {
70 var fi = new FragmentImporter(url);
71 fi.load();
72 }
73 catch (e) {
74 window.location.href = rawUrl;
75 return;
76 }
77 if (!noPush)
78 history.pushState(rawUrl, '', rawUrl)
79 };
80
81 function ajaxSubmitFormHandler(evt) {
82 var target = getTargetedObject(evt);
83 if (target.nodeName == 'INPUT' && (target.type == 'submit' || target.type == 'image')) {
84 var form = target;
85 while (form != document) {
86 form = form.parentNode;
87 if (form.nodeName == 'FORM') {
88 var fm = new FormManager(form, document.getElementById("mainCell"));
89 fm.submitButton = target;
90 break;
91 }
92 }
93 }
94 }
95
96 function _addRootHandlers() {
97 if ((AJAX_CONFIG & 1) == 1 && history.pushState !== undefined) {
98 window.linkHandler = new AjaxLinkHandler(200);
99 }
100 if ((AJAX_CONFIG & 2) == 2) {
101 addListener(document, 'click', ajaxSubmitFormHandler);
102 }
103 }
104
105 registerStartupFunction(_addRootHandlers);
106
107 })();