]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/io/io-base.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / io / io-base.js
1 /*
2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 3.3.0
6 build: 3167
7 */
8 YUI.add('io-base', function(Y) {
9
10    /**
11     * Base IO functionality. Provides basic XHR transport support.
12     * @module io
13     * @submodule io-base
14     */
15
16    /**
17     * The io class is a utility that brokers HTTP requests through a simplified
18     * interface.  Specifically, it allows JavaScript to make HTTP requests to
19     * a resource without a page reload.  The underlying transport for making
20     * same-domain requests is the XMLHttpRequest object.  YUI.io can also use
21     * Flash, if specified as a transport, for cross-domain requests.
22     *
23     * @class io
24     */
25
26    /**
27     * @event io:start
28     * @description This event is fired by YUI.io when a transaction is initiated.
29     * @type Event Custom
30     */
31     var E_START = 'io:start',
32
33    /**
34     * @event io:complete
35     * @description This event is fired by YUI.io when a transaction is complete.
36     * Response status and data are accessible, if available.
37     * @type Event Custom
38     */
39     E_COMPLETE = 'io:complete',
40
41    /**
42     * @event io:success
43     * @description This event is fired by YUI.io when a transaction is complete, and
44     * the HTTP status resolves to HTTP2xx.
45     * @type Event Custom
46     */
47     E_SUCCESS = 'io:success',
48
49    /**
50     * @event io:failure
51     * @description This event is fired by YUI.io when a transaction is complete, and
52     * the HTTP status resolves to HTTP4xx, 5xx and above.
53     * @type Event Custom
54     */
55     E_FAILURE = 'io:failure',
56
57    /**
58     * @event io:end
59     * @description This event signifies the end of the transaction lifecycle.  The
60     * transaction transport is destroyed.
61     * @type Event Custom
62     */
63     E_END = 'io:end',
64
65     //--------------------------------------
66     //  Properties
67     //--------------------------------------
68    /**
69     * @description A transaction counter that increments for each transaction.
70     *
71     * @property transactionId
72     * @private
73     * @static
74     * @type int
75     */
76     transactionId = 0,
77
78    /**
79     * @description Object of default HTTP headers to be initialized and sent
80     * for all transactions.
81     *
82     * @property _headers
83     * @private
84     * @static
85     * @type object
86     */
87     _headers = {
88         'X-Requested-With' : 'XMLHttpRequest'
89     },
90
91    /**
92     * @description Object that stores timeout values for any transaction with
93     * a defined "timeout" configuration property.
94     *
95     * @property _timeout
96     * @private
97     * @static
98     * @type object
99     */
100     _timeout = {},
101
102     // Window reference
103     w = Y.config.win;
104
105     //--------------------------------------
106     //  Methods
107     //--------------------------------------
108
109    /**
110     * @description Method that creates the XMLHttpRequest transport
111     *
112     * @method _xhr
113     * @private
114     * @static
115     * @return object
116     */
117     function _xhr() {
118         return w.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
119     }
120
121
122    /**
123     * @description Method that increments _transactionId for each transaction.
124     *
125     * @method _id
126     * @private
127     * @static
128     * @return int
129     */
130     function _id() {
131         var id = transactionId;
132
133         transactionId++;
134
135         return id;
136     }
137
138    /**
139     * @description Method that creates a unique transaction object for each
140     * request.
141     *
142     * @method _create
143     * @private
144     * @static
145     * @param {number} c - configuration object subset to determine if
146     *                     the transaction is an XDR or file upload,
147     *                     requiring an alternate transport.
148     * @param {number} i - transaction id
149     * @return object
150     */
151     function _create(c, i) {
152         var o = {};
153             o.id = Y.Lang.isNumber(i) ? i : _id();
154             c = c || {};
155
156         if (!c.use && !c.upload) {
157             o.c = _xhr();
158         }
159         else if (c.use) {
160             if (c.use === 'native') {
161                 if (w.XDomainRequest) {
162                     o.c = new XDomainRequest();
163                     o.t = c.use;
164                 }
165                 else {
166                     o.c = _xhr();
167                 }
168             }
169             else {
170                 o.c = Y.io._transport[c.use];
171                 o.t = c.use;
172             }
173         }
174         else {
175             o.c = {};
176                         o.t = 'io:iframe';
177         }
178
179         return o;
180     }
181
182
183     function _destroy(o) {
184         if (w) {
185             if (o.c && w.XMLHttpRequest) {
186                 o.c.onreadystatechange = null;
187             }
188                         else if (Y.UA.ie === 6 && !o.t) {
189                                 // IE, when using XMLHttpRequest as an ActiveX Object, will throw
190                                 // a "Type Mismatch" error if the event handler is set to "null".
191                                 o.c.abort();
192                         }
193         }
194
195         o.c = null;
196         o = null;
197     }
198
199    /**
200     * @description Method for creating and subscribing transaction events.
201     *
202     * @method _tE
203     * @private
204     * @static
205     * @param {string} e - event to be published
206     * @param {object} c - configuration data subset for event subscription.
207     *
208     * @return void
209     */
210     function _tE(e, c) {
211         var eT = new Y.EventTarget().publish('transaction:' + e),
212             a = c.arguments,
213             cT = c.context || Y;
214
215         if (a) {
216             eT.on(c.on[e], cT, a);
217         }
218         else {
219             eT.on(c.on[e], cT);
220         }
221
222         return eT;
223     }
224
225    /**
226     * @description Fires event "io:start" and creates, fires a
227     * transaction-specific start event, if config.on.start is
228     * defined.
229     *
230     * @method _ioStart
231     * @private
232     * @static
233     * @param {number} id - transaction id
234     * @param {object} c - configuration object for the transaction.
235     *
236     * @return void
237     */
238     function _ioStart(id, c) {
239         var a = c.arguments;
240
241         if (a) {
242             Y.fire(E_START, id, a);
243         }
244         else {
245             Y.fire(E_START, id);
246         }
247
248         if (c.on && c.on.start) {
249             _tE('start', c).fire(id);
250         }
251     }
252
253
254    /**
255     * @description Fires event "io:complete" and creates, fires a
256     * transaction-specific "complete" event, if config.on.complete is
257     * defined.
258     *
259     * @method _ioComplete
260     * @private
261     * @static
262     * @param {object} o - transaction object.
263     * @param {object} c - configuration object for the transaction.
264     *
265     * @return void
266     */
267     function _ioComplete(o, c) {
268         var r = o.e ? { status: 0, statusText: o.e } : o.c,
269             a = c.arguments;
270
271         if (a) {
272             Y.fire(E_COMPLETE, o.id, r, a);
273         }
274         else {
275             Y.fire(E_COMPLETE, o.id, r);
276         }
277
278         if (c.on && c.on.complete) {
279             _tE('complete', c).fire(o.id, r);
280         }
281     }
282
283    /**
284     * @description Fires event "io:end" and creates, fires a
285     * transaction-specific "end" event, if config.on.end is
286     * defined.
287     *
288     * @method _ioEnd
289     * @private
290     * @static
291     * @param {object} o - transaction object.
292     * @param {object} c - configuration object for the transaction.
293     *
294     * @return void
295     */
296     function _ioEnd(o, c) {
297         var a = c.arguments;
298
299         if (a) {
300             Y.fire(E_END, o.id, a);
301         }
302         else {
303             Y.fire(E_END, o.id);
304         }
305
306         if (c.on && c.on.end) {
307             _tE('end', c).fire(o.id);
308         }
309
310         _destroy(o);
311     }
312
313    /**
314     * @description Fires event "io:success" and creates, fires a
315     * transaction-specific "success" event, if config.on.success is
316     * defined.
317     *
318     * @method _ioSuccess
319     * @private
320     * @static
321     * @param {object} o - transaction object.
322     * @param {object} c - configuration object for the transaction.
323     *
324     * @return void
325     */
326     function _ioSuccess(o, c) {
327         var a = c.arguments;
328
329         if (a) {
330             Y.fire(E_SUCCESS, o.id, o.c, a);
331         }
332         else {
333             Y.fire(E_SUCCESS, o.id, o.c);
334         }
335
336         if (c.on && c.on.success) {
337             _tE('success', c).fire(o.id, o.c);
338         }
339
340         _ioEnd(o, c);
341     }
342
343    /**
344     * @description Fires event "io:failure" and creates, fires a
345     * transaction-specific "failure" event, if config.on.failure is
346     * defined.
347     *
348     * @method _ioFailure
349     * @private
350     * @static
351     * @param {object} o - transaction object.
352     * @param {object} c - configuration object for the transaction.
353     *
354     * @return void
355     */
356     function _ioFailure(o, c) {
357         var r = o.e ? { status: 0, statusText: o.e } : o.c,
358             a = c.arguments;
359
360         if (a) {
361             Y.fire(E_FAILURE, o.id, r, a);
362         }
363         else {
364             Y.fire(E_FAILURE, o.id, r);
365         }
366
367         if (c.on && c.on.failure) {
368             _tE('failure', c).fire(o.id, r);
369         }
370
371         _ioEnd(o, c);
372     }
373
374    /**
375     * @description Resends an XDR transaction, using the Flash tranport,
376     * if the native transport fails.
377     *
378     * @method _resend
379     * @private
380     * @static
381
382     * @param {object} o - Transaction object generated by _create().
383     * @param {string} uri - qualified path to transaction resource.
384     * @param {object} c - configuration object for the transaction.
385     *
386     * @return void
387     */
388     function _resend(o, uri, c, d) {
389         _destroy(o);
390         c.xdr.use = 'flash';
391         // If the original request included serialized form data and
392         // additional data are defined in configuration.data, it must
393         // be reset to prevent data duplication.
394         c.data = c.form && d ? d : null;
395
396         return Y.io(uri, c, o.id);
397     }
398
399    /**
400     * @description Method that concatenates string data for HTTP GET transactions.
401     *
402     * @method _concat
403     * @private
404     * @static
405     * @param {string} s - URI or root data.
406     * @param {string} d - data to be concatenated onto URI.
407     * @return int
408     */
409     function _concat(s, d) {
410         s += ((s.indexOf('?') == -1) ? '?' : '&') + d;
411         return s;
412     }
413
414    /**
415     * @description Method that stores default client headers for all transactions.
416     * If a label is passed with no value argument, the header will be deleted.
417     *
418     * @method _setHeader
419     * @private
420     * @static
421     * @param {string} l - HTTP header
422     * @param {string} v - HTTP header value
423     * @return int
424     */
425     function _setHeader(l, v) {
426         if (v) {
427             _headers[l] = v;
428         }
429         else {
430             delete _headers[l];
431         }
432     }
433
434    /**
435     * @description Method that sets all HTTP headers to be sent in a transaction.
436     *
437     * @method _setHeaders
438     * @private
439     * @static
440     * @param {object} o - XHR instance for the specific transaction.
441     * @param {object} h - HTTP headers for the specific transaction, as defined
442     *                     in the configuration object passed to YUI.io().
443     * @return void
444     */
445     function _setHeaders(o, h) {
446         var p;
447             h = h || {};
448
449         for (p in _headers) {
450             if (_headers.hasOwnProperty(p)) {
451                                 /*
452                 if (h[p]) {
453                     // Configuration headers will supersede preset io headers,
454                     // if headers match.
455                     continue;
456                 }
457                 else {
458                     h[p] = _headers[p];
459                 }
460                                 */
461                                 if (!h[p]) {
462                                         h[p] = _headers[p];
463                                 }
464             }
465         }
466
467         for (p in h) {
468             if (h.hasOwnProperty(p)) {
469                                 if (h[p] !== 'disable') {
470                         o.setRequestHeader(p, h[p]);
471                                 }
472                         }
473         }
474     }
475
476    /**
477     * @description Terminates a transaction due to an explicit abort or
478     * timeout.
479     *
480     * @method _ioCancel
481     * @private
482     * @static
483     * @param {object} o - Transaction object generated by _create().
484     * @param {string} s - Identifies timed out or aborted transaction.
485     *
486     * @return void
487     */
488     function _ioCancel(o, s) {
489         if (o && o.c) {
490             o.e = s;
491             o.c.abort();
492         }
493     }
494
495    /**
496     * @description Starts timeout count if the configuration object
497     * has a defined timeout property.
498     *
499     * @method _startTimeout
500     * @private
501     * @static
502     * @param {object} o - Transaction object generated by _create().
503     * @param {object} t - Timeout in milliseconds.
504     * @return void
505     */
506     function _startTimeout(o, t) {
507         _timeout[o.id] = w.setTimeout(function() { _ioCancel(o, 'timeout'); }, t);
508     }
509
510    /**
511     * @description Clears the timeout interval started by _startTimeout().
512     *
513     * @method _clearTimeout
514     * @private
515     * @static
516     * @param {number} id - Transaction id.
517     * @return void
518     */
519     function _clearTimeout(id) {
520         w.clearTimeout(_timeout[id]);
521         delete _timeout[id];
522     }
523
524    /**
525     * @description Method that determines if a transaction response qualifies
526     * as success or failure, based on the response HTTP status code, and
527     * fires the appropriate success or failure events.
528     *
529     * @method _handleResponse
530     * @private
531     * @static
532     * @param {object} o - Transaction object generated by _create().
533     * @param {object} c - Configuration object passed to io().
534     * @return void
535     */
536     function _handleResponse(o, c) {
537         var status;
538
539         try {
540                         status = (o.c.status && o.c.status !== 0) ? o.c.status : 0;
541         }
542         catch(e) {
543             status = 0;
544         }
545
546         // IE reports HTTP 204 as HTTP 1223.
547         if (status >= 200 && status < 300 || status === 1223) {
548             _ioSuccess(o, c);
549         }
550         else {
551             _ioFailure(o, c);
552         }
553     }
554
555    /**
556     * @description Event handler bound to onreadystatechange.
557     *
558     * @method _readyState
559     * @private
560     * @static
561     * @param {object} o - Transaction object generated by _create().
562     * @param {object} c - Configuration object passed to YUI.io().
563     * @return void
564     */
565     function _readyState(o, c) {
566         if (o.c.readyState === 4) {
567             if (c.timeout) {
568                 _clearTimeout(o.id);
569             }
570
571             w.setTimeout(
572                 function() {
573                     _ioComplete(o, c);
574                     _handleResponse(o, c);
575                 }, 0);
576         }
577     }
578
579    /**
580     * @description Method for requesting a transaction. _io() is implemented as
581     * yui.io().  Each transaction may include a configuration object.  Its
582     * properties are:
583     *
584     * method: HTTP method verb (e.g., GET or POST). If this property is not
585     *         not defined, the default value will be GET.
586     *
587     * data: This is the name-value string that will be sent as the transaction
588     *       data.  If the request is HTTP GET, the data become part of
589     *       querystring. If HTTP POST, the data are sent in the message body.
590     *
591     * xdr: Defines the transport to be used for cross-domain requests.  By
592     *      setting this property, the transaction will use the specified
593     *      transport instead of XMLHttpRequest.
594     *      The properties are:
595     *      {
596     *        use: Specify the transport to be used: 'flash' and 'native'
597     *        dataType: Set the value to 'XML' if that is the expected
598     *                  response content type.
599     *      }
600     *
601     *
602     * form: This is a defined object used to process HTML form as data.  The
603     *       properties are:
604     *       {
605     *         id: Node object or id of HTML form.
606     *         useDisabled: Boolean value to allow disabled HTML form field
607     *                      values to be sent as part of the data.
608     *       }
609     *
610     * on: This is a defined object used to create and handle specific
611     *     events during a transaction lifecycle.  These events will fire in
612     *     addition to the global io events. The events are:
613     *     start - This event is fired when a request is sent to a resource.
614     *     complete - This event fires when the transaction is complete.
615     *     success - This event fires when the response status resolves to
616     *               HTTP 2xx.
617     *     failure - This event fires when the response status resolves to
618     *               HTTP 4xx, 5xx; and, for all transaction exceptions,
619     *               including aborted transactions and transaction timeouts.
620     *     end -  This even is fired at the conclusion of the transaction
621     *            lifecycle, after a success or failure resolution.
622     *
623     *     The properties are:
624     *     {
625     *       start: function(id, arguments){},
626     *       complete: function(id, responseobject, arguments){},
627     *       success: function(id, responseobject, arguments){},
628     *       failure: function(id, responseobject, arguments){},
629     *       end: function(id, arguments){}
630     *     }
631     *     Each property can reference a function or be written as an
632     *     inline function.
633     *
634     * sync: To enable synchronous transactions, set the configuration property
635     *       "sync" to true; the default behavior is false.  Synchronous
636     *       transactions are limited to same-domain requests only.
637     *
638     * context: Object reference for all defined transaction event handlers
639     *          when it is implemented as a method of a base object. Defining
640     *          "context" will set the reference of "this," used in the
641     *          event handlers, to the context value.  In the case where
642     *          different event handlers all have different contexts,
643     *          use Y.bind() to set the execution context, bypassing this
644     *          configuration.
645     *
646     * headers: This is a defined object of client headers, as many as.
647     *          desired for the transaction.  The object pattern is:
648     *          { 'header': 'value' }.
649     *
650     * timeout: This value, defined as milliseconds, is a time threshold for the
651     *          transaction. When this threshold is reached, and the transaction's
652     *          Complete event has not yet fired, the transaction will be aborted.
653     *
654     * arguments: Object, array, string, or number passed to all registered
655     *            event handlers.  This value is available as the second
656     *            argument in the "start" and "abort" event handlers; and, it is
657     *            the third argument in the "complete", "success", and "failure"
658     *            event handlers.
659     *
660     * @method _io
661     * @private
662     * @static
663     * @param {string} uri - qualified path to transaction resource.
664     * @param {object} c - configuration object for the transaction.
665     * @param {number} i - transaction id, if already set.
666     * @return object
667     */
668     function _io(uri, c, i) {
669         var f, o, d, m, r, s, oD, a, j,
670             u = uri;
671             c = Y.Object(c);
672             o = _create(c.xdr || c.form, i);
673             m = c.method ? c.method = c.method.toUpperCase() : c.method = 'GET';
674             s = c.sync;
675             oD = c.data;
676
677         //To serialize an object into a key-value string, add the
678         //QueryString module to the YUI instance's 'use' method.
679         if (Y.Lang.isObject(c.data) && Y.QueryString) {
680             c.data = Y.QueryString.stringify(c.data);
681         }
682
683         if (c.form) {
684             if (c.form.upload) {
685                 // This is a file upload transaction, calling
686                 // upload() in io-upload-iframe.
687                 return Y.io.upload(o, uri, c);
688             }
689             else {
690                 // Serialize HTML form data.
691                 f = Y.io._serialize(c.form, c.data);
692                 if (m === 'POST' || m === 'PUT') {
693                     c.data = f;
694                 }
695                 else if (m === 'GET') {
696                     uri = _concat(uri, f);
697                 }
698             }
699         }
700
701         if (c.data && m === 'GET') {
702             uri = _concat(uri, c.data);
703         }
704
705         if (c.data && m === 'POST') {
706             c.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, c.headers);
707         }
708
709         if (o.t) {
710             return Y.io.xdr(uri, o, c);
711         }
712
713         if (!s) {
714             o.c.onreadystatechange = function() { _readyState(o, c); };
715         }
716
717         try {
718             o.c.open(m, uri, s ? false : true);
719             // Will work only in browsers that implement the
720             // Cross-Origin Resource Sharing draft.
721             if (c.xdr && c.xdr.credentials) {
722                 o.c.withCredentials = true;
723             }
724         }
725         catch(e1) {
726             if (c.xdr) {
727                 // This exception is usually thrown by browsers
728                 // that do not support native XDR transactions.
729                 return _resend(o, u, c, oD);
730             }
731         }
732
733         _setHeaders(o.c, c.headers);
734         _ioStart(o.id, c);
735         try {
736             // Using "null" with HTTP POST will  result in a request
737             // with no Content-Length header defined.
738             o.c.send(c.data || '');
739             if (s) {
740                 d = o.c;
741                 a  = ['status', 'statusText', 'responseText', 'responseXML'];
742                 r = c.arguments ? { id: o.id, arguments: c.arguments } : { id: o.id };
743
744                 for (j = 0; j < 4; j++) {
745                     r[a[j]] = o.c[a[j]];
746                 }
747
748                 r.getAllResponseHeaders = function() { return d.getAllResponseHeaders(); };
749                 r.getResponseHeader = function(h) { return d.getResponseHeader(h); };
750                 _ioComplete(o, c);
751                 _handleResponse(o, c);
752
753                 return r;
754             }
755         }
756         catch(e2) {
757             if (c.xdr) {
758                 // This exception is usually thrown by browsers
759                 // that do not support native XDR transactions.
760                 return _resend(o, u, c, oD);
761             }
762         }
763
764         // If config.timeout is defined, and the request is standard XHR,
765         // initialize timeout polling.
766         if (c.timeout) {
767             _startTimeout(o, c.timeout);
768         }
769
770         return {
771             id: o.id,
772             abort: function() {
773                 return o.c ? _ioCancel(o, 'abort') : false;
774             },
775             isInProgress: function() {
776                 return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false;
777             }
778         };
779     }
780
781     _io.start = _ioStart;
782     _io.complete = _ioComplete;
783     _io.success = _ioSuccess;
784     _io.failure = _ioFailure;
785     _io.end = _ioEnd;
786     _io._id = _id;
787     _io._timeout = _timeout;
788
789     //--------------------------------------
790     //  Begin public interface definition
791     //--------------------------------------
792    /**
793     * @description Method that stores default client headers for all transactions.
794     * If a label is passed with no value argument, the header will be deleted.
795     * This is the interface for _setHeader().
796     *
797     * @method header
798     * @public
799     * @static
800     * @param {string} l - HTTP header
801     * @param {string} v - HTTP header value
802     * @return int
803     */
804     _io.header = _setHeader;
805
806    /**
807     * @description Method for requesting a transaction. This
808     * is the interface for _io().
809     *
810     * @method io
811     * @public
812     * @static
813     * @param {string} uri - qualified path to transaction resource.
814     * @param {object} c - configuration object for the transaction.
815     * @return object
816     */
817     Y.io = _io;
818     Y.io.http = _io;
819
820
821
822 }, '3.3.0' ,{requires:['event-custom-base', 'querystring-stringify-simple']});