Subversion Repositories Applications.papyrus

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2150 mathias 1
if(!dojo._hasResource["dojox.layout.ContentPane"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2
dojo._hasResource["dojox.layout.ContentPane"] = true;
3
dojo.provide("dojox.layout.ContentPane");
4
 
5
dojo.require("dijit.layout.ContentPane");
6
 
7
(function(){ // private scope, sort of a namespace
8
 
9
	// TODO: should these methods be moved to dojox.html.cssPathAdjust or something?
10
 
11
	// css at-rules must be set before any css declarations according to CSS spec
12
	// match:
13
	// @import 'http://dojotoolkit.org/dojo.css';
14
	// @import 'you/never/thought/' print;
15
	// @import url("it/would/work") tv, screen;
16
	// @import url(/did/you/now.css);
17
	// but not:
18
	// @namespace dojo "http://dojotoolkit.org/dojo.css"; /* namespace URL should always be a absolute URI */
19
	// @charset 'utf-8';
20
	// @media print{ #menuRoot {display:none;} }
21
 
22
 
23
	// we adjust all paths that dont start on '/' or contains ':'
24
	//(?![a-z]+:|\/)
25
 
26
	if(dojo.isIE){
27
		var alphaImageLoader = /(AlphaImageLoader\([^)]*?src=(['"]))(?![a-z]+:|\/)([^\r\n;}]+?)(\2[^)]*\)\s*[;}]?)/g;
28
	}
29
 
30
	var cssPaths = /(?:(?:@import\s*(['"])(?![a-z]+:|\/)([^\r\n;{]+?)\1)|url\(\s*(['"]?)(?![a-z]+:|\/)([^\r\n;]+?)\3\s*\))([a-z, \s]*[;}]?)/g;
31
 
32
	function adjustCssPaths(cssUrl, cssText){
33
		//	summary:
34
		//		adjusts relative paths in cssText to be relative to cssUrl
35
		//		a path is considered relative if it doesn't start with '/' and not contains ':'
36
		//	description:
37
		//		Say we fetch a HTML page from level1/page.html
38
		//		It has some inline CSS:
39
		//			@import "css/page.css" tv, screen;
40
		//			...
41
		//			background-image: url(images/aplhaimage.png);
42
		//
43
		//		as we fetched this HTML and therefore this CSS
44
		//		from level1/page.html, these paths needs to be adjusted to:
45
		//			@import 'level1/css/page.css' tv, screen;
46
		//			...
47
		//			background-image: url(level1/images/alphaimage.png);
48
		//
49
		//		In IE it will also adjust relative paths in AlphaImageLoader()
50
		//			filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/alphaimage.png');
51
		//		will be adjusted to:
52
		//			filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='level1/images/alphaimage.png');
53
		//
54
		//		Please note that any relative paths in AlphaImageLoader in external css files wont work, as
55
		//		the paths in AlphaImageLoader is MUST be declared relative to the HTML page,
56
		//		not relative to the CSS file that declares it
57
 
58
		if(!cssText || !cssUrl){ return; }
59
 
60
		// support the ImageAlphaFilter if it exists, most people use it in IE 6 for transparent PNGs
61
		// We are NOT going to kill it in IE 7 just because the PNGs work there. Somebody might have
62
		// other uses for it.
63
		// If user want to disable css filter in IE6  he/she should
64
		// unset filter in a declaration that just IE 6 doesn't understands
65
		// like * > .myselector { filter:none; }
66
		if(alphaImageLoader){
67
			cssText = cssText.replace(alphaImageLoader, function(ignore, pre, delim, url, post){
68
				return pre + (new dojo._Url(cssUrl, './'+url).toString()) + post;
69
			});
70
		}
71
 
72
		return cssText.replace(cssPaths, function(ignore, delimStr, strUrl, delimUrl, urlUrl, media){
73
			if(strUrl){
74
				return '@import "' + (new dojo._Url(cssUrl, './'+strUrl).toString()) + '"' + media;
75
			}else{
76
				return 'url(' + (new dojo._Url(cssUrl, './'+urlUrl).toString()) + ')' + media;
77
			}
78
		});
79
	}
80
 
81
	// attributepaths one tag can have multiple paths, example:
82
	// <input src="..." style="url(..)"/> or <a style="url(..)" href="..">
83
	// <img style='filter:progid...AlphaImageLoader(src="noticeTheSrcHereRunsThroughHtmlSrc")' src="img">
84
	var htmlAttrPaths = /(<[a-z][a-z0-9]*\s[^>]*)(?:(href|src)=(['"]?)([^>]*?)\3|style=(['"]?)([^>]*?)\5)([^>]*>)/gi;
85
 
86
	function adjustHtmlPaths(htmlUrl, cont){
87
		var url = htmlUrl || "./";
88
 
89
		return cont.replace(htmlAttrPaths,
90
			function(tag, start, name, delim, relUrl, delim2, cssText, end){
91
				return start + (name ?
92
							(name + '=' + delim + (new dojo._Url(url, relUrl).toString()) + delim)
93
						: ('style=' + delim2 + adjustCssPaths(url, cssText) + delim2)
94
				) + end;
95
			}
96
		);
97
	}
98
 
99
	function secureForInnerHtml(cont){
100
		/********* remove <!DOCTYPE.. and <title>..</title> tag **********/
101
		// khtml is picky about dom faults, you can't attach a <style> or <title> node as child of body
102
		// must go into head, so we need to cut out those tags
103
		return cont.replace(/(?:\s*<!DOCTYPE\s[^>]+>|<title[^>]*>[\s\S]*?<\/title>)/ig, "");
104
	}
105
 
106
	function snarfStyles(/*String*/cssUrl, /*String*/cont, /*Array*/styles){
107
		/****************  cut out all <style> and <link rel="stylesheet" href=".."> **************/
108
		// also return any attributes from this tag (might be a media attribute)
109
		// if cssUrl is set it will adjust paths accordingly
110
		styles.attributes = [];
111
 
112
		return cont.replace(/(?:<style([^>]*)>([\s\S]*?)<\/style>|<link\s+(?=[^>]*rel=['"]?stylesheet)([^>]*?href=(['"])([^>]*?)\4[^>\/]*)\/?>)/gi,
113
			function(ignore, styleAttr, cssText, linkAttr, delim, href){
114
				// trim attribute
115
				var i, attr = (styleAttr||linkAttr||"").replace(/^\s*([\s\S]*?)\s*$/i, "$1");
116
				if(cssText){
117
					i = styles.push(cssUrl ? adjustCssPaths(cssUrl, cssText) : cssText);
118
				}else{
119
					i = styles.push('@import "' + href + '";')
120
					attr = attr.replace(/\s*(?:rel|href)=(['"])?[^\s]*\1\s*/gi, ""); // remove rel=... and href=...
121
				}
122
				if(attr){
123
					attr = attr.split(/\s+/);// split on both "\n", "\t", " " etc
124
					var atObj = {}, tmp;
125
					for(var j = 0, e = attr.length; j < e; j++){
126
						tmp = attr[j].split('=')// split name='value'
127
						atObj[tmp[0]] = tmp[1].replace(/^\s*['"]?([\s\S]*?)['"]?\s*$/, "$1"); // trim and remove ''
128
					}
129
					styles.attributes[i - 1] = atObj;
130
				}
131
				return ""; // squelsh the <style> or <link>
132
			}
133
		);
134
	}
135
 
136
	function snarfScripts(cont, byRef){
137
		// summary
138
		//		strips out script tags from cont
139
		// invoke with
140
		//	byRef = {errBack:function(){/*add your download error code here*/, downloadRemote: true(default false)}}
141
		//	byRef will have {code: 'jscode'} when this scope leaves
142
		byRef.code = "";
143
 
144
		function download(src){
145
			if(byRef.downloadRemote){
146
				// console.debug('downloading',src);
147
				dojo.xhrGet({
148
					url: src,
149
					sync: true,
150
					load: function(code){
151
						byRef.code += code+";";
152
					},
153
					error: byRef.errBack
154
				});
155
			}
156
		}
157
 
158
		// match <script>, <script type="text/..., but not <script type="dojo(/method)...
159
		return cont.replace(/<script\s*(?![^>]*type=['"]?dojo)(?:[^>]*?(?:src=(['"]?)([^>]*?)\1[^>]*)?)*>([\s\S]*?)<\/script>/gi,
160
			function(ignore, delim, src, code){
161
				if(src){
162
					download(src);
163
				}else{
164
					byRef.code += code;
165
				}
166
				return "";
167
			}
168
		);
169
	}
170
 
171
	function evalInGlobal(code, appendNode){
172
		// we do our own eval here as dojo.eval doesn't eval in global crossbrowser
173
		// This work X browser but but it relies on a DOM
174
		// plus it doesn't return anything, thats unrelevant here but not for dojo core
175
		appendNode = appendNode || dojo.doc.body;
176
		var n = appendNode.ownerDocument.createElement('script');
177
		n.type = "text/javascript";
178
		appendNode.appendChild(n);
179
		n.text = code; // DOM 1 says this should work
180
	}
181
 
182
	/*=====
183
	dojox.layout.ContentPane.DeferredHandle = {
184
		// cancel: Function
185
		cancel: function(){
186
			// summary: cancel a in flight download
187
		},
188
 
189
		addOnLoad: function(func){
190
			// summary: add a callback to the onLoad chain
191
			// func: Function
192
		},
193
 
194
		addOnUnload: function(func){
195
			// summary: add a callback to the onUnload chain
196
			// func: Function
197
		}
198
	}
199
	=====*/
200
 
201
 
202
dojo.declare("dojox.layout.ContentPane", dijit.layout.ContentPane, {
203
	// summary:
204
	//		An extended version of dijit.layout.ContentPane
205
	//		Supports infile scrips and external ones declared by <script src=''
206
	//		relative path adjustments (content fetched from a different folder)
207
	//		<style> and <link rel='stylesheet' href='..'> tags,
208
	//		css paths inside cssText is adjusted (if you set adjustPaths = true)
209
	//
210
	//		NOTE that dojo.require in script in the fetched file isn't recommended
211
	//		Many widgets need to be required at page load to work properly
212
 
213
	// adjustPaths: Boolean
214
	//		Adjust relative paths in html string content to point to this page
215
	//		Only usefull if you grab content from a another folder then the current one
216
	adjustPaths: false,
217
 
218
	// cleanContent: Boolean
219
	//	summary:
220
	//		cleans content to make it less likly to generate DOM/JS errors.
221
	//	description:
222
	//		usefull if you send contentpane a complete page, instead of a html fragment
223
	//		scans for
224
	//			style nodes, inserts in Document head
225
	//			title Node, remove
226
	//			DOCTYPE tag, remove
227
	//			<!-- *JS code here* -->
228
	//			<![CDATA[ *JS code here* ]]>
229
	cleanContent: false,
230
 
231
	// renderStyles: Boolean
232
	//		trigger/load styles in the content
233
	renderStyles: false,
234
 
235
	// executeScripts: Boolean
236
	//		Execute (eval) scripts that is found in the content
237
	executeScripts: true,
238
 
239
	// scriptHasHooks: Boolean
240
	//		replace keyword '_container_' in scripts with 'dijit.byId(this.id)'
241
	// NOTE this name might change in the near future
242
	scriptHasHooks: false,
243
 
244
	/*======
245
	// ioMethod: dojo.xhrGet|dojo.xhrPost
246
	//		reference to the method that should grab the content
247
	ioMethod: dojo.xhrGet,
248
 
249
	// ioArgs: Object
250
	//		makes it possible to add custom args to xhrGet, like ioArgs.headers['X-myHeader'] = 'true'
251
	ioArgs: {},
252
 
253
	// onLoadDeferred: dojo.Deferred
254
	//		callbackchain will start when onLoad occurs
255
	onLoadDeferred: new dojo.Deferred(),
256
 
257
	// onUnloadDeferred: dojo.Deferred
258
	//		callbackchain will start when onUnload occurs
259
	onUnloadDeferred: new dojo.Deferred(),
260
 
261
	setHref: function(url){
262
		// summary: replace current content with url's content
263
		return ;// dojox.layout.ContentPane.DeferredHandle
264
	},
265
 
266
	refresh: function(){
267
		summary: force a re-download of content
268
		return ;// dojox.layout.ContentPane.DeferredHandle
269
	},
270
 
271
	======*/
272
 
273
	constructor: function(){
274
		// init per instance properties, initializer doesn't work here because how things is hooked up in dijit._Widget
275
		this.ioArgs = {};
276
		this.ioMethod = dojo.xhrGet;
277
		this.onLoadDeferred = new dojo.Deferred();
278
		this.onUnloadDeferred = new dojo.Deferred();
279
	},
280
 
281
	postCreate: function(){
282
		// override to support loadDeferred
283
		this._setUpDeferreds();
284
 
285
		dijit.layout.ContentPane.prototype.postCreate.apply(this, arguments);
286
	},
287
 
288
	onExecError: function(e){
289
		// summary
290
		//		event callback, called on script error or on java handler error
291
		//		overide and return your own html string if you want a some text
292
		//		displayed within the ContentPane
293
	},
294
 
295
	setContent: function(data){
296
		// summary: set data as new content, sort of like innerHTML
297
		// data: String|DomNode|NodeList|dojo.NodeList
298
		if(!this._isDownloaded){
299
			var defObj = this._setUpDeferreds();
300
		}
301
 
302
		dijit.layout.ContentPane.prototype.setContent.apply(this, arguments);
303
		return defObj; // dojox.layout.ContentPane.DeferredHandle
304
	},
305
 
306
	cancel: function(){
307
		// summary: cancels a inflight download
308
		if(this._xhrDfd && this._xhrDfd.fired == -1){
309
			// we are still in flight, which means we should reset our DeferredHandle
310
			// otherwise we will trigger onUnLoad chain of the canceled content,
311
			// the canceled content have never gotten onLoad so it shouldn't get onUnload
312
			this.onUnloadDeferred = null;
313
		}
314
		dijit.layout.ContentPane.prototype.cancel.apply(this, arguments);
315
	},
316
 
317
	_setUpDeferreds: function(){
318
		var _t = this, cancel = function(){ _t.cancel();	}
319
		var onLoad = (_t.onLoadDeferred = new dojo.Deferred());
320
		var onUnload = (_t._nextUnloadDeferred = new dojo.Deferred());
321
		return {
322
			cancel: cancel,
323
			addOnLoad: function(func){onLoad.addCallback(func);},
324
			addOnUnload: function(func){onUnload.addCallback(func);}
325
		};
326
	},
327
 
328
	_onLoadHandler: function(){
329
		dijit.layout.ContentPane.prototype._onLoadHandler.apply(this, arguments);
330
		if(this.onLoadDeferred){
331
			this.onLoadDeferred.callback(true);
332
		}
333
	},
334
 
335
	_onUnloadHandler: function(){
336
		this.isLoaded = false;
337
		this.cancel();// need to cancel so we don't get any inflight suprises
338
		if(this.onUnloadDeferred){
339
			this.onUnloadDeferred.callback(true);
340
		}
341
 
342
		dijit.layout.ContentPane.prototype._onUnloadHandler.apply(this, arguments);
343
 
344
		if(this._nextUnloadDeferred){
345
			this.onUnloadDeferred = this._nextUnloadDeferred;
346
		}
347
	},
348
 
349
	_onError: function(type, err){
350
		dijit.layout.ContentPane.prototype._onError.apply(this, arguments);
351
		if(this.onLoadDeferred){
352
			this.onLoadDeferred.errback(err);
353
		}
354
	},
355
 
356
	_prepareLoad: function(forceLoad){
357
		// sets up for a xhrLoad, load is deferred until widget is showing
358
		var defObj = this._setUpDeferreds();
359
 
360
		dijit.layout.ContentPane.prototype._prepareLoad.apply(this, arguments);
361
 
362
		return defObj;
363
	},
364
 
365
	_setContent: function(cont){
366
		// override dijit.layout.ContentPane._setContent, to enable path adjustments
367
		var styles = [];// init vars
368
		if(dojo.isString(cont)){
369
			if(this.adjustPaths && this.href){
370
				cont = adjustHtmlPaths(this.href, cont);
371
			}
372
			if(this.cleanContent){
373
				cont = secureForInnerHtml(cont);
374
			}
375
			if(this.renderStyles || this.cleanContent){
376
				cont = snarfStyles(this.href, cont, styles);
377
			}
378
 
379
			// because of a bug in IE, script tags that is first in html hierarchy doesnt make it into the DOM
380
			//	when content is innerHTML'ed, so we can't use dojo.query to retrieve scripts from DOM
381
			if(this.executeScripts){
382
				var _t = this, code, byRef = {
383
					downloadRemote: true,
384
					errBack:function(e){
385
						_t._onError.call(_t, 'Exec', 'Error downloading remote script in "'+_t.id+'"', e);
386
					}
387
				};
388
				cont = snarfScripts(cont, byRef);
389
				code = byRef.code;
390
			}
391
 
392
			// rationale for this block:
393
			// if containerNode/domNode is a table derivate tag, some browsers dont allow innerHTML on those
394
			var node = (this.containerNode || this.domNode), pre = post = '', walk = 0;
395
			switch(name = node.nodeName.toLowerCase()){
396
				case 'tr':
397
					pre = '<tr>'; post = '</tr>';
398
					walk += 1;//fallthrough
399
				case 'tbody': case 'thead':// children of THEAD is of same type as TBODY
400
					pre = '<tbody>' + pre; post += '</tbody>';
401
					walk += 1;// falltrough
402
				case 'table':
403
					pre = '<table>' + pre; post += '</table>';
404
					walk += 1;
405
					break;
406
			}
407
			if(walk){
408
				var n = node.ownerDocument.createElement('div');
409
				n.innerHTML = pre + cont + post;
410
				do{
411
					n = n.firstChild;
412
				}while(--walk);
413
				cont = n.childNodes;
414
			}
415
		}
416
 
417
		// render the content
418
		dijit.layout.ContentPane.prototype._setContent.call(this, cont);
419
 
420
		// clear old stylenodes from the DOM
421
		if(this._styleNodes && this._styleNodes.length){
422
			while(this._styleNodes.length){
423
				dojo._destroyElement(this._styleNodes.pop());
424
			}
425
		}
426
		// render new style nodes
427
		if(this.renderStyles && styles && styles.length){
428
			this._renderStyles(styles);
429
		}
430
 
431
		if(this.executeScripts && code){
432
			if(this.cleanContent){
433
				// clean JS from html comments and other crap that browser
434
				// parser takes care of in a normal page load
435
				code = code.replace(/(<!--|(?:\/\/)?-->|<!\[CDATA\[|\]\]>)/g, '');
436
			}
437
			if(this.scriptHasHooks){
438
				// replace _container_ with dijit.byId(this.id)
439
				code = code.replace(/_container_(?!\s*=[^=])/g, "dijit.byId('"+this.id+"')");
440
			}
441
			try{
442
				evalInGlobal(code, (this.containerNode || this.domNode));
443
			}catch(e){
444
				this._onError('Exec', 'Error eval script in '+this.id+', '+e.message, e);
445
			}
446
		}
447
	},
448
 
449
	_renderStyles: function(styles){
450
		// insert css from content into document head
451
		this._styleNodes = [];
452
		var st, att, cssText, doc = this.domNode.ownerDocument;
453
		var head = doc.getElementsByTagName('head')[0];
454
 
455
		for(var i = 0, e = styles.length; i < e; i++){
456
			cssText = styles[i]; att = styles.attributes[i];
457
			st = doc.createElement('style');
458
			st.setAttribute("type", "text/css"); // this is required in CSS spec!
459
 
460
			for(var x in att){
461
				st.setAttribute(x, att[x])
462
			}
463
 
464
			this._styleNodes.push(st);
465
			head.appendChild(st); // must insert into DOM before setting cssText
466
 
467
			if(st.styleSheet){ // IE
468
				st.styleSheet.cssText = cssText;
469
			}else{ // w3c
470
				st.appendChild(doc.createTextNode(cssText));
471
			}
472
		}
473
	}
474
});
475
 
476
})();
477
 
478
}