]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/get/get.js
Release 6.2.1
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / get / get.js
1 /*
2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 3.0.0
6 build: 1549
7 */
8 YUI.add('get', function(Y) {
9
10 (function() {
11
12 /**
13  * Provides a mechanism to fetch remote resources and
14  * insert them into a document.
15  * @module yui
16  * @submodule get
17  */
18
19 var ua         = Y.UA, 
20     L          = Y.Lang,
21     // PREFIX     = Y.guid(),
22     TYPE_JS    = "text/javascript",
23     TYPE_CSS   = "text/css",
24     STYLESHEET = "stylesheet";
25
26 /**
27  * Fetches and inserts one or more script or link nodes into the document 
28  * @class Get
29  * @static
30  */
31 Y.Get = function() {
32
33     /**
34      * hash of queues to manage multiple requests
35      * @property queues
36      * @private
37      */
38     var queues={}, 
39         
40     /**
41      * queue index used to generate transaction ids
42      * @property qidx
43      * @type int
44      * @private
45      */
46         qidx=0, 
47         
48     /**
49      * interal property used to prevent multiple simultaneous purge 
50      * processes
51      * @property purging
52      * @type boolean
53      * @private
54      */
55         purging=false,
56
57     
58     /** 
59      * Generates an HTML element, this is not appended to a document
60      * @method _node
61      * @param type {string} the type of element
62      * @param attr {string} the attributes
63      * @param win {Window} optional window to create the element in
64      * @return {HTMLElement} the generated node
65      * @private
66      */
67     _node = function(type, attr, win) {
68         var w = win || Y.config.win, d=w.document, n=d.createElement(type),
69             i;
70
71         for (i in attr) {
72             if (attr[i] && attr.hasOwnProperty(i)) {
73                 n.setAttribute(i, attr[i]);
74             }
75         }
76
77         return n;
78     },
79
80     /**
81      * Generates a link node
82      * @method _linkNode
83      * @param url {string} the url for the css file
84      * @param win {Window} optional window to create the node in
85      * @param attributes optional attributes collection to apply to the new node
86      * @return {HTMLElement} the generated node
87      * @private
88      */
89     _linkNode = function(url, win, attributes) {
90         var o = {
91             id:   Y.guid(),
92             type: TYPE_CSS,
93             rel:  STYLESHEET,
94             href: url
95         };
96         if (attributes) {
97             Y.mix(o, attributes);
98         }
99         return _node("link", o, win);
100     },
101
102     /**
103      * Generates a script node
104      * @method _scriptNode
105      * @param url {string} the url for the script file
106      * @param win {Window} optional window to create the node in
107      * @param attributes optional attributes collection to apply to the new node
108      * @return {HTMLElement} the generated node
109      * @private
110      */
111     _scriptNode = function(url, win, attributes) {
112         var o = {
113             id:   Y.guid(),
114             type: TYPE_JS,
115             src:  url
116         };
117
118         if (attributes) {
119             Y.mix(o, attributes);
120         }
121
122         return _node("script", o, win);
123     },
124
125     /**
126      * Removes the nodes for the specified queue
127      * @method _purge
128      * @private
129      */
130     _purge = function(tId) {
131         var q=queues[tId], n, l, d, h, s, i, node, attr;
132         if (q) {
133             n = q.nodes; 
134             l = n.length;
135             d = q.win.document;
136             h = d.getElementsByTagName("head")[0];
137
138             if (q.insertBefore) {
139                 s = _get(q.insertBefore, tId);
140                 if (s) {
141                     h = s.parentNode;
142                 }
143             }
144
145             for (i=0; i<l; i=i+1) {
146                 node = n[i];
147                 if (node.clearAttributes) {
148                     node.clearAttributes();
149                 } else {
150                     // This is a hostile delete
151                     // operation attempting to improve
152                     // memory performance.  As such, the
153                     // hasOwnProperty check is intentionally
154                     // ommitted.
155                     for (attr in node) {
156                         delete node[attr];
157                     }
158                 }
159
160                 h.removeChild(node);
161             }
162         }
163         q.nodes = [];
164     },
165
166     /**
167      * Returns the data payload for callback functions
168      * @method _returnData
169      * @private
170      */
171     _returnData = function(q, msg, result) {
172         return {
173                 tId: q.tId,
174                 win: q.win,
175                 data: q.data,
176                 nodes: q.nodes,
177                 msg: msg,
178                 statusText: result,
179                 purge: function() {
180                     _purge(this.tId);
181                 }
182             };
183     },
184
185     /**
186      * The transaction is finished
187      * @method _end
188      * @param id {string} the id of the request
189      * @private
190      */
191     _end = function(id, msg, result) {
192         var q = queues[id], sc;
193         if (q && q.onEnd) {
194             sc = q.context || q;
195             q.onEnd.call(sc, _returnData(q, msg, result));
196         }
197     },
198
199     /*
200      * The request failed, execute fail handler with whatever
201      * was accomplished.  There isn't a failure case at the
202      * moment unless you count aborted transactions
203      * @method _fail
204      * @param id {string} the id of the request
205      * @private
206      */
207     _fail = function(id, msg) {
208
209
210         var q = queues[id], sc;
211         if (q.timer) {
212             // q.timer.cancel();
213             clearTimeout(q.timer);
214         }
215
216         // execute failure callback
217         if (q.onFailure) {
218             sc = q.context || q;
219             q.onFailure.call(sc, _returnData(q, msg));
220         }
221
222         _end(id, msg, 'failure');
223     },
224
225     _get = function(nId, tId) {
226         var q = queues[tId],
227             n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
228         if (!n) {
229             _fail(tId, "target node not found: " + nId);
230         }
231
232         return n;
233     },
234
235     /**
236      * The request is complete, so executing the requester's callback
237      * @method _finish
238      * @param id {string} the id of the request
239      * @private
240      */
241     _finish = function(id) {
242         var q = queues[id], msg, sc;
243         if (q.timer) {
244             // q.timer.cancel();
245             clearTimeout(q.timer);
246         }
247         q.finished = true;
248
249         if (q.aborted) {
250             msg = "transaction " + id + " was aborted";
251             _fail(id, msg);
252             return;
253         }
254
255         // execute success callback
256         if (q.onSuccess) {
257             sc = q.context || q;
258             q.onSuccess.call(sc, _returnData(q));
259         }
260
261         _end(id, msg, 'OK');
262     },
263
264     /**
265      * Timeout detected
266      * @method _timeout
267      * @param id {string} the id of the request
268      * @private
269      */
270     _timeout = function(id) {
271         var q = queues[id], sc;
272         if (q.onTimeout) {
273             sc = q.context || q;
274             q.onTimeout.call(sc, _returnData(q));
275         }
276
277         _end(id, 'timeout', 'timeout');
278     },
279     
280
281     /**
282      * Loads the next item for a given request
283      * @method _next
284      * @param id {string} the id of the request
285      * @param loaded {string} the url that was just loaded, if any
286      * @private
287      */
288     _next = function(id, loaded) {
289
290
291         var q = queues[id], msg, w, d, h, n, url, s;
292
293         if (q.timer) {
294             // q.timer.cancel();
295             clearTimeout(q.timer);
296         }
297
298         if (q.aborted) {
299             msg = "transaction " + id + " was aborted";
300             _fail(id, msg);
301             return;
302         }
303
304         if (loaded) {
305             q.url.shift(); 
306             if (q.varName) {
307                 q.varName.shift(); 
308             }
309         } else {
310             // This is the first pass: make sure the url is an array
311             q.url = (L.isString(q.url)) ? [q.url] : q.url;
312             if (q.varName) {
313                 q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName;
314             }
315         }
316
317         w = q.win; 
318         d = w.document; 
319         h = d.getElementsByTagName("head")[0];
320
321         if (q.url.length === 0) {
322             _finish(id);
323             return;
324         } 
325
326         url = q.url[0];
327
328         // if the url is undefined, this is probably a trailing comma problem in IE
329         if (!url) {
330             q.url.shift(); 
331             return _next(id);
332         }
333
334
335         if (q.timeout) {
336             // q.timer = L.later(q.timeout, q, _timeout, id);
337             q.timer = setTimeout(function() { 
338                 _timeout(id);
339             }, q.timeout);
340         }
341
342         if (q.type === "script") {
343             n = _scriptNode(url, w, q.attributes);
344         } else {
345             n = _linkNode(url, w, q.attributes);
346         }
347
348         // track this node's load progress
349         _track(q.type, n, id, url, w, q.url.length);
350
351         // add the node to the queue so we can return it to the user supplied callback
352         q.nodes.push(n);
353
354         // add it to the head or insert it before 'insertBefore'
355         if (q.insertBefore) {
356             s = _get(q.insertBefore, id);
357             if (s) {
358                 s.parentNode.insertBefore(n, s);
359             }
360         } else {
361             h.appendChild(n);
362         }
363         
364
365         // FireFox does not support the onload event for link nodes, so there is
366         // no way to make the css requests synchronous. This means that the css 
367         // rules in multiple files could be applied out of order in this browser
368         // if a later request returns before an earlier one.  Safari too.
369         if ((ua.webkit || ua.gecko) && q.type === "css") {
370             _next(id, url);
371         }
372     },
373
374     /**
375      * Removes processed queues and corresponding nodes
376      * @method _autoPurge
377      * @private
378      */
379     _autoPurge = function() {
380
381         if (purging) {
382             return;
383         }
384
385         purging = true;
386
387         var i, q;
388
389         for (i in queues) {
390             if (queues.hasOwnProperty(i)) {
391                 q = queues[i];
392                 if (q.autopurge && q.finished) {
393                     _purge(q.tId);
394                     delete queues[i];
395                 }
396             }
397         }
398
399         purging = false;
400     },
401
402     /**
403      * Saves the state for the request and begins loading
404      * the requested urls
405      * @method queue
406      * @param type {string} the type of node to insert
407      * @param url {string} the url to load
408      * @param opts the hash of options for this request
409      * @private
410      */
411     _queue = function(type, url, opts) {
412
413         opts = opts || {};
414
415         var id = "q" + (qidx++), q,
416             thresh = opts.purgethreshold || Y.Get.PURGE_THRESH;
417
418         if (qidx % thresh === 0) {
419             _autoPurge();
420         }
421
422         queues[id] = Y.merge(opts, {
423             tId: id,
424             type: type,
425             url: url,
426             finished: false,
427             nodes: []
428         });
429
430         q           = queues[id];
431         q.win       = q.win || Y.config.win;
432         q.context   = q.context || q;
433         q.autopurge = ("autopurge" in q) ? q.autopurge : 
434                       (type === "script") ? true : false;
435
436         if (opts.charset) {
437             q.attributes = q.attributes || {};
438             q.attributes.charset = opts.charset;
439         }
440
441         // L.later(0, q, _next, id);
442         setTimeout(function() {
443             _next(id);
444         }, 0);
445
446         return {
447             tId: id
448         };
449     },
450
451     /**
452      * Detects when a node has been loaded.  In the case of
453      * script nodes, this does not guarantee that contained
454      * script is ready to use.
455      * @method _track
456      * @param type {string} the type of node to track
457      * @param n {HTMLElement} the node to track
458      * @param id {string} the id of the request
459      * @param url {string} the url that is being loaded
460      * @param win {Window} the targeted window
461      * @param qlength the number of remaining items in the queue,
462      * including this one
463      * @param trackfn {Function} function to execute when finished
464      * the default is _next
465      * @private
466      */
467     _track = function(type, n, id, url, win, qlength, trackfn) {
468         var f = trackfn || _next;
469
470         // IE supports the readystatechange event for script and css nodes
471         // Opera only for script nodes.  Opera support onload for script
472         // nodes, but this doesn't fire when there is a load failure.
473         // The onreadystatechange appears to be a better way to respond
474         // to both success and failure.
475         if (ua.ie) {
476             n.onreadystatechange = function() {
477                 var rs = this.readyState;
478                 if ("loaded" === rs || "complete" === rs) {
479                     n.onreadystatechange = null;
480                     f(id, url);
481                 }
482             };
483
484         // webkit prior to 3.x is no longer supported
485         } else if (ua.webkit) {
486
487             if (type === "script") {
488                 // Safari 3.x supports the load event for script nodes (DOM2)
489                 n.addEventListener("load", function() {
490                     f(id, url);
491                 });
492             } 
493
494         // FireFox and Opera support onload (but not DOM2 in FF) handlers for
495         // script nodes.  Opera, but not FF, supports the onload event for link
496         // nodes.
497         } else { 
498
499             n.onload = function() {
500                 f(id, url);
501             };
502
503             n.onerror = function(e) {
504                 _fail(id, e + ": " + url);
505             };
506         }
507     };
508
509     return {
510
511         /**
512          * The number of request required before an automatic purge.
513          * Can be configured via the 'purgethreshold' config
514          * property PURGE_THRESH
515          * @static
516          * @type int
517          * @default 20
518          * @private
519          */
520         PURGE_THRESH: 20,
521
522         /**
523          * Called by the the helper for detecting script load in Safari
524          * @method _finalize
525          * @static
526          * @param id {string} the transaction id
527          * @private
528          */
529         _finalize: function(id) {
530             // L.later(0, null, _finish, id);
531             setTimeout(function() {
532                 _finish(id);
533             }, 0);
534         },
535
536         /**
537          * Abort a transaction
538          * @method abort
539          * @static
540          * @param o {string|object} Either the tId or the object returned from
541          * script() or css()
542          */
543         abort: function(o) {
544             var id = (L.isString(o)) ? o : o.tId,
545                 q = queues[id];
546             if (q) {
547                 q.aborted = true;
548             }
549         }, 
550
551         /**
552          * Fetches and inserts one or more script nodes into the head
553          * of the current document or the document in a specified window.
554          *
555          * @method script
556          * @static
557          * @param url {string|string[]} the url or urls to the script(s)
558          * @param opts {object} Options: 
559          * <dl>
560          * <dt>onSuccess</dt>
561          * <dd>
562          * callback to execute when the script(s) are finished loading
563          * The callback receives an object back with the following
564          * data:
565          * <dl>
566          * <dt>win</dt>
567          * <dd>the window the script(s) were inserted into</dd>
568          * <dt>data</dt>
569          * <dd>the data object passed in when the request was made</dd>
570          * <dt>nodes</dt>
571          * <dd>An array containing references to the nodes that were
572          * inserted</dd>
573          * <dt>purge</dt>
574          * <dd>A function that, when executed, will remove the nodes
575          * that were inserted</dd>
576          * <dt>
577          * </dl>
578          * </dd>
579          * <dt>onTimeout</dt>
580          * <dd>
581          * callback to execute when a timeout occurs.
582          * The callback receives an object back with the following
583          * data:
584          * <dl>
585          * <dt>win</dt>
586          * <dd>the window the script(s) were inserted into</dd>
587          * <dt>data</dt>
588          * <dd>the data object passed in when the request was made</dd>
589          * <dt>nodes</dt>
590          * <dd>An array containing references to the nodes that were
591          * inserted</dd>
592          * <dt>purge</dt>
593          * <dd>A function that, when executed, will remove the nodes
594          * that were inserted</dd>
595          * <dt>
596          * </dl>
597          * </dd>
598          * <dt>onEnd</dt>
599          * <dd>a function that executes when the transaction finishes, regardless of the exit path</dd>
600          * <dt>onFailure</dt>
601          * <dd>
602          * callback to execute when the script load operation fails
603          * The callback receives an object back with the following
604          * data:
605          * <dl>
606          * <dt>win</dt>
607          * <dd>the window the script(s) were inserted into</dd>
608          * <dt>data</dt>
609          * <dd>the data object passed in when the request was made</dd>
610          * <dt>nodes</dt>
611          * <dd>An array containing references to the nodes that were
612          * inserted successfully</dd>
613          * <dt>purge</dt>
614          * <dd>A function that, when executed, will remove any nodes
615          * that were inserted</dd>
616          * <dt>
617          * </dl>
618          * </dd>
619          * <dt>context</dt>
620          * <dd>the execution context for the callbacks</dd>
621          * <dt>win</dt>
622          * <dd>a window other than the one the utility occupies</dd>
623          * <dt>autopurge</dt>
624          * <dd>
625          * setting to true will let the utilities cleanup routine purge 
626          * the script once loaded
627          * </dd>
628          * <dt>purgethreshold</dt>
629          * <dd>
630          * The number of transaction before autopurge should be initiated
631          * </dd>
632          * <dt>data</dt>
633          * <dd>
634          * data that is supplied to the callback when the script(s) are
635          * loaded.
636          * </dd>
637          * <dt>insertBefore</dt>
638          * <dd>node or node id that will become the new node's nextSibling</dd>
639          * </dl>
640          * <dt>charset</dt>
641          * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd>
642          * <dt>attributes</dt>
643          * <dd>An object literal containing additional attributes to add to the link tags</dd>
644          * <dt>timeout</dt>
645          * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
646          * <pre>
647          * &nbsp;&nbsp;Y.Get.script(
648          * &nbsp;&nbsp;["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
649          * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], &#123;
650          * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123;
651          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log("won't cause error because Y is the context");
652          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
653          * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123;
654          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
655          * &nbsp;&nbsp;&nbsp;&nbsp;onTimeout: function(o) &#123;
656          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
657          * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo",
658          * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout
659          * &nbsp;&nbsp;&nbsp;&nbsp;context: Y, // make the YUI instance
660          * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame
661          * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes
662          * &nbsp;&nbsp;&nbsp;&nbsp;purgetheshold: 1 // purge previous transaction before next transaction
663          * &nbsp;&nbsp;&#125;);
664          * </pre>
665          * @return {tId: string} an object containing info about the transaction
666          */
667         script: function(url, opts) { 
668             return _queue("script", url, opts); 
669         },
670
671         /**
672          * Fetches and inserts one or more css link nodes into the 
673          * head of the current document or the document in a specified
674          * window.
675          * @method css
676          * @static
677          * @param url {string} the url or urls to the css file(s)
678          * @param opts Options: 
679          * <dl>
680          * <dt>onSuccess</dt>
681          * <dd>
682          * callback to execute when the css file(s) are finished loading
683          * The callback receives an object back with the following
684          * data:
685          * <dl>win</dl>
686          * <dd>the window the link nodes(s) were inserted into</dd>
687          * <dt>data</dt>
688          * <dd>the data object passed in when the request was made</dd>
689          * <dt>nodes</dt>
690          * <dd>An array containing references to the nodes that were
691          * inserted</dd>
692          * <dt>purge</dt>
693          * <dd>A function that, when executed, will remove the nodes
694          * that were inserted</dd>
695          * <dt>
696          * </dl>
697          * </dd>
698          * <dt>context</dt>
699          * <dd>the execution context for the callbacks</dd>
700          * <dt>win</dt>
701          * <dd>a window other than the one the utility occupies</dd>
702          * <dt>data</dt>
703          * <dd>
704          * data that is supplied to the callbacks when the nodes(s) are
705          * loaded.
706          * </dd>
707          * <dt>insertBefore</dt>
708          * <dd>node or node id that will become the new node's nextSibling</dd>
709          * <dt>charset</dt>
710          * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd>
711          * <dt>attributes</dt>
712          * <dd>An object literal containing additional attributes to add to the link tags</dd>
713          * </dl>
714          * <pre>
715          *      Y.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css");
716          * </pre>
717          * <pre>
718          * &nbsp;&nbsp;Y.Get.css(
719          * &nbsp;&nbsp;["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css",
720          * &nbsp;&nbsp;&nbsp;&nbsp;insertBefore: 'custom-styles' // nodes will be inserted before the specified node
721          * &nbsp;&nbsp;&#125;);
722          * </pre>
723          * @return {tId: string} an object containing info about the transaction
724          */
725         css: function(url, opts) {
726             return _queue("css", url, opts); 
727         }
728     };
729 }();
730
731 })();
732
733
734 }, '3.0.0' );