app-base.js revision e003df9c0cca758e53e27d267b48075e33502427
168N/AYUI.add('app-base', function(Y) {
769N/A
769N/A/**
168N/AThe App Framework provides simple MVC-like building blocks (models, model lists,
168N/Aviews, and URL-based routing) for writing single-page JavaScript applications.
168N/A
168N/A@main app
168N/A@module app
168N/A@since 3.4.0
168N/A**/
168N/A
168N/A/**
168N/AProvides a top-level application component which manages navigation and views.
168N/A
168N/A@submodule app-base
292N/A@since 3.5.0
168N/A**/
168N/A
168N/A// TODO: Better handling of lifecycle for registered views:
168N/A//
168N/A// * Seems like any view created via `createView` should listen for the view's
168N/A// `destroy` event and use that to remove it from the `_viewsInfoMap`. I
168N/A// should look at what ModelList does for Models as a reference.
168N/A//
168N/A// * Should we have a companion `destroyView()` method? Maybe this wouldn't be
168N/A// needed if we have a `getView(name, create)` method, and already doing the
168N/A// above? We could do `app.getView('foo').destroy()` and it would be removed
168N/A// from the `_viewsInfoMap` as well.
168N/A
168N/Avar Lang = Y.Lang,
168N/A PjaxBase = Y.PjaxBase,
168N/A Router = Y.Router,
670N/A View = Y.View,
769N/A YObject = Y.Object,
168N/A
670N/A win = Y.config.win,
526N/A
526N/A App;
526N/A
526N/A/**
670N/AProvides a top-level application component which manages navigation and views.
670N/A
526N/AThis gives you a foundation and structure on which to build your application; it
670N/Acombines robust URL navigation with powerful routing and flexible view
526N/Amanagement.
526N/A
526N/A@class App.Base
168N/A@param {Object} [config] The following are configuration properties that can be
168N/A specified _in addition_ to default attribute values and the non-attribute
670N/A properties provided by `Y.Base`:
670N/A @param {Object} [config.views] Hash of view-name to metadata used to
670N/A declaratively describe an application's views and their relationship with
670N/A the app and other views. The views specified here will override any defaults
168N/A provided by the `views` object on the `prototype`.
168N/A@constructor
168N/A@extends Base
168N/A@uses View
613N/A@uses Router
613N/A@uses PjaxBase
613N/A@since 3.5.0
168N/A**/
613N/AApp = Y.Base.create('app', Y.Base, [View, Router, PjaxBase], {
613N/A // -- Public Properties ----------------------------------------------------
613N/A
168N/A /**
168N/A Hash of view-name to metadata used to declaratively describe an
168N/A application's views and their relationship with the app and its other views.
168N/A
168N/A The view metadata is composed of Objects keyed to a view-name that can have
168N/A any or all of the following properties:
670N/A
670N/A * `type`: Function or a string representing the view constructor to use to
670N/A create view instances. If a string is used, the constructor function is
670N/A assumed to be on the `Y` object; e.g. `"SomeView"` -> `Y.SomeView`.
670N/A
670N/A * `preserve`: Boolean for whether the view instance should be retained. By
670N/A default, the view instance will be destroyed when it is no longer the
670N/A `activeView`. If `true` the view instance will simply be `removed()`
670N/A from the DOM when it is no longer active. This is useful when the view
670N/A is frequently used and may be expensive to re-create.
670N/A
670N/A * `parent`: String to another named view in this hash that represents the
670N/A parent view within the application's view hierarchy; e.g. a `"photo"`
670N/A view could have `"album"` has its `parent` view. This parent/child
670N/A relationship is a useful cue for things like transitions.
670N/A
670N/A * `instance`: Used internally to manage the current instance of this named
670N/A view. This can be used if your view instance is created up-front, or if
670N/A you would rather manage the View lifecycle, but you probably should just
670N/A let this be handled for you.
670N/A
670N/A If `views` are specified at instantiation time, the metadata in the `views`
670N/A Object here will be used as defaults when creating the instance's `views`.
670N/A
670N/A Every `Y.App` instance gets its own copy of a `views` object so this Object
670N/A on the prototype will not be polluted.
670N/A
670N/A @example
670N/A // Imagine that `Y.UsersView` and `Y.UserView` have been defined.
670N/A var app = new Y.App({
670N/A views: {
670N/A users: {
670N/A type : Y.UsersView,
670N/A preserve: true
670N/A },
670N/A
670N/A user: {
670N/A type : Y.UserView,
670N/A parent: 'users'
670N/A }
168N/A }
670N/A });
670N/A
670N/A @property views
670N/A @type Object
670N/A @default `{}`
670N/A **/
670N/A views: {},
670N/A
670N/A // -- Protected Properties -------------------------------------------------
670N/A
670N/A /**
670N/A Map of view instance id (via `Y.stamp()`) to view-info object in `views`.
168N/A
168N/A This mapping is used to tie a specific view instance back to its metadata by
168N/A adding a reference to the the related view info on the `views` object.
168N/A
168N/A @property _viewInfoMap
670N/A @type Object
670N/A @default {}
670N/A @protected
670N/A **/
295N/A
295N/A // -- Lifecycle Methods ----------------------------------------------------
295N/A initializer: function (config) {
670N/A config || (config = {});
295N/A
295N/A var views = {};
295N/A
295N/A // Merges-in specified view metadata into local `views` object.
295N/A function mergeViewConfig(view, name) {
295N/A views[name] = Y.merge(views[name], view);
295N/A }
295N/A
295N/A // First, each view in the `views` prototype object gets its metadata
295N/A // merged-in, providing the defaults.
670N/A YObject.each(this.views, mergeViewConfig);
670N/A
670N/A // Then, each view in the specified `config.views` object gets its
295N/A // metadata merged-in.
295N/A YObject.each(config.views, mergeViewConfig);
295N/A
295N/A // The resulting hodgepodge of metadata is then stored as the instance's
295N/A // `views` object, and no one's objects were harmed in the making.
769N/A this.views = views;
769N/A
295N/A this._viewInfoMap = {};
769N/A
670N/A this.after('activeViewChange', this._afterActiveViewChange);
670N/A
670N/A // PjaxBase will bind click events when `html5` is `true`, so this just
670N/A // forces the binding when `serverRouting` and `html5` are both falsy.
670N/A if (!this.get('serverRouting')) {
670N/A this._pjaxBindUI();
670N/A }
670N/A },
670N/A
670N/A // TODO: `destructor` to destory the `activeView`?
295N/A
295N/A // -- Public Methods -------------------------------------------------------
295N/A
295N/A /**
295N/A Creates and returns this apps's container node from the specified selector
295N/A string, DOM element, or existing `Y.Node` instance. This method is called
295N/A internally when the app is initialized.
295N/A
295N/A This node is also stamped with the CSS class specified by
295N/A `Y.App.Base.CSS_CLASS`.
295N/A
295N/A By default, the created node is _not_ added to the DOM automatically.
295N/A
670N/A @method create
295N/A @param {String|Node|HTMLElement} container Selector string, `Y.Node`
295N/A instance, or DOM element to use as the container node.
295N/A @return {Node} Node instance of the created container node.
295N/A **/
295N/A create: function () {
295N/A var container = View.prototype.create.apply(this, arguments);
670N/A return container && container.addClass(App.CSS_CLASS);
670N/A },
670N/A
670N/A /**
295N/A Creates and returns a new view instance using the provided `name` to look up
295N/A the view info metadata defined in the `views` object. The passed-in `config`
295N/A object is passed to the view constructor function.
295N/A
295N/A This function also maps a view instance back to its view info metadata.
670N/A
670N/A @method createView
670N/A @param {String} name The name of a view defined on the `views` object.
670N/A @param {Object} [config] The configuration object passed to the view
295N/A constructor function when creating the new view instance.
295N/A @return {View} The new view instance.
295N/A **/
295N/A createView: function (name, config) {
295N/A var viewInfo = this.getViewInfo(name),
295N/A type = (viewInfo && viewInfo.type) || View,
295N/A ViewConstructor, view;
295N/A
295N/A // Looks for a namespaced constructor function on `Y`.
402N/A ViewConstructor = Lang.isString(type) ?
295N/A YObject.getValue(Y, type.split('.')) : type;
402N/A
295N/A // Create the view instance and map it with its metadata.
670N/A view = new ViewConstructor(config);
670N/A this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
670N/A
670N/A return view;
670N/A },
670N/A
670N/A /**
670N/A Creates and returns this app's view-container node from the specified
670N/A selector string, DOM element, or existing `Y.Node` instance. This method is
670N/A called internally when the app is initialized.
670N/A
670N/A This node is also stamped with the CSS class specified by
670N/A `Y.App.Base.VIEWS_CSS_CLASS`.
670N/A
670N/A By default, the created node will appended to the `container` node by the
670N/A `render()` method.
670N/A
295N/A @method createViewContainer
295N/A @param {String|Node|HTMLElement} viewContainer Selector string, `Y.Node`
295N/A instance, or DOM element to use as the view-container node.
295N/A @return {Node} Node instance of the created view-container node.
670N/A **/
295N/A createViewContainer: function (viewContainer) {
295N/A viewContainer = Y.one(viewContainer);
295N/A return viewContainer && viewContainer.addClass(App.VIEWS_CSS_CLASS);
670N/A },
670N/A
670N/A /**
670N/A Returns the metadata associated with a view instance or view name defined on
670N/A the `views` object.
670N/A
670N/A @method getViewInfo
670N/A @param {View|String} view View instance, or name of a view defined on the
670N/A `views` object.
670N/A @return {Object} The metadata for the view, or `undefined` if the view is
670N/A not registered.
670N/A **/
670N/A getViewInfo: function (view) {
670N/A if (view instanceof View) {
670N/A return this._viewInfoMap[Y.stamp(view, true)];
670N/A }
670N/A
670N/A return this.views[view];
670N/A },
670N/A
670N/A /**
670N/A Navigates to the specified URL if there is a route handler that matches. In
670N/A browsers capable of using HTML5 history or when `serverRouting` is falsy,
670N/A the navigation will be enhanced by firing the `navigate` event and having
670N/A the app handle the "request". When `serverRouting` is `true`, non-HTML5
670N/A browsers will navigate to the new URL via a full page reload.
670N/A
670N/A When there is a route handler for the specified URL and it is being
670N/A navigated to, this method will return `true`, otherwise it will return
670N/A `false`.
670N/A
670N/A **Note:** The specified URL _must_ be of the same origin as the current URL,
670N/A otherwise an error will be logged and navigation will not occur. This is
670N/A intended as both a security constraint and a purposely imposed limitation as
670N/A it does not make sense to tell the app to navigate to a URL on a
670N/A different scheme, host, or port.
670N/A
670N/A @method navigate
670N/A @param {String} url The fully-resolved URL that the app should dispatch to
670N/A its route handlers to fulfill the enhanced navigation "request", or use to
670N/A update `window.location` in non-HTML5 history capable browsers when
670N/A `serverRouting` is `true`.
670N/A @param {Object} [options] Additional options to configure the navigation.
670N/A These are mixed into the `navigate` event facade.
670N/A @param {Boolean} [options.replace] Whether or not the current history
670N/A entry will be replaced, or a new entry will be created. Will default
670N/A to `true` if the specified `url` is the same as the current URL.
670N/A @param {Boolean} [options.force] Whether the enhanced navigation
670N/A should occur even in browsers without HTML5 history. Will default to
670N/A `true` when `serverRouting` is falsy.
670N/A @see PjaxBase.navigate()
670N/A **/
670N/A
670N/A /**
670N/A Renders this application by appending the `viewContainer` node to the
670N/A `container` node if it isn't already a child of the container, and the
670N/A `activeView` will be appended the view container, if it isn't already.
670N/A
670N/A You should call this method at least once, usually after the initialization
670N/A of your app instance so the proper DOM structure is setup and optionally
670N/A append the container to the DOM if it's not there already.
670N/A
670N/A You may override this method to customize the app's rendering, but you
670N/A should expect that the `viewContainer`'s contents will be modified by the
670N/A app for the purpose of rendering the `activeView` when it changes.
670N/A
670N/A @method render
670N/A @chainable
168N/A **/
168N/A render: function () {
168N/A var container = this.get('container'),
168N/A viewContainer = this.get('viewContainer'),
168N/A activeView = this.get('activeView'),
168N/A activeViewContainer = activeView && activeView.get('container'),
168N/A areSame = container.compareTo(viewContainer);
168N/A
670N/A if (activeView && !viewContainer.contains(activeViewContainer)) {
670N/A viewContainer.appendChild(activeViewContainer);
670N/A }
670N/A
670N/A if (!container.contains(viewContainer) && !areSame) {
670N/A container.appendChild(viewContainer);
670N/A }
670N/A
670N/A return this;
670N/A },
168N/A
168N/A /**
168N/A Sets which view is active/visible for the application. This will set the
168N/A app's `activeView` attribute to the specified `view`.
168N/A
168N/A When a string-name is provided for a view which has been registered on this
168N/A app's `views` object, the referenced metadata will be used and the
168N/A `activeView` will be set to either a preserved view instance, or a new
670N/A instance of the registered view will be created using the specified `config`
670N/A object passed-into this method.
670N/A
670N/A A callback function can be specified as either the third or fourth argument,
670N/A and this function will be called after the new `view` becomes the
670N/A `activeView`, is rendered to the `viewContainer`, and is ready to use.
670N/A
670N/A @example
168N/A var app = new Y.App({
168N/A views: {
168N/A users: {
168N/A // Imagine that `Y.UsersView` has been defined.
670N/A type: Y.UsersView
670N/A }
168N/A }
168N/A });
168N/A
168N/A app.route('/users/', function () {
670N/A this.showView('users');
670N/A });
670N/A
670N/A app.render();
670N/A app.navigate('/uses/'); // => Creates a new `Y.UsersView` and shows it.
670N/A
670N/A @method showView
670N/A @param {String|View} view The name of a view defined in the `views` object,
670N/A or a view instance.
168N/A @param {Object} [config] Optional configuration to use when creating a new
168N/A view instance.
168N/A @param {Object} [options] Optional object containing any of the following
168N/A properties:
168N/A @param {Boolean} [options.prepend] Whether the new view should be
168N/A prepended instead of appended to the `viewContainer`.
168N/A @param {Function} [callback] Optional callback Function to call after the
168N/A new `activeView` is ready to use, the function will be passed:
168N/A @param {View} callback.view A reference to the new `activeView`.
769N/A @chainable
670N/A **/
769N/A showView: function (view, config, options, callback) {
670N/A var viewInfo;
670N/A
770N/A if (Lang.isString(view)) {
670N/A viewInfo = this.getViewInfo(view);
769N/A
769N/A // Use the preserved view instance, or create a new view.
769N/A // TODO: Maybe we can remove the strict check for `preserve` and
670N/A // assume we'll use a View instance if it is there, and just check
670N/A // `preserve` when detaching?
168N/A if (viewInfo && viewInfo.preserve && viewInfo.instance) {
168N/A view = viewInfo.instance;
168N/A // Make sure there's a mapping back to the view metadata.
769N/A this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
168N/A } else {
769N/A view = this.createView(view, config);
168N/A view.render();
168N/A }
168N/A }
168N/A
670N/A // TODO: Add `options.update` to update to view with the `config`, if
670N/A // needed. This could also call `setAttrs()` when the specified `view`
670N/A // already a View instance. Is this be too much overloading of the API?
670N/A
670N/A // TODO: Add `options.render` to provide a way to control whether a view
670N/A // is rendered or not; by default, `render()` will only be called if
670N/A // this method created the View.
670N/A
670N/A options || (options = {});
670N/A
670N/A if (callback) {
670N/A options.callback = callback;
670N/A } else if (Lang.isFunction(options)) {
670N/A options = {callback: options};
670N/A }
168N/A
168N/A // TODO: Should the `callback` _always_ be called, even when the
168N/A // `activeView` does not change?
168N/A
168N/A return this._set('activeView', view, {options: options});
168N/A },
168N/A
168N/A // -- Protected Methods ----------------------------------------------------
168N/A
168N/A /**
168N/A Helper method to attach the view instance to the application by making the
168N/A app a bubble target of the view, append the view to the `viewContainer`, and
613N/A assign it to the `instance` property of the associated view info metadata.
613N/A
670N/A @method _attachView
670N/A @param {View} view View to attach.
613N/A @param {Boolean} prepend Whether the view should be prepended instead of
168N/A appended to the `viewContainer`.
168N/A @protected
168N/A **/
670N/A _attachView: function (view, prepend) {
670N/A if (!view) {
670N/A return;
670N/A }
670N/A
670N/A var viewInfo = this.getViewInfo(view),
168N/A viewContainer = this.get('viewContainer');
168N/A
168N/A view.addTarget(this);
168N/A viewInfo && (viewInfo.instance = view);
168N/A
168N/A // TODO: Attach events here for persevered Views?
168N/A // See related TODO in `_detachView`.
526N/A
168N/A // Insert view into the DOM.
168N/A viewContainer[prepend ? 'prepend' : 'append'](view.get('container'));
168N/A },
168N/A
168N/A /**
168N/A Overrides View's container destruction to deal with the `viewContainer` and
168N/A checks to make sure not to remove and purge the `<body>`.
168N/A
613N/A @method _destroyContainer
613N/A @protected
670N/A **/
670N/A _destroyContainer: function () {
613N/A var container = this.get('container'),
168N/A viewContainer = this.get('viewContainer'),
168N/A areSame = container.compareTo(viewContainer);
168N/A
670N/A // We do not want to remove or destroy the `<body>`.
670N/A if (Y.one('body').compareTo(container)) {
670N/A // Just clean-up our events listeners.
670N/A this.detachEvents();
670N/A
670N/A // Clean-up `yui3-app` CSS class on the `container`.
670N/A container && container.removeClass(App.CSS_CLASS);
670N/A
670N/A if (areSame) {
670N/A // Clean-up `yui3-app-views` CSS class on the `container`.
670N/A container && container.removeClass(App.VIEWS_CSS_CLASS);
168N/A } else {
168N/A // Destroy and purge the `viewContainer`.
168N/A viewContainer && viewContainer.remove(true);
168N/A }
769N/A
670N/A return;
168N/A }
168N/A
670N/A // Remove and purge events from both containers.
168N/A viewContainer && viewContainer.remove(true);
168N/A !areSame && container && container.remove(true);
168N/A },
168N/A
168N/A /**
670N/A Helper method to detach the view instance from the application by removing
670N/A the application as a bubble target of the view, and either just removing the
168N/A view if it is intended to be preserved, or destroying the instance
670N/A completely.
769N/A
769N/A @method _detachView
769N/A @param {View} view View to detach.
168N/A @protected
670N/A **/
670N/A _detachView: function (view) {
670N/A if (!view) {
670N/A return;
670N/A }
168N/A
168N/A var viewInfo = this.getViewInfo(view) || {};
168N/A
168N/A if (viewInfo.preserve) {
168N/A view.remove();
168N/A // TODO: Detach events here for preserved Views? It is possible that
670N/A // some event subscriptions are made on elements other than the
670N/A // View's `container`.
168N/A } else {
670N/A view.destroy({remove: true});
670N/A
295N/A // TODO: The following should probably happen automagically from
670N/A // `destroy()` being called! Possibly `removeTarget()` as well.
670N/A
670N/A // Remove from view to view-info map.
670N/A delete this._viewInfoMap[Y.stamp(view, true)];
670N/A
670N/A // Remove from view-info instance property.
670N/A if (view === viewInfo.instance) {
670N/A delete viewInfo.instance;
670N/A }
670N/A }
670N/A
670N/A view.removeTarget(this);
670N/A },
670N/A
670N/A /**
670N/A Provides the default value for the `html5` attribute.
670N/A
670N/A The value returned is dependent on the value of the `serverRouting`
670N/A attribute. When `serverRouting` is explicit set to `false` (not just falsy),
670N/A the default value for `html5` will be set to `false` for *all* browsers.
670N/A
670N/A When `serverRouting` is `true` or `undefined` the returned value will be
670N/A dependent on the browser's capability of using HTML5 history.
670N/A
670N/A @method _initHtml5
670N/A @return {Boolean} Whether or not HTML5 history should be used.
670N/A @protected
670N/A **/
670N/A _initHtml5: function () {
670N/A // When `serverRouting` is explicitly set to `false` (not just falsy),
670N/A // forcing hash-based URLs in all browsers.
670N/A if (this.get('serverRouting') === false) {
670N/A return false;
670N/A } else {
670N/A return Router.html5;
295N/A }
295N/A },
295N/A
670N/A /**
670N/A Determines if the specified `view` is configured as a child of the specified
670N/A `parent` view. This requires both views to be either named-views, or view
670N/A instances created using configuration data that exists in the `views`
670N/A object, e.g. created by the `createView()` or `showView()` method.
670N/A
670N/A @method _isChildView
168N/A @param {View|String} view The name of a view defined in the `views` object,
168N/A or a view instance.
613N/A @param {View|String} parent The name of a view defined in the `views`
613N/A object, or a view instance.
613N/A @return {Boolean} Whether the view is configured as a child of the parent.
168N/A @protected
168N/A **/
670N/A _isChildView: function (view, parent) {
168N/A var viewInfo = this.getViewInfo(view),
168N/A parentInfo = this.getViewInfo(parent);
168N/A
168N/A if (viewInfo && parentInfo) {
168N/A return this.getViewInfo(viewInfo.parent) === parentInfo;
613N/A }
613N/A
670N/A return false;
670N/A },
613N/A
670N/A /**
168N/A Determines if the specified `view` is configured as the parent of the
168N/A specified `child` view. This requires both views to be either named-views,
168N/A or view instances created using configuration data that exists in the
670N/A `views` object, e.g. created by the `createView()` or `showView()` method.
168N/A
168N/A @method _isParentView
168N/A @param {View|String} view The name of a view defined in the `views` object,
168N/A or a view instance.
670N/A @param {View|String} parent The name of a view defined in the `views`
168N/A object, or a view instance.
670N/A @return {Boolean} Whether the view is configured as the parent of the child.
168N/A @protected
168N/A **/
613N/A _isParentView: function (view, child) {
613N/A var viewInfo = this.getViewInfo(view),
670N/A childInfo = this.getViewInfo(child);
613N/A
613N/A if (viewInfo && childInfo) {
168N/A return this.getViewInfo(childInfo.parent) === viewInfo;
295N/A }
295N/A
295N/A return false;
295N/A },
168N/A
168N/A /**
613N/A Underlying implementation for `navigate()`.
613N/A
670N/A @method _navigate
613N/A @param {String} url The fully-resolved URL that the app should dispatch to
613N/A its route handlers to fulfill the enhanced navigation "request", or use to
168N/A update `window.location` in non-HTML5 history capable browsers when
168N/A `serverRouting` is `true`.
168N/A @param {Object} [options] Additional options to configure the navigation.
168N/A These are mixed into the `navigate` event facade.
613N/A @param {Boolean} [options.replace] Whether or not the current history
613N/A entry will be replaced, or a new entry will be created. Will default
670N/A to `true` if the specified `url` is the same as the current URL.
613N/A @param {Boolean} [options.force] Whether the enhanced navigation
613N/A should occur even in browsers without HTML5 history. Will default to
168N/A `true` when `serverRouting` is falsy.
168N/A @protected
168N/A @see PjaxBase._navigate()
168N/A **/
168N/A _navigate: function (url, options) {
168N/A url = this._upgradeURL(url);
168N/A
168N/A options || (options = {});
if (!this.get('serverRouting')) {
// Force navigation to be enhanced and handled by the app when
// `serverRouting` is falsy because the server might not be able to
// properly handle the request.
Lang.isValue(options.force) || (options.force = true);
// Determine if the current history entry should be replaced. Since
// we've upgraded a hash-based URL to a full-path URL, we'll do the
// same for the current URL before comparing the two.
if (!Lang.isValue(options.replace)) {
options.replace = url === this._upgradeURL(this._getURL());
}
}
return PjaxBase.prototype._navigate.call(this, url, options);
},
/**
Will either save a history entry using `pushState()` or the location hash,
or gracefully-degrade to sending a request to the server causing a full-page
reload.
Overrides Router's `_save()` method to preform graceful-degradation when the
app's `serverRouting` is `true` and `html5` is `false` by updating the full
URL via standard assignment to `window.location` or by calling
`window.location.replace()`; both of which will cause a request to the
server resulting in a full-page reload.
Otherwise this will just delegate off to Router's `_save()` method allowing
the client-side enhanced routing to occur.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@see Router._save()
@chainable
@protected
**/
_save: function (url, replace) {
// Forces full-path URLs to always be used by modifying
// `window.location` in non-HTML5 history capable browsers.
if (this.get('serverRouting') && !this.get('html5')) {
// Perform same-origin check on the specified URL.
if (!this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Results in the URL's full path starting with '/'.
url = this._joinURL(url || '');
// Either replace the current history entry or create a new one
// while navigating to the `url`.
if (replace) {
win && win.location.replace(url);
} else {
win && (win.location = url);
}
return this;
}
return Router.prototype._save.apply(this, arguments);
},
/**
Performs the actual change of the app's `activeView` by attaching the
`newView` to this app, and detaching the `oldView` from this app using any
specified `options`.
The `newView` is attached to the app by rendering it to the `viewContainer`,
and making this app a bubble target of its events.
The `oldView` is detached from the app by removing it from the
`viewContainer`, and removing this app as a bubble target for its events.
The `oldView` will either be preserved or properly destroyed.
The `activeView` attribute is read-only and can be changed by calling the
`showView()` method.
@method _uiSetActiveView
@param {View} newView The View which is now this app's `activeView`.
@param {View} [oldView] The View which was this app's `activeView`.
@param {Object} [options] Optional object containing any of the following
properties:
@param {Boolean} [options.prepend] Whether the new view should be
prepended instead of appended to the `viewContainer`.
@param {Function} [callback] Optional callback Function to call after the
`newView` is ready to use, the function will be passed:
@param {View} options.callback.view A reference to the `newView`.
@protected
**/
_uiSetActiveView: function (newView, oldView, options) {
options || (options = {});
var callback = options.callback,
isChild = this._isChildView(newView, oldView),
isParent = !isChild && this._isParentView(newView, oldView),
prepend = !!options.prepend || isParent;
// Prevent detaching (thus removing) the view we want to show.
// Also hard to animate out and in, the same view.
if (newView === oldView) {
return callback && callback.call(this, newView);
}
this._attachView(newView, prepend);
this._detachView(oldView);
callback && callback.call(this, newView);
},
/**
Upgrades a hash-based URL to a full-path URL, if necessary.
The specified `url` will be upgraded if its of the same origin as the
current URL and has a path-like hash. URLs that don't need upgrading will be
returned as-is.
@example
app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
@method _upgradeURL
@param {String} url The URL to upgrade from hash-based to full-path.
@return {String} The upgraded URL, or the specified URL untouched.
@protected
**/
_upgradeURL: function (url) {
// We should not try to upgrade paths for external URLs.
if (!this._hasSameOrigin(url)) {
return url;
}
// TODO: Should the `root` be removed first, and the hash only
// considered if in the form of '/#/'?
var hash = (url.match(/#(.*)$/) || [])[1] || '',
hashPrefix = Y.HistoryHash.hashPrefix;
// Strip any hash prefix, like hash-bangs.
if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
hash = hash.replace(hashPrefix, '');
}
// If the hash looks like a URL path, assume it is, and upgrade it!
if (hash && hash.charAt(0) === '/') {
// Re-join with configured `root` before resolving.
url = this._resolveURL(this._joinURL(hash));
}
return url;
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles the application's `activeViewChange` event (which is fired when the
`activeView` attribute changes) by detaching the old view, attaching the new
view.
The `activeView` attribute is read-only, so the public API to change its
value is through the `showView()` method.
@method _afterActiveViewChange
@param {EventFacade} e
@protected
**/
_afterActiveViewChange: function (e) {
this._uiSetActiveView(e.newVal, e.prevVal, e.options);
}
}, {
ATTRS: {
/**
The application's active/visible view.
This attribute is read-only, to set the `activeView` use the
`showView()` method.
@attribute activeView
@type View
@default `null`
@readOnly
@see showView
**/
activeView: {
value : null,
readOnly: true
},
/**
Container node which represents the application's bounding-box, into
which this app's content will be rendered.
The container node serves as the host for all DOM events attached by the
app. Delegation is used to handle events on children of the container,
allowing the container's contents to be re-rendered at any time without
losing event subscriptions.
The default container is the `<body>` Node, but you can override this in
a subclass, or by passing in a custom `container` config value at
instantiation time.
When `container` is overridden by a subclass or passed as a config
option at instantiation time, it may be provided as a selector string, a
DOM element, or a `Y.Node` instance. During initialization, this app's
`create()` method will be called to convert the container into a
`Y.Node` instance if it isn't one already and stamp it with the CSS
class: `"yui3-app"`.
The container is not added to the page automatically. This allows you to
have full control over how and when your app is actually rendered to
the page.
@attribute container
@type HTMLElement|Node|String
@default `<body>`
@initOnly
**/
container: {
valueFn: function () {
return Y.one('body');
}
},
/**
Whether or not this browser is capable of using HTML5 history.
This value is dependent on the value of `serverRouting` and will default
accordingly.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
@see serverRouting
**/
html5: {
valueFn: '_initHtml5'
},
/**
CSS selector string used to filter link click events so that only the
links which match it will have the enhanced-navigation behavior of pjax
applied.
When a link is clicked and that link matches this selector, navigating
to the link's `href` URL using the enhanced, pjax, behavior will be
attempted; and the browser's default way to navigate to new pages will
be the fallback.
By default this selector will match _all_ links on the page.
@attribute linkSelector
@type String|Function
@default `"a"`
**/
linkSelector: {
value: 'a'
},
/**
Whether or not this application's server is capable of properly routing
all requests and rendering the initial state in the HTML responses.
This can have three different values, each having particular
implications on how the app will handle routing and navigation:
* `undefined`: The best form of URLs will be chosen based on the
capabilities of the browser. Given no information about the server
environmentm a balanced approach to routing and navigation is
chosen.
The server should be capable of handling full-path requests, since
full-URLs will be generated by browsers using HTML5 history. If this
is a client-side-only app the server could handle full-URL requests
by sending a redirect back to the root with a hash-based URL, e.g:
Request: http://example.com/users/1
Redirect to: http://example.com/#/users/1
* `true`: The server is *fully* capable of properly handling requests
to all full-path URLs the app can produce.
This is the best option for progressive-enhancement because it will
cause **all URLs to always have full-paths**, which means the server
will be able to accurately handle all URLs this app produces. e.g.
http://example.com/users/1
To meet this strict full-URL requirement, browsers which are not
capable of using HTML5 history will make requests to the server
resulting in full-page reloads.
* `false`: The server is *not* capable of properly handling requests
to all full-path URLs the app can produce, therefore all routing
will be handled by this App instance.
Be aware that this will cause **all URLs to always be hash-based**,
even in browsers that are capable of using HTML5 history. e.g.
http://example.com/#/users/1
A single-page or client-side-only app where the server sends a
"shell" page with JavaScript to the client might have this
restriction. If you're setting this to `false`, read the following:
**Note:** When this is set to `false`, the server will *never* receive
the full URL because browsers do not send the fragment-part to the
server, that is everything after and including the '#'.
Consider the following example:
URL shown in browser: http://example.com/#/users/1
URL sent to server: http://example.com/
You should feel bad about hurting our precious web if you forcefully set
either `serverRouting` or `html5` to `false`, because you're basically
punching the web in the face here with your lossy URLs! Please make sure
you know what you're doing and that you understand the implications.
Ideally you should always prefer full-path URLs (not /#/foo/), and want
full-page reloads when the client's browser is not capable of enhancing
the experience using the HTML5 history APIs. Setting this to `true` is
the best option for progressive-enhancement (and graceful-degradation).
@attribute serverRouting
@type Boolean
@default `undefined`
@initOnly
**/
serverRouting: {
value : undefined,
writeOnce: 'initOnly'
},
/**
The node into which this app's `views` will be rendered when they become
the `activeView`.
The view container node serves as the container to hold the app's
`activeView`. Each time the `activeView` is set via `showView()`, the
previous view will be removed from this node, and the new active view's
`container` node will be appended.
The default view container is `<div>` Node, but you can override this in
a subclass, or by passing in a custom `viewContainer` config value at
instantiation time.
When `viewContainer` is overridden by a subclass or passed as a config
option at instantiation time, it may be provided as a selector string,
DOM element, or a `Y.Node` instance (having the `viewContainer` and the
`container` be the same node is also supported). During initialization,
the app's `createViewContainer()` method will be called to convert the
view container into a `Y.Node` instance if it isn't one already and
stamp it with the CSS class: `"yui3-app-views"`.
The app's `render()` method will append the view container to the app's
`container` node if it isn't already, and any `activeView` will be
appended to this node if it isn't already.
@attribute viewContainer
@type HTMLElement|Node|String
@default `Y.Node.create("<div/>")`
@initOnly
**/
viewContainer: {
valueFn: function () {
return Y.Node.create('<div/>');
},
setter : 'createViewContainer',
writeOnce: 'initOnly'
}
},
CSS_CLASS : Y.ClassNameManager.getClassName('app'),
VIEWS_CSS_CLASS: Y.ClassNameManager.getClassName('app', 'views')
});
// -- Namespace ----------------------------------------------------------------
Y.namespace('App').Base = App;
/**
Provides a top-level application component which manages navigation and views.
This gives you a foundation and structure on which to build your application; it
combines robust URL navigation with powerful routing and flexible view
management.
`Y.App` is both a namespace and constructor function. The `Y.App` class is
special in that any `Y.App` class extensions that are included in the YUI
instance will be **auto-mixed** on to the `Y.App` class. Consider this example:
YUI().use('app-base', 'app-transitions', function (Y) {
// This will create two YUI Apps, `basicApp` will not have transitions,
// but `fancyApp` will have transitions support included and turn it on.
var basicApp = new Y.App.Base(),
fancyApp = new Y.App({transitions: true});
});
@class App
@param {Object} [config] The following are configuration properties that can be
specified _in addition_ to default attribute values and the non-attribute
properties provided by `Y.Base`:
@param {Object} [config.views] Hash of view-name to metadata used to
declaratively describe an application's views and their relationship with
the app and other views. The views specified here will override any defaults
provided by the `views` object on the `prototype`.
@constructor
@extends App.Base
@since 3.5.0
**/
Y.App = Y.mix(Y.Base.create('app', Y.App.Base, []), Y.App, true);
}, '@VERSION@' ,{requires:['classnamemanager', 'pjax-base', 'router', 'view']});