Debian Codegraph @

dojox/html/_base.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare",
3 "dojo/Deferred",
4 "dojo/dom-construct",
5 "dojo/html",
6 "dojo/_base/kernel",
7 "dojo/_base/lang",
8 "dojo/ready",
9 "dojo/_base/sniff",
10 "dojo/_base/url",
11 "dojo/_base/xhr",
12 "dojo/when",
13 "dojo/_base/window"
14 ], function(declare, Deferred, domConstruct, htmlUtil, kernel, lang, ready, has, _Url, xhrUtil, when, windowUtil){
15
16 /*
17 Status: don't know where this will all live exactly
18 Need to pull in the implementation of the various helper methods
19 Some can be static method, others maybe methods of the ContentSetter (?)
20
21 Gut the ContentPane, replace its _setContent with our own call to dojox/html.set()
22
23
24 */
25 var html = kernel.getObject("dojox.html", true);
26
27 if(has("ie")){
28 var alphaImageLoader = /(AlphaImageLoader\([^)]*?src=(['"]))(?![a-z]+:|\/)([^\r\n;}]+?)(\2[^)]*\)\s*[;}]?)/g;
29 }
30
31 // css at-rules must be set before any css declarations according to CSS spec
32 // match:
33 // @import 'http://dojotoolkit.org/dojo.css';
34 // @import 'you/never/thought/' print;
35 // @import url("it/would/work") tv, screen;
36 // @import url(/did/you/now.css);
37 // but not:
38 // @namespace dojo "http://dojotoolkit.org/dojo.css"; /* namespace URL should always be a absolute URI */
39 // @charset 'utf-8';
40 // @media print{ #menuRoot {display:none;} }
41
42 // we adjust all paths that dont start on '/' or contains ':'
43 //(?![a-z]+:|\/)
44
45 var cssPaths = /(?:(?:@import\s*(['"])(?![a-z]+:|\/)([^\r\n;{]+?)\1)|url\(\s*(['"]?)(?![a-z]+:|\/)([^\r\n;]+?)\3\s*\))([a-z, \s]*[;}]?)/g;
46
47 var adjustCssPaths = html._adjustCssPaths = function(cssUrl, cssText){
48 // summary:
49 // adjusts relative paths in cssText to be relative to cssUrl
50 // a path is considered relative if it doesn't start with '/' and not contains ':'
51 // description:
52 // Say we fetch a HTML page from level1/page.html
53 // It has some inline CSS:
54 // | @import "css/page.css" tv, screen;
55 // | ...
56 // | background-image: url(images/aplhaimage.png);
57 //
58 // as we fetched this HTML and therefore this CSS
59 // from level1/page.html, these paths needs to be adjusted to:
60 // | @import 'level1/css/page.css' tv, screen;
61 // | ...
62 // | background-image: url(level1/images/alphaimage.png);
63 //
64 // In IE it will also adjust relative paths in AlphaImageLoader()
65 // | filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/alphaimage.png');
66 // will be adjusted to:
67 // | filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='level1/images/alphaimage.png');
68 //
69 // Please note that any relative paths in AlphaImageLoader in external css files wont work, as
70 // the paths in AlphaImageLoader is MUST be declared relative to the HTML page,
71 // not relative to the CSS file that declares it
72
73 if(!cssText || !cssUrl){ return; }
74
75 // support the ImageAlphaFilter if it exists, most people use it in IE 6 for transparent PNGs
76 // We are NOT going to kill it in IE 7 just because the PNGs work there. Somebody might have
77 // other uses for it.
78 // If user want to disable css filter in IE6 he/she should
79 // unset filter in a declaration that just IE 6 doesn't understands
80 // like * > .myselector { filter:none; }
81 if(alphaImageLoader){
82 cssText = cssText.replace(alphaImageLoader, function(ignore, pre, delim, url, post){
83 return pre + (new _Url(cssUrl, './'+url).toString()) + post;
84 });
85 }
86
87 return cssText.replace(cssPaths, function(ignore, delimStr, strUrl, delimUrl, urlUrl, media){
88 if(strUrl){
89 return '@import "' + (new _Url(cssUrl, './'+strUrl).toString()) + '"' + media;
90 }else{
91 return 'url(' + (new _Url(cssUrl, './'+urlUrl).toString()) + ')' + media;
92 }
93 });
94 };
95
96 // attributepaths one tag can have multiple paths, example:
97 // <input src="..." style="url(..)"/> or <a style="url(..)" href="..">
98 // <img style='filter:progid...AlphaImageLoader(src="noticeTheSrcHereRunsThroughHtmlSrc")' src="img">
99 var htmlAttrPaths = /(<[a-z][a-z0-9]*\s[^>]*)(?:(href|src)=(['"]?)([^>]*?)\3|style=(['"]?)([^>]*?)\5)([^>]*>)/gi;
100
101 var adjustHtmlPaths = html._adjustHtmlPaths = function(htmlUrl, cont){
102 var url = htmlUrl || "./";
103
104 return cont.replace(htmlAttrPaths,
105 function(tag, start, name, delim, relUrl, delim2, cssText, end){
106 return start + (name ?
107 (name + '=' + delim + (new _Url(url, relUrl).toString()) + delim)
108 : ('style=' + delim2 + adjustCssPaths(url, cssText) + delim2)
109 ) + end;
110 }
111 );
112 };
113
114 var snarfStyles = html._snarfStyles = function (/*String*/cssUrl, /*String*/cont, /*Array*/styles){
115 /**************** cut out all <style> and <link rel="stylesheet" href=".."> **************/
116 // also return any attributes from this tag (might be a media attribute)
117 // if cssUrl is set it will adjust paths accordingly
118 styles.attributes = [];
119
120 cont = cont.replace(/<[!][-][-](.|\s)*?[-][-]>/g,
121 function(comment){
122 return comment.replace(/<(\/?)style\b/ig,"&lt;$1Style").replace(/<(\/?)link\b/ig,"&lt;$1Link").replace(/@import "/ig,"@ import \"");
123 }
124 );
125 return cont.replace(/(?:<style([^>]*)>([\s\S]*?)<\/style>|<link\s+(?=[^>]*rel=['"]?stylesheet)([^>]*?href=(['"])([^>]*?)\4[^>\/]*)\/?>)/gi,
126 function(ignore, styleAttr, cssText, linkAttr, delim, href){
127 // trim attribute
128 var i, attr = (styleAttr||linkAttr||"").replace(/^\s*([\s\S]*?)\s*$/i, "$1");
129 if(cssText){
130 i = styles.push(cssUrl ? adjustCssPaths(cssUrl, cssText) : cssText);
131 }else{
132 i = styles.push('@import "' + href + '";');
133 attr = attr.replace(/\s*(?:rel|href)=(['"])?[^\s]*\1\s*/gi, ""); // remove rel=... and href=...
134 }
135 if(attr){
136 attr = attr.split(/\s+/);// split on both "\n", "\t", " " etc
137 var atObj = {}, tmp;
138 for(var j = 0, e = attr.length; j < e; j++){
139 tmp = attr[j].split('='); // split name='value'
140 atObj[tmp[0]] = tmp[1].replace(/^\s*['"]?([\s\S]*?)['"]?\s*$/, "$1"); // trim and remove ''
141 }
142 styles.attributes[i - 1] = atObj;
143 }
144 return "";
145 }
146 );
147 };
148
149 var snarfScripts = html._snarfScripts = function(cont, byRef){
150 // summary:
151 // strips out script tags from cont
152 // byRef:
153 // byRef = {errBack:function(){/*add your download error code here*/, downloadRemote: true(default false)}}
154 // byRef will have {code: 'jscode'} when this scope leaves
155 byRef.code = "";
156
157 //Update script tags nested in comments so that the script tag collector doesn't pick
158 //them up.
159 cont = cont.replace(/<[!][-][-](.|\s)*?[-][-]>/g,
160 function(comment){
161 return comment.replace(/<(\/?)script\b/ig,"&lt;$1Script");
162 }
163 );
164
165 function download(src){
166 if(byRef.downloadRemote){
167 // console.debug('downloading',src);
168 //Fix up src, in case there were entity character encodings in it.
169 //Probably only need to worry about a subset.
170 src = src.replace(/&([a-z0-9#]+);/g, function(m, name) {
171 switch(name) {
172 case "amp" : return "&";
173 case "gt" : return ">";
174 case "lt" : return "<";
175 default:
176 return name.charAt(0)=="#" ? String.fromCharCode(name.substring(1)) : "&"+name+";";
177 }
178 });
179 xhrUtil.get({
180 url: src,
181 sync: true,
182 load: function(code){
183 if(byRef.code !=="") {
184 code = "\n" + code;
185 }
186 byRef.code += code+";";
187 },
188 error: byRef.errBack
189 });
190 }
191 }
192
193 // match <script>, <script type="text/..., but not <script type="dojo(/method)...
194 return cont.replace(/<script\s*(?![^>]*type=['"]?(?:dojo\/|text\/html\b))[^>]*?(?:src=(['"]?)([^>]*?)\1[^>]*)?>([\s\S]*?)<\/script>/gi,
195 function(ignore, delim, src, code){
196 if(src){
197 download(src);
198 }else{
199 if(byRef.code !=="") {
200 code = "\n" + code;
201 }
202 byRef.code += code+";";
203 }
204 return "";
205 }
206 );
207 };
208
209 var evalInGlobal = html.evalInGlobal = function(code, appendNode){
210 // we do our own eval here as dojo.eval doesn't eval in global crossbrowser
211 // This work X browser but but it relies on a DOM
212 // plus it doesn't return anything, thats unrelevant here but not for dojo core
213 appendNode = appendNode || windowUtil.doc.body;
214 var n = appendNode.ownerDocument.createElement('script');
215 n.type = "text/javascript";
216 appendNode.appendChild(n);
217 n.text = code; // DOM 1 says this should work
218 };
219
220 html._ContentSetter = declare(/*===== "dojox/html._ContentSetter", =====*/ htmlUtil._ContentSetter, {
221 // adjustPaths: Boolean
222 // Adjust relative paths in html string content to point to this page
223 // Only useful if you grab content from a another folder than the current one
224 adjustPaths: false,
225 referencePath: ".",
226 renderStyles: false,
227
228 executeScripts: false,
229 scriptHasHooks: false,
230 scriptHookReplacement: null,
231
232 _renderStyles: function(styles){
233 // insert css from content into document head
234 this._styleNodes = [];
235 var st, att, cssText, doc = this.node.ownerDocument;
236 var head = doc.getElementsByTagName('head')[0];
237
238 for(var i = 0, e = styles.length; i < e; i++){
239 cssText = styles[i]; att = styles.attributes[i];
240 st = doc.createElement('style');
241 st.setAttribute("type", "text/css"); // this is required in CSS spec!
242
243 for(var x in att){
244 st.setAttribute(x, att[x]);
245 }
246
247 this._styleNodes.push(st);
248 head.appendChild(st); // must insert into DOM before setting cssText
249
250 if(st.styleSheet){ // IE
251 st.styleSheet.cssText = cssText;
252 }else{ // w3c
253 st.appendChild(doc.createTextNode(cssText));
254 }
255 }
256 },
257
258 empty: function() {
259 this.inherited("empty", arguments);
260
261 // empty out the styles array from any previous use
262 this._styles = [];
263 },
264
265 onBegin: function() {
266 // summary:
267 // Called after instantiation, but before set();
268 // It allows modification of any of the object properties - including the node and content
269 // provided - before the set operation actually takes place
270 // This implementation extends that of dojo/html/_ContentSetter
271 // to add handling for adjustPaths, renderStyles on the html string content before it is set
272 this.inherited("onBegin", arguments);
273
274 var cont = this.content,
275 node = this.node;
276
277 var styles = this._styles;// init vars
278 this._code = null; // do not execute scripts from previous content set
279
280 if(lang.isString(cont)){
281 if(this.adjustPaths && this.referencePath){
282 cont = adjustHtmlPaths(this.referencePath, cont);
283 }
284
285 if(this.renderStyles || this.cleanContent){
286 cont = snarfStyles(this.referencePath, cont, styles);
287 }
288
289 // because of a bug in IE, the script tag that is first in html hierarchy doesnt make it into the DOM
290 // when content is innerHTML'ed, so we can't use dojo/query to retrieve scripts from DOM
291 if(this.executeScripts){
292 var _t = this;
293 var byRef = {
294 downloadRemote: true,
295 errBack:function(e){
296 _t._onError.call(_t, 'Exec', 'Error downloading remote script in "'+_t.id+'"', e);
297 }
298 };
299 cont = snarfScripts(cont, byRef);
300 this._code = byRef.code;
301 }
302 }
303 this.content = cont;
304 },
305
306 onEnd: function() {
307 // summary:
308 // Called after set(), when the new content has been pushed into the node
309 // It provides an opportunity for post-processing before handing back the node to the caller
310 // This implementation extends that of dojo/html/_ContentSetter
311
312 var code = this._code,
313 styles = this._styles;
314
315 // clear old stylenodes from the DOM
316 // these were added by the last set call
317 // (in other words, if you dont keep and reuse the ContentSetter for a particular node
318 // .. you'll have no practical way to do this)
319 if(this._styleNodes && this._styleNodes.length){
320 while(this._styleNodes.length){
321 domConstruct.destroy(this._styleNodes.pop());
322 }
323 }
324 // render new style nodes
325 if(this.renderStyles && styles && styles.length){
326 this._renderStyles(styles);
327 }
328
329 // Deferred to signal when this function is complete
330 var d = new Deferred();
331
332 // Setup function to call onEnd() in the superclass, for parsing, and resolve the above Deferred when
333 // parsing is complete.
334 var superClassOnEndMethod = this.getInherited(arguments),
335 args = arguments,
336 callSuperclass = lang.hitch(this, function(){
337 superClassOnEndMethod.apply(this, args);
338
339 // If parser ran (parseContent == true), wait for it to finish, otherwise call d.resolve() immediately
340 when(this.parseDeferred, function(){ d.resolve(); });
341 });
342
343 if(this.executeScripts && code){
344 // Evaluate any <script> blocks in the content
345 if(this.cleanContent){
346 // clean JS from html comments and other crap that browser
347 // parser takes care of in a normal page load
348 code = code.replace(/(<!--|(?:\/\/)?-->|<!\[CDATA\[|\]\]>)/g, '');
349 }
350 if(this.scriptHasHooks){
351 // replace _container_ with this.scriptHookReplace()
352 // the scriptHookReplacement can be a string
353 // or a function, which when invoked returns the string you want to substitute in
354 code = code.replace(/_container_(?!\s*=[^=])/g, this.scriptHookReplacement);
355 }
356 try{
357 evalInGlobal(code, this.node);
358 }catch(e){
359 this._onError('Exec', 'Error eval script in '+this.id+', '+e.message, e);
360 }
361
362 // Finally, use ready() to wait for any require() calls from the <script> blocks to complete,
363 // then call onEnd() in the superclass, for parsing, and when that is done resolve the Deferred.
364 // For 2.0, remove the call to ready() (or this whole if() branch?) since the parser can do loading for us.
365 ready(callSuperclass);
366 }else{
367 // There were no <script>'s to execute, so immediately call onEnd() in the superclass, and
368 // when the parser finishes running, resolve the Deferred.
369 callSuperclass();
370 }
371
372 // Return a promise that resolves after the ready() call completes, and after the parser finishes running.
373 return d.promise;
374 },
375
376 tearDown: function() {
377 this.inherited(arguments);
378 delete this._styles;
379 // only tear down -or another set() - will explicitly throw away the
380 // references to the style nodes we added
381 if(this._styleNodes && this._styleNodes.length){
382 while(this._styleNodes.length){
383 domConstruct.destroy(this._styleNodes.pop());
384 }
385 }
386 delete this._styleNodes;
387 // reset the defaults from the prototype
388 // XXX: not sure if this is the correct intended behaviour, it was originally
389 // dojo.getObject(this.declaredClass).prototype which will not work with anonymous
390 // modules
391 lang.mixin(this, html._ContentSetter.prototype);
392 }
393
394 });
395
396 html.set = function(/* DomNode */ node, /* String|DomNode|NodeList */ cont, /* Object? */ params){
397 // TODO: add all the other options
398 // summary:
399 // inserts (replaces) the given content into the given node
400 // node:
401 // the parent element that will receive the content
402 // cont:
403 // the content to be set on the parent element.
404 // This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
405 // params:
406 // Optional flags/properties to configure the content-setting. See dojo/html/_ContentSetter
407 // example:
408 // A safe string/node/nodelist content replacement/injection with hooks for extension
409 // Example Usage:
410 // | require(["dojo/html", "dojox/html", "dojo/domReady!"], function(html){
411 // | html.set(node, "some string");
412 // | html.set(node, contentNode, {options});
413 // | html.set(node, myNode.childNodes, {options});
414 // | });
415
416 if(!params){
417 // simple and fast
418 return htmlUtil._setNodeContent(node, cont, true);
419 }else{
420 // more options but slower
421 var op = new html._ContentSetter(lang.mixin(
422 params,
423 { content: cont, node: node }
424 ));
425 return op.set();
426 }
427 };
428
429 return html;
430 });