]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/history/history-base.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / history / history-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('history-base', function(Y) {
9
10 /**
11  * Provides browser history management functionality using a simple
12  * add/replace/get paradigm. This can be used to ensure that the browser's back
13  * and forward buttons work as the user expects and to provide bookmarkable URLs
14  * that return the user to the current application state, even in an Ajax
15  * application that doesn't perform full-page refreshes.
16  *
17  * @module history
18  * @since 3.2.0
19  */
20
21 /**
22  * Provides global state management backed by an object, but with no browser
23  * history integration. For actual browser history integration and back/forward
24  * support, use the history-html5 or history-hash modules.
25  *
26  * @module history
27  * @submodule history-base
28  * @class HistoryBase
29  * @uses EventTarget
30  * @constructor
31  * @param {Object} config (optional) configuration object, which may contain
32  *   zero or more of the following properties:
33  *
34  * <dl>
35  *   <dt>initialState (Object)</dt>
36  *   <dd>
37  *     Initial state to set, as an object hash of key/value pairs. This will be
38  *     merged into the current global state.
39  *   </dd>
40  * </dl>
41  */
42
43 var Lang      = Y.Lang,
44     Obj       = Y.Object,
45     GlobalEnv = YUI.namespace('Env.History'),
46     YArray    = Y.Array,
47
48     doc       = Y.config.doc,
49     docMode   = doc.documentMode,
50     win       = Y.config.win,
51
52     DEFAULT_OPTIONS = {merge: true},
53     EVT_CHANGE      = 'change',
54     SRC_ADD         = 'add',
55     SRC_REPLACE     = 'replace';
56
57 function HistoryBase() {
58     this._init.apply(this, arguments);
59 }
60
61 Y.augment(HistoryBase, Y.EventTarget, null, null, {
62     emitFacade : true,
63     prefix     : 'history',
64     preventable: false,
65     queueable  : true
66 });
67
68 if (!GlobalEnv._state) {
69     GlobalEnv._state = {};
70 }
71
72 // -- Private Methods ----------------------------------------------------------
73
74 /**
75  * Returns <code>true</code> if <i>value</i> is a simple object and not a
76  * function or an array.
77  *
78  * @method _isSimpleObject
79  * @param {mixed} value
80  * @return {Boolean}
81  * @private
82  */
83 function _isSimpleObject(value) {
84     return Lang.type(value) === 'object';
85 }
86
87 // -- Public Static Properties -------------------------------------------------
88
89 /**
90  * Name of this component.
91  *
92  * @property NAME
93  * @type String
94  * @static
95  */
96 HistoryBase.NAME = 'historyBase';
97
98 /**
99  * Constant used to identify state changes originating from the
100  * <code>add()</code> method.
101  *
102  * @property SRC_ADD
103  * @type String
104  * @static
105  * @final
106  */
107 HistoryBase.SRC_ADD = SRC_ADD;
108
109 /**
110  * Constant used to identify state changes originating from the
111  * <code>replace()</code> method.
112  *
113  * @property SRC_REPLACE
114  * @type String
115  * @static
116  * @final
117  */
118 HistoryBase.SRC_REPLACE = SRC_REPLACE;
119
120 /**
121  * Whether or not this browser supports the HTML5 History API.
122  *
123  * @property html5
124  * @type Boolean
125  * @static
126  */
127
128 // All HTML5-capable browsers except Gecko 2+ (Firefox 4+) correctly return
129 // true for 'onpopstate' in win. In order to support Gecko 2, we fall back to a
130 // UA sniff for now. (current as of Firefox 4.0b2)
131 HistoryBase.html5 = !!(win.history && win.history.pushState &&
132         win.history.replaceState && ('onpopstate' in win || Y.UA.gecko >= 2));
133
134 /**
135  * Whether or not this browser supports the <code>window.onhashchange</code>
136  * event natively. Note that even if this is <code>true</code>, you may
137  * still want to use HistoryHash's synthetic <code>hashchange</code> event
138  * since it normalizes implementation differences and fixes spec violations
139  * across various browsers.
140  *
141  * @property nativeHashChange
142  * @type Boolean
143  * @static
144  */
145
146 // Most browsers that support hashchange expose it on the window. Opera 10.6+
147 // exposes it on the document (but you can still attach to it on the window).
148 //
149 // IE8 supports the hashchange event, but only in IE8 Standards
150 // Mode. However, IE8 in IE7 compatibility mode still defines the
151 // event but never fires it, so we can't just detect the event. We also can't
152 // just UA sniff for IE8, since other browsers support this event as well.
153 HistoryBase.nativeHashChange = ('onhashchange' in win || 'onhashchange' in doc) &&
154         (!docMode || docMode > 7);
155
156 Y.mix(HistoryBase.prototype, {
157     // -- Initialization -------------------------------------------------------
158
159     /**
160      * Initializes this HistoryBase instance. This method is called by the
161      * constructor.
162      *
163      * @method _init
164      * @param {Object} config configuration object
165      * @protected
166      */
167     _init: function (config) {
168         var initialState;
169
170         /**
171          * Configuration object provided by the user on instantiation, or an
172          * empty object if one wasn't provided.
173          *
174          * @property _config
175          * @type Object
176          * @default {}
177          * @protected
178          */
179         config = this._config = config || {};
180
181         /**
182          * Resolved initial state: a merge of the user-supplied initial state
183          * (if any) and any initial state provided by a subclass. This may
184          * differ from <code>_config.initialState</code>. If neither the config
185          * nor a subclass supplies an initial state, this property will be
186          * <code>null</code>.
187          *
188          * @property _initialState
189          * @type Object|null
190          * @default {}
191          * @protected
192          */
193         initialState = this._initialState = this._initialState ||
194                 config.initialState || null;
195
196         /**
197          * Fired when the state changes. To be notified of all state changes
198          * regardless of the History or YUI instance that generated them,
199          * subscribe to this event on <code>Y.Global</code>. If you would rather
200          * be notified only about changes generated by this specific History
201          * instance, subscribe to this event on the instance.
202          *
203          * @event history:change
204          * @param {EventFacade} e Event facade with the following additional
205          *   properties:
206          *
207          * <dl>
208          *   <dt>changed (Object)</dt>
209          *   <dd>
210          *     Object hash of state items that have been added or changed. The
211          *     key is the item key, and the value is an object containing
212          *     <code>newVal</code> and <code>prevVal</code> properties
213          *     representing the values of the item both before and after the
214          *     change. If the item was newly added, <code>prevVal</code> will be
215          *     <code>undefined</code>.
216          *   </dd>
217          *
218          *   <dt>newVal (Object)</dt>
219          *   <dd>
220          *     Object hash of key/value pairs of all state items after the
221          *     change.
222          *   </dd>
223          *
224          *   <dt>prevVal (Object)</dt>
225          *   <dd>
226          *     Object hash of key/value pairs of all state items before the
227          *     change.
228          *   </dd>
229          *
230          *   <dt>removed (Object)</dt>
231          *   <dd>
232          *     Object hash of key/value pairs of state items that have been
233          *     removed. Values are the old values prior to removal.
234          *   </dd>
235          *
236          *   <dt>src (String)</dt>
237          *   <dd>
238          *     The source of the event. This can be used to selectively ignore
239          *     events generated by certain sources.
240          *   </dd>
241          * </dl>
242          */
243         this.publish(EVT_CHANGE, {
244             broadcast: 2,
245             defaultFn: this._defChangeFn
246         });
247
248         // If initialState was provided, merge it into the current state.
249         if (initialState) {
250             this.add(initialState);
251         }
252     },
253
254     // -- Public Methods -------------------------------------------------------
255
256     /**
257      * Adds a state entry with new values for the specified keys. By default,
258      * the new state will be merged into the existing state, and new values will
259      * override existing values. Specifying a <code>null</code> or
260      * <code>undefined</code> value will cause that key to be removed from the
261      * new state entry.
262      *
263      * @method add
264      * @param {Object} state Object hash of key/value pairs.
265      * @param {Object} options (optional) Zero or more of the following options:
266      *   <dl>
267      *     <dt>merge (Boolean)</dt>
268      *     <dd>
269      *       <p>
270      *       If <code>true</code> (the default), the new state will be merged
271      *       into the existing state. New values will override existing values,
272      *       and <code>null</code> or <code>undefined</code> values will be
273      *       removed from the state.
274      *       </p>
275      *
276      *       <p>
277      *       If <code>false</code>, the existing state will be discarded as a
278      *       whole and the new state will take its place.
279      *       </p>
280      *     </dd>
281      *   </dl>
282      * @chainable
283      */
284     add: function () {
285         var args = YArray(arguments, 0, true);
286         args.unshift(SRC_ADD);
287         return this._change.apply(this, args);
288     },
289
290     /**
291      * Adds a state entry with a new value for a single key. By default, the new
292      * value will be merged into the existing state values, and will override an
293      * existing value with the same key if there is one. Specifying a
294      * <code>null</code> or <code>undefined</code> value will cause the key to
295      * be removed from the new state entry.
296      *
297      * @method addValue
298      * @param {String} key State parameter key.
299      * @param {String} value New value.
300      * @param {Object} options (optional) Zero or more options. See
301      *   <code>add()</code> for a list of supported options.
302      * @chainable
303      */
304     addValue: function (key, value, options) {
305         var state = {};
306         state[key] = value;
307         return this._change(SRC_ADD, state, options);
308     },
309
310     /**
311      * Returns the current value of the state parameter specified by <i>key</i>,
312      * or an object hash of key/value pairs for all current state parameters if
313      * no key is specified.
314      *
315      * @method get
316      * @param {String} key (optional) State parameter key.
317      * @return {Object|String} Value of the specified state parameter, or an
318      *   object hash of key/value pairs for all current state parameters.
319      */
320     get: function (key) {
321         var state    = GlobalEnv._state,
322             isObject = _isSimpleObject(state);
323
324         if (key) {
325             return isObject && Obj.owns(state, key) ? state[key] : undefined;
326         } else {
327             return isObject ? Y.mix({}, state, true) : state; // mix provides a fast shallow clone.
328         }
329     },
330
331     /**
332      * Same as <code>add()</code> except that a new browser history entry will
333      * not be created. Instead, the current history entry will be replaced with
334      * the new state.
335      *
336      * @method replace
337      * @param {Object} state Object hash of key/value pairs.
338      * @param {Object} options (optional) Zero or more options. See
339      *   <code>add()</code> for a list of supported options.
340      * @chainable
341      */
342     replace: function () {
343         var args = YArray(arguments, 0, true);
344         args.unshift(SRC_REPLACE);
345         return this._change.apply(this, args);
346     },
347
348     /**
349      * Same as <code>addValue()</code> except that a new browser history entry
350      * will not be created. Instead, the current history entry will be replaced
351      * with the new state.
352      *
353      * @method replaceValue
354      * @param {String} key State parameter key.
355      * @param {String} value New value.
356      * @param {Object} options (optional) Zero or more options. See
357      *   <code>add()</code> for a list of supported options.
358      * @chainable
359      */
360     replaceValue: function (key, value, options) {
361         var state = {};
362         state[key] = value;
363         return this._change(SRC_REPLACE, state, options);
364     },
365
366     // -- Protected Methods ----------------------------------------------------
367
368     /**
369      * Changes the state. This method provides a common implementation shared by
370      * the public methods for changing state.
371      *
372      * @method _change
373      * @param {String} src Source of the change, for inclusion in event facades
374      *   to facilitate filtering.
375      * @param {Object} state Object hash of key/value pairs.
376      * @param {Object} options (optional) Zero or more options. See
377      *   <code>add()</code> for a list of supported options.
378      * @protected
379      * @chainable
380      */
381     _change: function (src, state, options) {
382         options = options ? Y.merge(DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;
383
384         if (options.merge && _isSimpleObject(state) &&
385                 _isSimpleObject(GlobalEnv._state)) {
386             state = Y.merge(GlobalEnv._state, state);
387         }
388
389         this._resolveChanges(src, state, options);
390         return this;
391     },
392
393     /**
394      * Called by _resolveChanges() when the state has changed. This method takes
395      * care of actually firing the necessary events.
396      *
397      * @method _fireEvents
398      * @param {String} src Source of the changes, for inclusion in event facades
399      *   to facilitate filtering.
400      * @param {Object} changes Resolved changes.
401      * @param {Object} options Zero or more options. See <code>add()</code> for
402      *   a list of supported options.
403      * @protected
404      */
405     _fireEvents: function (src, changes, options) {
406         // Fire the global change event.
407         this.fire(EVT_CHANGE, {
408             _options: options,
409             changed : changes.changed,
410             newVal  : changes.newState,
411             prevVal : changes.prevState,
412             removed : changes.removed,
413             src     : src
414         });
415
416         // Fire change/remove events for individual items.
417         Obj.each(changes.changed, function (value, key) {
418             this._fireChangeEvent(src, key, value);
419         }, this);
420
421         Obj.each(changes.removed, function (value, key) {
422             this._fireRemoveEvent(src, key, value);
423         }, this);
424     },
425
426     /**
427      * Fires a dynamic "[key]Change" event.
428      *
429      * @method _fireChangeEvent
430      * @param {String} src source of the change, for inclusion in event facades
431      *   to facilitate filtering
432      * @param {String} key key of the item that was changed
433      * @param {Object} value object hash containing <i>newVal</i> and
434      *   <i>prevVal</i> properties for the changed item
435      * @protected
436      */
437     _fireChangeEvent: function (src, key, value) {
438         /**
439          * <p>
440          * Dynamic event fired when an individual history item is added or
441          * changed. The name of this event depends on the name of the key that
442          * changed. To listen to change events for a key named "foo", subscribe
443          * to the <code>fooChange</code> event; for a key named "bar", subscribe
444          * to <code>barChange</code>, etc.
445          * </p>
446          *
447          * <p>
448          * Key-specific events are only fired for instance-level changes; that
449          * is, changes that were made via the same History instance on which the
450          * event is subscribed. To be notified of changes made by other History
451          * instances, subscribe to the global <code>history:change</code> event.
452          * </p>
453          *
454          * @event [key]Change
455          * @param {EventFacade} e Event facade with the following additional
456          *   properties:
457          *
458          * <dl>
459          *   <dt>newVal (mixed)</dt>
460          *   <dd>
461          *     The new value of the item after the change.
462          *   </dd>
463          *
464          *   <dt>prevVal (mixed)</dt>
465          *   <dd>
466          *     The previous value of the item before the change, or
467          *     <code>undefined</code> if the item was just added and has no
468          *     previous value.
469          *   </dd>
470          *
471          *   <dt>src (String)</dt>
472          *   <dd>
473          *     The source of the event. This can be used to selectively ignore
474          *     events generated by certain sources.
475          *   </dd>
476          * </dl>
477          */
478         this.fire(key + 'Change', {
479             newVal : value.newVal,
480             prevVal: value.prevVal,
481             src    : src
482         });
483     },
484
485     /**
486      * Fires a dynamic "[key]Remove" event.
487      *
488      * @method _fireRemoveEvent
489      * @param {String} src source of the change, for inclusion in event facades
490      *   to facilitate filtering
491      * @param {String} key key of the item that was removed
492      * @param {mixed} value value of the item prior to its removal
493      * @protected
494      */
495     _fireRemoveEvent: function (src, key, value) {
496         /**
497          * <p>
498          * Dynamic event fired when an individual history item is removed. The
499          * name of this event depends on the name of the key that was removed.
500          * To listen to remove events for a key named "foo", subscribe to the
501          * <code>fooRemove</code> event; for a key named "bar", subscribe to
502          * <code>barRemove</code>, etc.
503          * </p>
504          *
505          * <p>
506          * Key-specific events are only fired for instance-level changes; that
507          * is, changes that were made via the same History instance on which the
508          * event is subscribed. To be notified of changes made by other History
509          * instances, subscribe to the global <code>history:change</code> event.
510          * </p>
511          *
512          * @event [key]Remove
513          * @param {EventFacade} e Event facade with the following additional
514          *   properties:
515          *
516          * <dl>
517          *   <dt>prevVal (mixed)</dt>
518          *   <dd>
519          *     The value of the item before it was removed.
520          *   </dd>
521          *
522          *   <dt>src (String)</dt>
523          *   <dd>
524          *     The source of the event. This can be used to selectively ignore
525          *     events generated by certain sources.
526          *   </dd>
527          * </dl>
528          */
529         this.fire(key + 'Remove', {
530             prevVal: value,
531             src    : src
532         });
533     },
534
535     /**
536      * Resolves the changes (if any) between <i>newState</i> and the current
537      * state and fires appropriate events if things have changed.
538      *
539      * @method _resolveChanges
540      * @param {String} src source of the changes, for inclusion in event facades
541      *   to facilitate filtering
542      * @param {Object} newState object hash of key/value pairs representing the
543      *   new state
544      * @param {Object} options Zero or more options. See <code>add()</code> for
545      *   a list of supported options.
546      * @protected
547      */
548     _resolveChanges: function (src, newState, options) {
549         var changed   = {},
550             isChanged,
551             prevState = GlobalEnv._state,
552             removed   = {};
553
554         if (!newState) {
555             newState = {};
556         }
557
558         if (!options) {
559             options = {};
560         }
561
562         if (_isSimpleObject(newState) && _isSimpleObject(prevState)) {
563             // Figure out what was added or changed.
564             Obj.each(newState, function (newVal, key) {
565                 var prevVal = prevState[key];
566
567                 if (newVal !== prevVal) {
568                     changed[key] = {
569                         newVal : newVal,
570                         prevVal: prevVal
571                     };
572
573                     isChanged = true;
574                 }
575             }, this);
576
577             // Figure out what was removed.
578             Obj.each(prevState, function (prevVal, key) {
579                 if (!Obj.owns(newState, key) || newState[key] === null) {
580                     delete newState[key];
581                     removed[key] = prevVal;
582                     isChanged = true;
583                 }
584             }, this);
585         } else {
586             isChanged = newState !== prevState;
587         }
588
589         if (isChanged) {
590             this._fireEvents(src, {
591                 changed  : changed,
592                 newState : newState,
593                 prevState: prevState,
594                 removed  : removed
595             }, options);
596         }
597     },
598
599     /**
600      * Stores the specified state. Don't call this method directly; go through
601      * _resolveChanges() to ensure that changes are resolved and all events are
602      * fired properly.
603      *
604      * @method _storeState
605      * @param {String} src source of the changes
606      * @param {Object} newState new state to store
607      * @param {Object} options Zero or more options. See <code>add()</code> for
608      *   a list of supported options.
609      * @protected
610      */
611     _storeState: function (src, newState) {
612         // Note: the src and options params aren't used here, but they are used
613         // by subclasses.
614         GlobalEnv._state = newState || {};
615     },
616
617     // -- Protected Event Handlers ---------------------------------------------
618
619     /**
620      * Default <code>history:change</code> event handler.
621      *
622      * @method _defChangeFn
623      * @param {EventFacade} e state change event facade
624      * @protected
625      */
626     _defChangeFn: function (e) {
627         this._storeState(e.src, e.newVal, e._options);
628     }
629 }, true);
630
631 Y.HistoryBase = HistoryBase;
632
633
634 }, '3.3.0' ,{requires:['event-custom-complex']});