summaryrefslogtreecommitdiffstats
path: root/WebContent/VAADIN/vaadinBootstrap.js
blob: 3fff0bd8292f69a657de6abe5389554d129cc6a8 (plain)
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
(function() {
	var apps = {};
	var themesLoaded = {};
	var widgetsets = {};
	
	
    var log;
    if (typeof console === "undefined" || !window.location.search.match(/[&?]debug(&|$)/)) {
    	//If no console.log present, just use a no-op
    	log = function() {};
    } else if (typeof console.log === "function") {
    	//If it's a function, use it with apply
		log = function() {
			console.log.apply(console, arguments);
		};
    } else {
    	//In IE, its a native function for which apply is not defined, but it works without a proper 'this' reference
    	log = console.log;
    }
	
	var loadTheme = function(url) {
		if(!themesLoaded[url]) {
			log("loadTheme", url);
			var stylesheet = document.createElement('link');
			stylesheet.setAttribute('rel', 'stylesheet');
			stylesheet.setAttribute('type', 'text/css');
			stylesheet.setAttribute('href', url + "/styles.css");
			document.getElementsByTagName('head')[0].appendChild(stylesheet);
			themesLoaded[url] = true;
		}		
	};
	
	var isWidgetsetLoaded = function(widgetset) {
		var className = widgetset.replace(/\./g, "_");
		return (typeof window[className]) != "undefined";
	};
	
	var loadWidgetset = function(basePath, widgetset) {
		if (widgetsets[widgetset]) {
			return;
		}
		log("load widgetset", basePath, widgetset);
		setTimeout(function() {
			if (!isWidgetsetLoaded(widgetset)) {
				alert("Failed to load the widgetset: " + url);
			}
		}, 15000);
		
		var url = basePath + widgetset + "/" + widgetset + ".nocache.js?" + new Date().getTime();
		
		var scriptTag = document.createElement('script');
		scriptTag.setAttribute('type', 'text/javascript');
		scriptTag.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(scriptTag);
		
		widgetsets[widgetset] = {
			pendingApps: []
		};
	};
	
	window.vaadin = window.vaadin || {
		initApplication: function(appId, config) {
			if (apps[appId]) {
				throw "Application " + appId + " already initialized";
			}
			log("init application", appId, config);
			
			var testbenchId = appId.replace(/-\d+$/, '');
			window.vaadin.clients[testbenchId] = {
					isActive: function() {
						return true;
					}
			};
			
			var getConfig = function(name) {
				var value = config[name];
				return value;
			};
			
			var fetchRootConfig = function() {
				log('Fetching root config');
				var url = getConfig('browserDetailsUrl');
				if (!url) {
					// No special url defined, use the default URL
					url = getConfig('appUri');
					// Add a slash to the end, because ApplicationConiguration.loadFromDOM does so...
					if (url.length == 0 || url.substr(url.length-1) !== "/") {
						url += '/';
					}
				}
				url += ((/\?/).test(url) ? "&" : "?") + "browserDetails=1";
				var rootId = getConfig("rootId");
				if (rootId !== undefined) {
					url += "&rootId=" + rootId;
				}

				var initialPath = getConfig("initialPath");
				if (initialPath !== undefined) {
					url += '&initialPath=' + encodeURIComponent(initialPath);
				}
				url += '&initialParams=' + encodeURIComponent(JSON.stringify(getConfig("initialParams")));
				
				url += '&' + vaadin.getBrowserDetailsParameters(appId); 
				
				// Timestamp to avoid caching
				url += '&' + (new Date()).getTime();
				
				var r = new XMLHttpRequest();
				r.open('POST', url, true);
				r.onreadystatechange = function (aEvt) {  
					if (r.readyState == 4) {
						if (r.status == 200){
							log("Got root config response", r.responseText);
							var updatedConfig = JSON.parse(r.responseText);
							
							// Copy new properties to the config object
							for (var property in updatedConfig) {
								if (updatedConfig.hasOwnProperty(property)) {
									config[property] = updatedConfig[property];
								}
							}
							
							// Try bootstrapping again, this time without fetching missing info
							bootstrapApp(false);
						} else if (r.status == 500) {
							document.write(r.responseText);
						} else {
							log('Error', r.statusText);  
						}
					}  
				};
				r.send(null);
				
				log('sending request to ', url);
			};			
			
			//Export public data
			var app = {
				'getConfig': getConfig
			};
			apps[appId] = app;
			
			if (!window.name) {
				window.name =  appId + '-' + Math.random();
			}
			
			var bootstrapApp = function(mayDefer) {
				var themeUri = getConfig('themeUri');
				loadTheme(themeUri);
				
				var widgetsetBase = getConfig('widgetsetBase');
				var widgetset = getConfig('widgetset');
				loadWidgetset(widgetsetBase, widgetset);
				
				if (getConfig('uidl') === undefined) {
					if (mayDefer) {
						fetchRootConfig();
					} else {
						throw "May not defer bootstrap any more";
					}
				} else {
					if (widgetsets[widgetset].callback) {
						log("Starting from bootstrap", appId);
						widgetsets[widgetset].callback(appId);
					}  else {
						log("Setting pending startup", appId);
						widgetsets[widgetset].pendingApps.push(appId);
					}
				}
			};
			bootstrapApp(true);

			if (getConfig("debug")) {
				// TODO debug state is now global for the entire page, but should somehow only be set for the current application  
				window.vaadin.debug = true;
			}
			
			return app;
		},
		clients: {},
		getApp: function(appId) {
			var app = apps[appId]; 
			return app;
		},
		loadTheme: loadTheme,
		registerWidgetset: function(widgetset, callback) {
			log("Widgetset registered", widgetset);
			widgetsets[widgetset].callback = callback;
			for(var i = 0; i < widgetsets[widgetset].pendingApps.length; i++) {
				var appId = widgetsets[widgetset].pendingApps[i];
				log("Starting from register widgetset", appId);
				callback(appId);
			}
			widgetsets[widgetset].pendingApps = null;
		},
		getBrowserDetailsParameters: function(parentElementId) {
			// Screen height and width
			var url = 'sh=' + window.screen.height;
			url += '&sw=' + window.screen.width;
			
			// Window height and width
			var cw = 0;
			var ch = 0;
			if(typeof(window.innerWidth) == 'number') {
				// Modern browsers
				cw = window.innerWidth;
				ch = window.innerHeight;
			} else {
				// IE 8
				cw = document.documentElement.clientWidth;
				ch = document.documentElement.clientHeight;
			}
			url += '&cw=' + cw + '&ch=' + ch;
			

			var d = new Date();
			
			url += '&curdate=' + d.getTime();
			
			var tzo1 = d.getTimezoneOffset(); // current offset
			var dstDiff = 0;
			var rtzo = tzo1;
			
			for (var m=12;m>0;m--) {
				d.setUTCMonth(m);
				var tzo2 = d.getTimezoneOffset();
				if (tzo1 != tzo2) {
					dstDiff =  (tzo1 > tzo2 ? tzo1-tzo2 : tzo2-tzo1); // offset w/o DST
					rtzo = (tzo1 > tzo2 ? tzo1 : tzo2); // offset w/o DST
					break;
				}
			}

			// Time zone offset
			url += '&tzo=' + tzo1;
			
			// DST difference
			url += '&dstd=' + dstDiff;
			
			// Raw time zone offset
			url += '&rtzo=' + rtzo;
			
			// DST in effect?
			url += '&dston=' + (tzo1 != rtzo);
			
			var pe = document.getElementById(parentElementId);
			if (pe) {
				url += '&vw=' + pe.offsetWidth;
				url += '&vh=' + pe.offsetHeight;
			}
			
			// Location
			url += '&loc=' + encodeURIComponent(location.href);

			// Window name
			if (window.name) {
				url += '&wn=' + encodeURIComponent(window.name);
			}
			
			// Detect touch device support
	        try { document.createEvent("TouchEvent"); url += "&td=1";} catch(e){};
	        
	        return url;
		}
	};
	
	log('Vaadin bootstrap loaded');
})();