diff --git a/License.txt b/License.txt new file mode 100644 index 0000000..73c1b0b --- /dev/null +++ b/License.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2012 Blue Spire Consulting, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 44d8d2d..b0c9052 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,53 @@ -Durandal-Bower -============== +![Durandal](http://durandaljs.com/media/DURANDAL-FINAL-HI-RES-LOGO-HOR-WEB.png) -The bower package repo. +Durandal is a cross-device, cross-platform client framework written in JavaScript and designed to make Single Page Applications (SPAs) easy to create and maintain. We've used it to build apps for PC, Mac, Linux, iOS and Android...and now it's your turn... + +[![Build Status](https://travis-ci.org/BlueSpire/Durandal.png?branch=master)](https://travis-ci.org/BlueSpire/Durandal) + +## Features + +* Clean MV* Architecture +* JS & HTML Modularity +* Simple App Lifecycle +* Eventing, Modals, Message Boxes, etc. +* Navigation & Screen State Management +* Consistent Async Programming w/ Promises +* App Bundling and Optimization +* Use any Backend Technology +* Built on top of [jQuery](http://jquery.com/), [Knockout](http://knockoutjs.com/) & [RequireJS](http://requirejs.org/). +* Integrates with popular CSS libraries such as [Bootstrap](http://twitter.github.com/bootstrap/) and [Foundation](http://foundation.zurb.com/). +* Make your own templatable and data-bindable widgets. + +## Documentation + +All the documentation is located on [the official site](http://durandaljs.com/), so have a look there for help on how to [get started](http://durandaljs.com/pages/get-started/), [read tutorials](http://durandaljs.com/pages/docs/), [view sample descriptions](http://durandaljs.com/documentation/Understanding-the-Samples/) and peruse the module reference docs. +If you want to keep up to date with the activity that is happening on the master branch, you can [subscribe to the commit feed](https://github.com/BlueSpire/durandal/commits/master.atom). + +## Community & Support + +Need help with something that the docs aren't providing an answer to? +Visit our [google group](https://groups.google.com/forum/?fromgroups#!forum/durandaljs) and join in the conversation. We also provide [full commercial support](http://durandaljs.com/pages/support/) no matter how large or small your team is. Additionally, we offer both [on-site and remote training](http://durandaljs.com/pages/training/). + +## License + +The MIT License + +Copyright (c) 2012 Blue Spire Consulting, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..6565c83 --- /dev/null +++ b/bower.json @@ -0,0 +1,10 @@ +{ + "name": "Durandal", + "version": "2.0.0", + "dependencies": { + "jquery":"1.9.1", + "requirejs":"2.1.8", + "requirejs-text":"2.0.3", + "knockout.js":"2.3.0" + } +} \ No newline at end of file diff --git a/css/durandal.css b/css/durandal.css new file mode 100644 index 0000000..82aeab4 --- /dev/null +++ b/css/durandal.css @@ -0,0 +1,71 @@ +/*! + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details + */ + +.modalBlockout { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: black; + opacity: 0; + + pointer-events: auto; + + -webkit-backface-visibility: hidden; + + -webkit-transition: opacity 0.1s linear; + -moz-transition: opacity 0.1s linear; + -o-transition: opacity 0.1s linear; + transition: opacity 0.1s linear; +} + +.modalHost { + top: 50%; + left: 50%; + position: fixed; + opacity: 0; + + -webkit-backface-visibility: hidden; + + -webkit-transition: opacity 0.1s linear; + -moz-transition: opacity 0.1s linear; + -o-transition: opacity 0.1s linear; + transition: opacity 0.1s linear; +} + +.messageBox { + background-color: white; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + outline: none; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; + min-width: 300px; +} + +.durandal-view-404 { + color: red; + margin: 8px 0; + padding: 8px; + + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; +} diff --git a/img/icon.png b/img/icon.png new file mode 100644 index 0000000..6a56171 Binary files /dev/null and b/img/icon.png differ diff --git a/img/ios-startup-image-landscape.png b/img/ios-startup-image-landscape.png new file mode 100644 index 0000000..3199040 Binary files /dev/null and b/img/ios-startup-image-landscape.png differ diff --git a/img/ios-startup-image-portrait.png b/img/ios-startup-image-portrait.png new file mode 100644 index 0000000..05aa4ed Binary files /dev/null and b/img/ios-startup-image-portrait.png differ diff --git a/js/activator.js b/js/activator.js new file mode 100644 index 0000000..3960c4b --- /dev/null +++ b/js/activator.js @@ -0,0 +1,617 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The activator module encapsulates all logic related to screen/component activation. + * An activator is essentially an asynchronous state machine that understands a particular state transition protocol. + * The protocol ensures that the following series of events always occur: `canDeactivate` (previous state), `canActivate` (new state), `deactivate` (previous state), `activate` (new state). + * Each of the _can_ callbacks may return a boolean, affirmative value or promise for one of those. If either of the _can_ functions yields a false result, then activation halts. + * @module activator + * @requires system + * @requires knockout + */ +define(['durandal/system', 'knockout'], function (system, ko) { + var activator; + + function ensureSettings(settings) { + if (settings == undefined) { + settings = {}; + } + + if (!settings.closeOnDeactivate) { + settings.closeOnDeactivate = activator.defaults.closeOnDeactivate; + } + + if (!settings.beforeActivate) { + settings.beforeActivate = activator.defaults.beforeActivate; + } + + if (!settings.afterDeactivate) { + settings.afterDeactivate = activator.defaults.afterDeactivate; + } + + if(!settings.affirmations){ + settings.affirmations = activator.defaults.affirmations; + } + + if (!settings.interpretResponse) { + settings.interpretResponse = activator.defaults.interpretResponse; + } + + if (!settings.areSameItem) { + settings.areSameItem = activator.defaults.areSameItem; + } + + return settings; + } + + function invoke(target, method, data) { + if (system.isArray(data)) { + return target[method].apply(target, data); + } + + return target[method](data); + } + + function deactivate(item, close, settings, dfd, setter) { + if (item && item.deactivate) { + system.log('Deactivating', item); + + var result; + try { + result = item.deactivate(close); + } catch(error) { + system.error(error); + dfd.resolve(false); + return; + } + + if (result && result.then) { + result.then(function() { + settings.afterDeactivate(item, close, setter); + dfd.resolve(true); + }, function(reason) { + system.log(reason); + dfd.resolve(false); + }); + } else { + settings.afterDeactivate(item, close, setter); + dfd.resolve(true); + } + } else { + if (item) { + settings.afterDeactivate(item, close, setter); + } + + dfd.resolve(true); + } + } + + function activate(newItem, activeItem, callback, activationData) { + if (newItem) { + if (newItem.activate) { + system.log('Activating', newItem); + + var result; + try { + result = invoke(newItem, 'activate', activationData); + } catch (error) { + system.error(error); + callback(false); + return; + } + + if (result && result.then) { + result.then(function() { + activeItem(newItem); + callback(true); + }, function(reason) { + system.log(reason); + callback(false); + }); + } else { + activeItem(newItem); + callback(true); + } + } else { + activeItem(newItem); + callback(true); + } + } else { + callback(true); + } + } + + function canDeactivateItem(item, close, settings) { + settings.lifecycleData = null; + + return system.defer(function (dfd) { + if (item && item.canDeactivate) { + var resultOrPromise; + try { + resultOrPromise = item.canDeactivate(close); + } catch(error) { + system.error(error); + dfd.resolve(false); + return; + } + + if (resultOrPromise.then) { + resultOrPromise.then(function(result) { + settings.lifecycleData = result; + dfd.resolve(settings.interpretResponse(result)); + }, function(reason) { + system.error(reason); + dfd.resolve(false); + }); + } else { + settings.lifecycleData = resultOrPromise; + dfd.resolve(settings.interpretResponse(resultOrPromise)); + } + } else { + dfd.resolve(true); + } + }).promise(); + }; + + function canActivateItem(newItem, activeItem, settings, activationData) { + settings.lifecycleData = null; + + return system.defer(function (dfd) { + if (newItem == activeItem()) { + dfd.resolve(true); + return; + } + + if (newItem && newItem.canActivate) { + var resultOrPromise; + try { + resultOrPromise = invoke(newItem, 'canActivate', activationData); + } catch (error) { + system.error(error); + dfd.resolve(false); + return; + } + + if (resultOrPromise.then) { + resultOrPromise.then(function(result) { + settings.lifecycleData = result; + dfd.resolve(settings.interpretResponse(result)); + }, function(reason) { + system.error(reason); + dfd.resolve(false); + }); + } else { + settings.lifecycleData = resultOrPromise; + dfd.resolve(settings.interpretResponse(resultOrPromise)); + } + } else { + dfd.resolve(true); + } + }).promise(); + }; + + /** + * An activator is a read/write computed observable that enforces the activation lifecycle whenever changing values. + * @class Activator + */ + function createActivator(initialActiveItem, settings) { + var activeItem = ko.observable(null); + var activeData; + + settings = ensureSettings(settings); + + var computed = ko.computed({ + read: function () { + return activeItem(); + }, + write: function (newValue) { + computed.viaSetter = true; + computed.activateItem(newValue); + } + }); + + computed.__activator__ = true; + + /** + * The settings for this activator. + * @property {ActivatorSettings} settings + */ + computed.settings = settings; + settings.activator = computed; + + /** + * An observable which indicates whether or not the activator is currently in the process of activating an instance. + * @method isActivating + * @return {boolean} + */ + computed.isActivating = ko.observable(false); + + /** + * Determines whether or not the specified item can be deactivated. + * @method canDeactivateItem + * @param {object} item The item to check. + * @param {boolean} close Whether or not to check if close is possible. + * @return {promise} + */ + computed.canDeactivateItem = function (item, close) { + return canDeactivateItem(item, close, settings); + }; + + /** + * Deactivates the specified item. + * @method deactivateItem + * @param {object} item The item to deactivate. + * @param {boolean} close Whether or not to close the item. + * @return {promise} + */ + computed.deactivateItem = function (item, close) { + return system.defer(function(dfd) { + computed.canDeactivateItem(item, close).then(function(canDeactivate) { + if (canDeactivate) { + deactivate(item, close, settings, dfd, activeItem); + } else { + computed.notifySubscribers(); + dfd.resolve(false); + } + }); + }).promise(); + }; + + /** + * Determines whether or not the specified item can be activated. + * @method canActivateItem + * @param {object} item The item to check. + * @param {object} activationData Data associated with the activation. + * @return {promise} + */ + computed.canActivateItem = function (newItem, activationData) { + return canActivateItem(newItem, activeItem, settings, activationData); + }; + + /** + * Activates the specified item. + * @method activateItem + * @param {object} newItem The item to activate. + * @param {object} newActivationData Data associated with the activation. + * @return {promise} + */ + computed.activateItem = function (newItem, newActivationData) { + var viaSetter = computed.viaSetter; + computed.viaSetter = false; + + return system.defer(function (dfd) { + if (computed.isActivating()) { + dfd.resolve(false); + return; + } + + computed.isActivating(true); + + var currentItem = activeItem(); + if (settings.areSameItem(currentItem, newItem, activeData, newActivationData)) { + computed.isActivating(false); + dfd.resolve(true); + return; + } + + computed.canDeactivateItem(currentItem, settings.closeOnDeactivate).then(function (canDeactivate) { + if (canDeactivate) { + computed.canActivateItem(newItem, newActivationData).then(function (canActivate) { + if (canActivate) { + system.defer(function (dfd2) { + deactivate(currentItem, settings.closeOnDeactivate, settings, dfd2); + }).promise().then(function () { + newItem = settings.beforeActivate(newItem, newActivationData); + activate(newItem, activeItem, function (result) { + activeData = newActivationData; + computed.isActivating(false); + dfd.resolve(result); + }, newActivationData); + }); + } else { + if (viaSetter) { + computed.notifySubscribers(); + } + + computed.isActivating(false); + dfd.resolve(false); + } + }); + } else { + if (viaSetter) { + computed.notifySubscribers(); + } + + computed.isActivating(false); + dfd.resolve(false); + } + }); + }).promise(); + }; + + /** + * Determines whether or not the activator, in its current state, can be activated. + * @method canActivate + * @return {promise} + */ + computed.canActivate = function () { + var toCheck; + + if (initialActiveItem) { + toCheck = initialActiveItem; + initialActiveItem = false; + } else { + toCheck = computed(); + } + + return computed.canActivateItem(toCheck); + }; + + /** + * Activates the activator, in its current state. + * @method activate + * @return {promise} + */ + computed.activate = function () { + var toActivate; + + if (initialActiveItem) { + toActivate = initialActiveItem; + initialActiveItem = false; + } else { + toActivate = computed(); + } + + return computed.activateItem(toActivate); + }; + + /** + * Determines whether or not the activator, in its current state, can be deactivated. + * @method canDeactivate + * @return {promise} + */ + computed.canDeactivate = function (close) { + return computed.canDeactivateItem(computed(), close); + }; + + /** + * Deactivates the activator, in its current state. + * @method deactivate + * @return {promise} + */ + computed.deactivate = function (close) { + return computed.deactivateItem(computed(), close); + }; + + computed.includeIn = function (includeIn) { + includeIn.canActivate = function () { + return computed.canActivate(); + }; + + includeIn.activate = function () { + return computed.activate(); + }; + + includeIn.canDeactivate = function (close) { + return computed.canDeactivate(close); + }; + + includeIn.deactivate = function (close) { + return computed.deactivate(close); + }; + }; + + if (settings.includeIn) { + computed.includeIn(settings.includeIn); + } else if (initialActiveItem) { + computed.activate(); + } + + computed.forItems = function (items) { + settings.closeOnDeactivate = false; + + settings.determineNextItemToActivate = function (list, lastIndex) { + var toRemoveAt = lastIndex - 1; + + if (toRemoveAt == -1 && list.length > 1) { + return list[1]; + } + + if (toRemoveAt > -1 && toRemoveAt < list.length - 1) { + return list[toRemoveAt]; + } + + return null; + }; + + settings.beforeActivate = function (newItem) { + var currentItem = computed(); + + if (!newItem) { + newItem = settings.determineNextItemToActivate(items, currentItem ? items.indexOf(currentItem) : 0); + } else { + var index = items.indexOf(newItem); + + if (index == -1) { + items.push(newItem); + } else { + newItem = items()[index]; + } + } + + return newItem; + }; + + settings.afterDeactivate = function (oldItem, close) { + if (close) { + items.remove(oldItem); + } + }; + + var originalCanDeactivate = computed.canDeactivate; + computed.canDeactivate = function (close) { + if (close) { + return system.defer(function (dfd) { + var list = items(); + var results = []; + + function finish() { + for (var j = 0; j < results.length; j++) { + if (!results[j]) { + dfd.resolve(false); + return; + } + } + + dfd.resolve(true); + } + + for (var i = 0; i < list.length; i++) { + computed.canDeactivateItem(list[i], close).then(function (result) { + results.push(result); + if (results.length == list.length) { + finish(); + } + }); + } + }).promise(); + } else { + return originalCanDeactivate(); + } + }; + + var originalDeactivate = computed.deactivate; + computed.deactivate = function (close) { + if (close) { + return system.defer(function (dfd) { + var list = items(); + var results = 0; + var listLength = list.length; + + function doDeactivate(item) { + computed.deactivateItem(item, close).then(function () { + results++; + items.remove(item); + if (results == listLength) { + dfd.resolve(); + } + }); + } + + for (var i = 0; i < listLength; i++) { + doDeactivate(list[i]); + } + }).promise(); + } else { + return originalDeactivate(); + } + }; + + return computed; + }; + + return computed; + } + + /** + * @class ActivatorSettings + * @static + */ + var activatorSettings = { + /** + * The default value passed to an object's deactivate function as its close parameter. + * @property {boolean} closeOnDeactivate + * @default true + */ + closeOnDeactivate: true, + /** + * Lower-cased words which represent a truthy value. + * @property {string[]} affirmations + * @default ['yes', 'ok', 'true'] + */ + affirmations: ['yes', 'ok', 'true'], + /** + * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array. + * @method interpretResponse + * @param {object} value + * @return {boolean} + */ + interpretResponse: function(value) { + if(system.isObject(value)) { + value = value.can || false; + } + + if(system.isString(value)) { + return ko.utils.arrayIndexOf(this.affirmations, value.toLowerCase()) !== -1; + } + + return value; + }, + /** + * Determines whether or not the current item and the new item are the same. + * @method areSameItem + * @param {object} currentItem + * @param {object} newItem + * @param {object} currentActivationData + * @param {object} newActivationData + * @return {boolean} + */ + areSameItem: function(currentItem, newItem, currentActivationData, newActivationData) { + return currentItem == newItem; + }, + /** + * Called immediately before the new item is activated. + * @method beforeActivate + * @param {object} newItem + */ + beforeActivate: function(newItem) { + return newItem; + }, + /** + * Called immediately after the old item is deactivated. + * @method afterDeactivate + * @param {object} oldItem The previous item. + * @param {boolean} close Whether or not the previous item was closed. + * @param {function} setter The activate item setter function. + */ + afterDeactivate: function(oldItem, close, setter) { + if(close && setter) { + setter(null); + } + } + }; + + /** + * @class ActivatorModule + * @static + */ + activator = { + /** + * The default settings used by activators. + * @property {ActivatorSettings} defaults + */ + defaults: activatorSettings, + /** + * Creates a new activator. + * @method create + * @param {object} [initialActiveItem] The item which should be immediately activated upon creation of the ativator. + * @param {ActivatorSettings} [settings] Per activator overrides of the default activator settings. + * @return {Activator} The created activator. + */ + create: createActivator, + /** + * Determines whether or not the provided object is an activator or not. + * @method isActivator + * @param {object} object Any object you wish to verify as an activator or not. + * @return {boolean} True if the object is an activator; false otherwise. + */ + isActivator:function(object){ + return object && object.__activator__; + } + }; + + return activator; +}); diff --git a/js/app.js b/js/app.js new file mode 100644 index 0000000..b6d6916 --- /dev/null +++ b/js/app.js @@ -0,0 +1,136 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The app module controls app startup, plugin loading/configuration and root visual display. + * @module app + * @requires system + * @requires viewEngine + * @requires composition + * @requires events + * @requires jquery + */ +define(['durandal/system', 'durandal/viewEngine', 'durandal/composition', 'durandal/events', 'jquery'], function(system, viewEngine, composition, Events, $) { + var app, + allPluginIds = [], + allPluginConfigs = []; + + function loadPlugins(){ + return system.defer(function(dfd){ + if(allPluginIds.length == 0){ + dfd.resolve(); + return; + } + + system.acquire(allPluginIds).then(function(loaded){ + for(var i = 0; i < loaded.length; i++){ + var currentModule = loaded[i]; + + if(currentModule.install){ + var config = allPluginConfigs[i]; + if(!system.isObject(config)){ + config = {}; + } + + currentModule.install(config); + system.log('Plugin:Installed ' + allPluginIds[i]); + }else{ + system.log('Plugin:Loaded ' + allPluginIds[i]); + } + } + + dfd.resolve(); + }).fail(function(err){ + system.error('Failed to load plugin(s). Details: ' + err.message); + }); + }).promise(); + } + + /** + * @class AppModule + * @static + * @uses Events + */ + app = { + /** + * The title of your application. + * @property {string} title + */ + title: 'Application', + /** + * Configures one or more plugins to be loaded and installed into the application. + * @method configurePlugins + * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin. + * @param {string} [baseUrl] The base url to load the plugins from. + */ + configurePlugins:function(config, baseUrl){ + var pluginIds = system.keys(config); + baseUrl = baseUrl || 'plugins/'; + + if(baseUrl.indexOf('/', baseUrl.length - 1) === -1){ + baseUrl += '/'; + } + + for(var i = 0; i < pluginIds.length; i++){ + var key = pluginIds[i]; + allPluginIds.push(baseUrl + key); + allPluginConfigs.push(config[key]); + } + }, + /** + * Starts the application. + * @method start + * @return {promise} + */ + start: function() { + system.log('Application:Starting'); + + if (this.title) { + document.title = this.title; + } + + return system.defer(function (dfd) { + $(function() { + loadPlugins().then(function(){ + dfd.resolve(); + system.log('Application:Started'); + }); + }); + }).promise(); + }, + /** + * Sets the root module/view for the application. + * @method setRoot + * @param {string} root The root view or module. + * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. + * @param {string} [applicationHost] The application host element or id. By default the id 'applicationHost' will be used. + */ + setRoot: function(root, transition, applicationHost) { + var hostElement, settings = { activate:true, transition: transition }; + + if (!applicationHost || system.isString(applicationHost)) { + hostElement = document.getElementById(applicationHost || 'applicationHost'); + } else { + hostElement = applicationHost; + } + + if (system.isString(root)) { + if (viewEngine.isViewUrl(root)) { + settings.view = root; + } else { + settings.model = root; + } + } else { + settings.model = root; + } + + composition.compose(hostElement, settings); + } + }; + + Events.includeIn(app); + + return app; +}); diff --git a/js/binder.js b/js/binder.js new file mode 100644 index 0000000..4174a77 --- /dev/null +++ b/js/binder.js @@ -0,0 +1,151 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The binder joins an object instance and a DOM element tree by applying databinding and/or invoking binding lifecycle callbacks (binding and bindingComplete). + * @module binder + * @requires system + * @requires knockout + */ +define(['durandal/system', 'knockout'], function (system, ko) { + var binder, + insufficientInfoMessage = 'Insufficient Information to Bind', + unexpectedViewMessage = 'Unexpected View Type', + bindingInstructionKey = 'durandal-binding-instruction', + koBindingContextKey = '__ko_bindingContext__'; + + function normalizeBindingInstruction(result){ + if(result === undefined){ + return { applyBindings: true }; + } + + if(system.isBoolean(result)){ + return { applyBindings:result }; + } + + if(result.applyBindings === undefined){ + result.applyBindings = true; + } + + return result; + } + + function doBind(obj, view, bindingTarget, data){ + if (!view || !bindingTarget) { + if (binder.throwOnErrors) { + system.error(insufficientInfoMessage); + } else { + system.log(insufficientInfoMessage, view, data); + } + return; + } + + if (!view.getAttribute) { + if (binder.throwOnErrors) { + system.error(unexpectedViewMessage); + } else { + system.log(unexpectedViewMessage, view, data); + } + return; + } + + var viewName = view.getAttribute('data-view'); + + try { + var instruction; + + if (obj && obj.binding) { + instruction = obj.binding(view); + } + + instruction = normalizeBindingInstruction(instruction); + binder.binding(data, view, instruction); + + if(instruction.applyBindings){ + system.log('Binding', viewName, data); + ko.applyBindings(bindingTarget, view); + }else if(obj){ + ko.utils.domData.set(view, koBindingContextKey, { $data:obj }); + } + + binder.bindingComplete(data, view, instruction); + + if (obj && obj.bindingComplete) { + obj.bindingComplete(view); + } + + ko.utils.domData.set(view, bindingInstructionKey, instruction); + return instruction; + } catch (e) { + e.message = e.message + ';\nView: ' + viewName + ";\nModuleId: " + system.getModuleId(data); + if (binder.throwOnErrors) { + system.error(e); + } else { + system.log(e.message); + } + } + } + + /** + * @class BinderModule + * @static + */ + return binder = { + /** + * Called before every binding operation. Does nothing by default. + * @method binding + * @param {object} data The data that is about to be bound. + * @param {DOMElement} view The view that is about to be bound. + * @param {object} instruction The object that carries the binding instructions. + */ + binding: system.noop, + /** + * Called after every binding operation. Does nothing by default. + * @method bindingComplete + * @param {object} data The data that has just been bound. + * @param {DOMElement} view The view that has just been bound. + * @param {object} instruction The object that carries the binding instructions. + */ + bindingComplete: system.noop, + /** + * Indicates whether or not the binding system should throw errors or not. + * @property {boolean} throwOnErrors + * @default false The binding system will not throw errors by default. Instead it will log them. + */ + throwOnErrors: false, + /** + * Gets the binding instruction that was associated with a view when it was bound. + * @method getBindingInstruction + * @param {DOMElement} view The view that was previously bound. + * @return {object} The object that carries the binding instructions. + */ + getBindingInstruction:function(view){ + return ko.utils.domData.get(view, bindingInstructionKey); + }, + /** + * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. + * @method bindContext + * @param {KnockoutBindingContext} bindingContext The current binding context. + * @param {DOMElement} view The view to bind. + * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present. + */ + bindContext: function(bindingContext, view, obj) { + if (obj && bindingContext) { + bindingContext = bindingContext.createChildContext(obj); + } + + return doBind(obj, view, bindingContext, obj || (bindingContext ? bindingContext.$data : null)); + }, + /** + * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. + * @method bind + * @param {object} obj The data to bind to. + * @param {DOMElement} view The view to bind. + */ + bind: function(obj, view) { + return doBind(obj, view, obj, obj); + } + }; +}); diff --git a/js/composition.js b/js/composition.js new file mode 100644 index 0000000..f18a4e4 --- /dev/null +++ b/js/composition.js @@ -0,0 +1,621 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The composition module encapsulates all functionality related to visual composition. + * @module composition + * @requires system + * @requires viewLocator + * @requires binder + * @requires viewEngine + * @requires activator + * @requires jquery + * @requires knockout + */ +define(['durandal/system', 'durandal/viewLocator', 'durandal/binder', 'durandal/viewEngine', 'durandal/activator', 'jquery', 'knockout'], function (system, viewLocator, binder, viewEngine, activator, $, ko) { + var dummyModel = {}, + activeViewAttributeName = 'data-active-view', + composition, + compositionCompleteCallbacks = [], + compositionCount = 0, + compositionDataKey = 'durandal-composition-data', + partAttributeName = 'data-part', + partAttributeSelector = '[' + partAttributeName + ']', + bindableSettings = ['model', 'view', 'transition', 'area', 'strategy', 'activationData']; + + function getHostState(parent) { + var elements = []; + var state = { + childElements: elements, + activeView: null + }; + + var child = ko.virtualElements.firstChild(parent); + + while (child) { + if (child.nodeType == 1) { + elements.push(child); + if (child.getAttribute(activeViewAttributeName)) { + state.activeView = child; + } + } + + child = ko.virtualElements.nextSibling(child); + } + + if(!state.activeView){ + state.activeView = elements[0]; + } + + return state; + } + + function endComposition() { + compositionCount--; + + if (compositionCount === 0) { + setTimeout(function(){ + var i = compositionCompleteCallbacks.length; + + while(i--) { + compositionCompleteCallbacks[i](); + } + + compositionCompleteCallbacks = []; + }, 1); + } + } + + function tryActivate(context, successCallback, skipActivation) { + if(skipActivation){ + successCallback(); + } else if (context.activate && context.model && context.model.activate) { + var result; + + if(system.isArray(context.activationData)) { + result = context.model.activate.apply(context.model, context.activationData); + } else { + result = context.model.activate(context.activationData); + } + + if(result && result.then) { + result.then(successCallback); + } else if(result || result === undefined) { + successCallback(); + } else { + endComposition(); + } + } else { + successCallback(); + } + } + + function triggerAttach() { + var context = this; + + if (context.activeView) { + context.activeView.removeAttribute(activeViewAttributeName); + } + + if (context.child) { + if (context.model && context.model.attached) { + if (context.composingNewView || context.alwaysTriggerAttach) { + context.model.attached(context.child, context.parent, context); + } + } + + if (context.attached) { + context.attached(context.child, context.parent, context); + } + + context.child.setAttribute(activeViewAttributeName, true); + + if (context.composingNewView && context.model) { + if (context.model.compositionComplete) { + composition.current.complete(function () { + context.model.compositionComplete(context.child, context.parent, context); + }); + } + + if (context.model.detached) { + ko.utils.domNodeDisposal.addDisposeCallback(context.child, function () { + context.model.detached(context.child, context.parent, context); + }); + } + } + + if (context.compositionComplete) { + composition.current.complete(function () { + context.compositionComplete(context.child, context.parent, context); + }); + } + } + + endComposition(); + context.triggerAttach = system.noop; + } + + function shouldTransition(context) { + if (system.isString(context.transition)) { + if (context.activeView) { + if (context.activeView == context.child) { + return false; + } + + if (!context.child) { + return true; + } + + if (context.skipTransitionOnSameViewId) { + var currentViewId = context.activeView.getAttribute('data-view'); + var newViewId = context.child.getAttribute('data-view'); + return currentViewId != newViewId; + } + } + + return true; + } + + return false; + } + + function cloneNodes(nodesArray) { + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) { + var clonedNode = nodesArray[i].cloneNode(true); + newNodesArray.push(clonedNode); + } + return newNodesArray; + } + + function replaceParts(context){ + var parts = cloneNodes(context.parts); + var replacementParts = composition.getParts(parts); + var standardParts = composition.getParts(context.child); + + for (var partId in replacementParts) { + $(standardParts[partId]).replaceWith(replacementParts[partId]); + } + } + + function removePreviousView(parent){ + var children = ko.virtualElements.childNodes(parent), i, len; + + if(!system.isArray(children)){ + var arrayChildren = []; + + for(i = 0, len = children.length; i < len; i++){ + arrayChildren[i] = children[i]; + } + + children = arrayChildren; + } + + for(i = 1,len = children.length; i < len; i++){ + ko.removeNode(children[i]); + } + } + + /** + * @class CompositionTransaction + * @static + */ + var compositionTransaction = { + /** + * Registers a callback which will be invoked when the current composition transaction has completed. The transaction includes all parent and children compositions. + * @method complete + * @param {function} callback The callback to be invoked when composition is complete. + */ + complete: function (callback) { + compositionCompleteCallbacks.push(callback); + } + }; + + /** + * @class CompositionModule + * @static + */ + composition = { + /** + * Converts a transition name to its moduleId. + * @method convertTransitionToModuleId + * @param {string} name The name of the transtion. + * @return {string} The moduleId. + */ + convertTransitionToModuleId: function (name) { + return 'transitions/' + name; + }, + /** + * The name of the transition to use in all compositions. + * @property {string} defaultTransitionName + * @default null + */ + defaultTransitionName: null, + /** + * Represents the currently executing composition transaction. + * @property {CompositionTransaction} current + */ + current: compositionTransaction, + /** + * Registers a binding handler that will be invoked when the current composition transaction is complete. + * @method addBindingHandler + * @param {string} name The name of the binding handler. + * @param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler. + * @param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does. + */ + addBindingHandler:function(name, config, initOptionsFactory){ + var key, + dataKey = 'composition-handler-' + name, + handler; + + config = config || ko.bindingHandlers[name]; + initOptionsFactory = initOptionsFactory || function(){ return undefined; }; + + handler = ko.bindingHandlers[name] = { + init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var data = { + trigger:ko.observable(null) + }; + + composition.current.complete(function(){ + if(config.init){ + config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + } + + if(config.update){ + ko.utils.domData.set(element, dataKey, config); + data.trigger('trigger'); + } + }); + + ko.utils.domData.set(element, dataKey, data); + + return initOptionsFactory(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + }, + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var data = ko.utils.domData.get(element, dataKey); + + if(data.update){ + return data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + } + + data.trigger(); + } + }; + + for (key in config) { + if (key !== "init" && key !== "update") { + handler[key] = config[key]; + } + } + }, + /** + * Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself. + * @method getParts + * @param {DOMElement\DOMElement[]} elements The element(s) to search for parts. + * @return {object} An object keyed by part. + */ + getParts: function(elements) { + var parts = {}; + + if (!system.isArray(elements)) { + elements = [elements]; + } + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + + if (element.getAttribute) { + var id = element.getAttribute(partAttributeName); + if (id) { + parts[id] = element; + } + + var childParts = $(partAttributeSelector, element) + .not($('[data-bind] ' + partAttributeSelector, element)); + + for (var j = 0; j < childParts.length; j++) { + var part = childParts.get(j); + parts[part.getAttribute(partAttributeName)] = part; + } + } + } + + return parts; + }, + cloneNodes:cloneNodes, + finalize: function (context) { + context.transition = context.transition || this.defaultTransitionName; + + if(!context.child && !context.activeView){ + if (!context.cacheViews) { + ko.virtualElements.emptyNode(context.parent); + } + + context.triggerAttach(); + }else if (shouldTransition(context)) { + var transitionModuleId = this.convertTransitionToModuleId(context.transition); + + system.acquire(transitionModuleId).then(function (transition) { + context.transition = transition; + + transition(context).then(function () { + if (!context.cacheViews) { + if(!context.child){ + ko.virtualElements.emptyNode(context.parent); + }else{ + removePreviousView(context.parent); + } + }else if(context.activeView){ + var instruction = binder.getBindingInstruction(context.activeView); + if(instruction.cacheViews != undefined && !instruction.cacheViews){ + ko.removeNode(context.activeView); + } + } + + context.triggerAttach(); + }); + }).fail(function(err){ + system.error('Failed to load transition (' + transitionModuleId + '). Details: ' + err.message); + }); + } else { + if (context.child != context.activeView) { + if (context.cacheViews && context.activeView) { + var instruction = binder.getBindingInstruction(context.activeView); + if(instruction.cacheViews != undefined && !instruction.cacheViews){ + ko.removeNode(context.activeView); + }else{ + $(context.activeView).hide(); + } + } + + if (!context.child) { + if (!context.cacheViews) { + ko.virtualElements.emptyNode(context.parent); + } + } else { + if (!context.cacheViews) { + removePreviousView(context.parent); + } + + $(context.child).show(); + } + } + + context.triggerAttach(); + } + }, + bindAndShow: function (child, context, skipActivation) { + context.child = child; + + if (context.cacheViews) { + context.composingNewView = (ko.utils.arrayIndexOf(context.viewElements, child) == -1); + } else { + context.composingNewView = true; + } + + tryActivate(context, function () { + if (context.binding) { + context.binding(context.child, context.parent, context); + } + + if (context.preserveContext && context.bindingContext) { + if (context.composingNewView) { + if(context.parts){ + replaceParts(context); + } + + $(child).hide(); + ko.virtualElements.prepend(context.parent, child); + + binder.bindContext(context.bindingContext, child, context.model); + } + } else if (child) { + var modelToBind = context.model || dummyModel; + var currentModel = ko.dataFor(child); + + if (currentModel != modelToBind) { + if (!context.composingNewView) { + $(child).remove(); + viewEngine.createView(child.getAttribute('data-view')).then(function(recreatedView) { + composition.bindAndShow(recreatedView, context, true); + }); + return; + } + + if(context.parts){ + replaceParts(context); + } + + $(child).hide(); + ko.virtualElements.prepend(context.parent, child); + + binder.bind(modelToBind, child); + } + } + + composition.finalize(context); + }, skipActivation); + }, + /** + * Eecutes the default view location strategy. + * @method defaultStrategy + * @param {object} context The composition context containing the model and possibly existing viewElements. + * @return {promise} A promise for the view. + */ + defaultStrategy: function (context) { + return viewLocator.locateViewForObject(context.model, context.area, context.viewElements); + }, + getSettings: function (valueAccessor, element) { + var value = valueAccessor(), + settings = ko.utils.unwrapObservable(value) || {}, + activatorPresent = activator.isActivator(value), + moduleId; + + if (system.isString(settings)) { + if (viewEngine.isViewUrl(settings)) { + settings = { + view: settings + }; + } else { + settings = { + model: settings, + activate: true + }; + } + + return settings; + } + + moduleId = system.getModuleId(settings); + if (moduleId) { + settings = { + model: settings, + activate: true + }; + + return settings; + } + + if(!activatorPresent && settings.model) { + activatorPresent = activator.isActivator(settings.model); + } + + for (var attrName in settings) { + if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) { + settings[attrName] = ko.utils.unwrapObservable(settings[attrName]); + } else { + settings[attrName] = settings[attrName]; + } + } + + if (activatorPresent) { + settings.activate = false; + } else if (settings.activate === undefined) { + settings.activate = true; + } + + return settings; + }, + executeStrategy: function (context) { + context.strategy(context).then(function (child) { + composition.bindAndShow(child, context); + }); + }, + inject: function (context) { + if (!context.model) { + this.bindAndShow(null, context); + return; + } + + if (context.view) { + viewLocator.locateView(context.view, context.area, context.viewElements).then(function (child) { + composition.bindAndShow(child, context); + }); + return; + } + + if (!context.strategy) { + context.strategy = this.defaultStrategy; + } + + if (system.isString(context.strategy)) { + system.acquire(context.strategy).then(function (strategy) { + context.strategy = strategy; + composition.executeStrategy(context); + }).fail(function(err){ + system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message); + }); + } else { + this.executeStrategy(context); + } + }, + /** + * Initiates a composition. + * @method compose + * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the parent for the composition. + * @param {object} settings The composition settings. + * @param {object} [bindingContext] The current binding context. + */ + compose: function (element, settings, bindingContext, fromBinding) { + compositionCount++; + + if(!fromBinding){ + settings = composition.getSettings(function() { return settings; }, element); + } + + var hostState = getHostState(element); + + settings.activeView = hostState.activeView; + settings.parent = element; + settings.triggerAttach = triggerAttach; + settings.bindingContext = bindingContext; + + if (settings.cacheViews && !settings.viewElements) { + settings.viewElements = hostState.childElements; + } + + if (!settings.model) { + if (!settings.view) { + this.bindAndShow(null, settings); + } else { + settings.area = settings.area || 'partial'; + settings.preserveContext = true; + + viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) { + composition.bindAndShow(child, settings); + }); + } + } else if (system.isString(settings.model)) { + system.acquire(settings.model).then(function (module) { + settings.model = system.resolveObject(module); + composition.inject(settings); + }).fail(function(err){ + system.error('Failed to load composed module (' + settings.model + '). Details: ' + err.message); + }); + } else { + composition.inject(settings); + } + } + }; + + ko.bindingHandlers.compose = { + init: function() { + return { controlsDescendantBindings: true }; + }, + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var settings = composition.getSettings(valueAccessor, element); + if(settings.mode){ + var data = ko.utils.domData.get(element, compositionDataKey); + if(!data){ + var childNodes = ko.virtualElements.childNodes(element); + data = {}; + + if(settings.mode === 'inline'){ + data.view = viewEngine.ensureSingleElement(childNodes); + }else if(settings.mode === 'templated'){ + data.parts = cloneNodes(childNodes); + } + + ko.virtualElements.emptyNode(element); + ko.utils.domData.set(element, compositionDataKey, data); + } + + if(settings.mode === 'inline'){ + settings.view = data.view.cloneNode(true); + }else if(settings.mode === 'templated'){ + settings.parts = data.parts; + } + + settings.preserveContext = true; + } + + composition.compose(element, settings, bindingContext, true); + } + }; + + ko.virtualElements.allowedBindings.compose = true; + + return composition; +}); diff --git a/js/events.js b/js/events.js new file mode 100644 index 0000000..67967fd --- /dev/null +++ b/js/events.js @@ -0,0 +1,216 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Durandal events originate from backbone.js but also combine some ideas from signals.js as well as some additional improvements. + * Events can be installed into any object and are installed into the `app` module by default for convenient app-wide eventing. + * @module events + * @requires system + */ +define(['durandal/system'], function (system) { + var eventSplitter = /\s+/; + var Events = function() { }; + + /** + * Represents an event subscription. + * @class Subscription + */ + var Subscription = function(owner, events) { + this.owner = owner; + this.events = events; + }; + + /** + * Attaches a callback to the event subscription. + * @method then + * @param {function} callback The callback function to invoke when the event is triggered. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @chainable + */ + Subscription.prototype.then = function (callback, context) { + this.callback = callback || this.callback; + this.context = context || this.context; + + if (!this.callback) { + return this; + } + + this.owner.on(this.events, this.callback, this.context); + return this; + }; + + /** + * Attaches a callback to the event subscription. + * @method on + * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @chainable + */ + Subscription.prototype.on = Subscription.prototype.then; + + /** + * Cancels the subscription. + * @method off + * @chainable + */ + Subscription.prototype.off = function () { + this.owner.off(this.events, this.callback, this.context); + return this; + }; + + /** + * Creates an object with eventing capabilities. + * @class Events + */ + + /** + * Creates a subscription or registers a callback for the specified event. + * @method on + * @param {string} events One or more events, separated by white space. + * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, a subscription instance is returned. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @return {Subscription|Events} A subscription is returned if no callback is supplied, otherwise the events object is returned for chaining. + */ + Events.prototype.on = function(events, callback, context) { + var calls, event, list; + + if (!callback) { + return new Subscription(this, events); + } else { + calls = this.callbacks || (this.callbacks = {}); + events = events.split(eventSplitter); + + while (event = events.shift()) { + list = calls[event] || (calls[event] = []); + list.push(callback, context); + } + + return this; + } + }; + + /** + * Removes the callbacks for the specified events. + * @method off + * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. + * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. + * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. + * @chainable + */ + Events.prototype.off = function(events, callback, context) { + var event, calls, list, i; + + // No events + if (!(calls = this.callbacks)) { + return this; + } + + //removing all + if (!(events || callback || context)) { + delete this.callbacks; + return this; + } + + events = events ? events.split(eventSplitter) : system.keys(calls); + + // Loop through the callback list, splicing where appropriate. + while (event = events.shift()) { + if (!(list = calls[event]) || !(callback || context)) { + delete calls[event]; + continue; + } + + for (i = list.length - 2; i >= 0; i -= 2) { + if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) { + list.splice(i, 2); + } + } + } + + return this; + }; + + /** + * Triggers the specified events. + * @method trigger + * @param {string} [events] One or more events, separated by white space to trigger. + * @chainable + */ + Events.prototype.trigger = function(events) { + var event, calls, list, i, length, args, all, rest; + if (!(calls = this.callbacks)) { + return this; + } + + rest = []; + events = events.split(eventSplitter); + for (i = 1, length = arguments.length; i < length; i++) { + rest[i - 1] = arguments[i]; + } + + // For each event, walk through the list of callbacks twice, first to + // trigger the event, then to trigger any `"all"` callbacks. + while (event = events.shift()) { + // Copy callback lists to prevent modification. + if (all = calls.all) { + all = all.slice(); + } + + if (list = calls[event]) { + list = list.slice(); + } + + // Execute event callbacks. + if (list) { + for (i = 0, length = list.length; i < length; i += 2) { + list[i].apply(list[i + 1] || this, rest); + } + } + + // Execute "all" callbacks. + if (all) { + args = [event].concat(rest); + for (i = 0, length = all.length; i < length; i += 2) { + all[i].apply(all[i + 1] || this, args); + } + } + } + + return this; + }; + + /** + * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. + * @method proxy + * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. + * @return {function} Calling the function will invoke the previously specified events on the events object. + */ + Events.prototype.proxy = function(events) { + var that = this; + return (function(arg) { + that.trigger(events, arg); + }); + }; + + /** + * Creates an object with eventing capabilities. + * @class EventsModule + * @static + */ + + /** + * Adds eventing capabilities to the specified object. + * @method includeIn + * @param {object} targetObject The object to add eventing capabilities to. + */ + Events.includeIn = function(targetObject) { + targetObject.on = Events.prototype.on; + targetObject.off = Events.prototype.off; + targetObject.trigger = Events.prototype.trigger; + targetObject.proxy = Events.prototype.proxy; + }; + + return Events; +}); diff --git a/js/plugins/dialog.js b/js/plugins/dialog.js new file mode 100644 index 0000000..4a8e56a --- /dev/null +++ b/js/plugins/dialog.js @@ -0,0 +1,402 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The dialog module enables the display of message boxes, custom modal dialogs and other overlays or slide-out UI abstractions. Dialogs are constructed by the composition system which interacts with a user defined dialog context. The dialog module enforced the activator lifecycle. + * @module dialog + * @requires system + * @requires app + * @requires composition + * @requires activator + * @requires viewEngine + * @requires jquery + * @requires knockout + */ +define(['durandal/system', 'durandal/app', 'durandal/composition', 'durandal/activator', 'durandal/viewEngine', 'jquery', 'knockout'], function (system, app, composition, activator, viewEngine, $, ko) { + var contexts = {}, + dialogCount = 0, + dialog; + + /** + * Models a message box's message, title and options. + * @class MessageBox + */ + var MessageBox = function(message, title, options) { + this.message = message; + this.title = title || MessageBox.defaultTitle; + this.options = options || MessageBox.defaultOptions; + }; + + /** + * Selects an option and closes the message box, returning the selected option through the dialog system's promise. + * @method selectOption + * @param {string} dialogResult The result to select. + */ + MessageBox.prototype.selectOption = function (dialogResult) { + dialog.close(this, dialogResult); + }; + + /** + * Provides the view to the composition system. + * @method getView + * @return {DOMElement} The view of the message box. + */ + MessageBox.prototype.getView = function(){ + return viewEngine.processMarkup(MessageBox.defaultViewMarkup); + }; + + /** + * Configures a custom view to use when displaying message boxes. + * @method setViewUrl + * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view. + * @static + */ + MessageBox.setViewUrl = function(viewUrl){ + delete MessageBox.prototype.getView; + MessageBox.prototype.viewUrl = viewUrl; + }; + + /** + * The title to be used for the message box if one is not provided. + * @property {string} defaultTitle + * @default Application + * @static + */ + MessageBox.defaultTitle = app.title || 'Application'; + + /** + * The options to display in the message box of none are specified. + * @property {string[]} defaultOptions + * @default ['Ok'] + * @static + */ + MessageBox.defaultOptions = ['Ok']; + + /** + * The markup for the message box's view. + * @property {string} defaultViewMarkup + * @static + */ + MessageBox.defaultViewMarkup = [ + '
' + ].join('\n'); + + function ensureDialogInstance(objOrModuleId) { + return system.defer(function(dfd) { + if (system.isString(objOrModuleId)) { + system.acquire(objOrModuleId).then(function (module) { + dfd.resolve(system.resolveObject(module)); + }).fail(function(err){ + system.error('Failed to load dialog module (' + objOrModuleId + '). Details: ' + err.message); + }); + } else { + dfd.resolve(objOrModuleId); + } + }).promise(); + } + + /** + * @class DialogModule + * @static + */ + dialog = { + /** + * The constructor function used to create message boxes. + * @property {MessageBox} MessageBox + */ + MessageBox:MessageBox, + /** + * The css zIndex that the last dialog was displayed at. + * @property {number} currentZIndex + */ + currentZIndex: 1050, + /** + * Gets the next css zIndex at which a dialog should be displayed. + * @method getNextZIndex + * @return {number} The next usable zIndex. + */ + getNextZIndex: function () { + return ++this.currentZIndex; + }, + /** + * Determines whether or not there are any dialogs open. + * @method isOpen + * @return {boolean} True if a dialog is open. false otherwise. + */ + isOpen: function() { + return dialogCount > 0; + }, + /** + * Gets the dialog context by name or returns the default context if no name is specified. + * @method getContext + * @param {string} [name] The name of the context to retrieve. + * @return {DialogContext} True context. + */ + getContext: function(name) { + return contexts[name || 'default']; + }, + /** + * Adds (or replaces) a dialog context. + * @method addContext + * @param {string} name The name of the context to add. + * @param {DialogContext} dialogContext The context to add. + */ + addContext: function(name, dialogContext) { + dialogContext.name = name; + contexts[name] = dialogContext; + + var helperName = 'show' + name.substr(0, 1).toUpperCase() + name.substr(1); + this[helperName] = function (obj, activationData) { + return this.show(obj, activationData, name); + }; + }, + createCompositionSettings: function(obj, dialogContext) { + var settings = { + model:obj, + activate:false + }; + + if (dialogContext.attached) { + settings.attached = dialogContext.attached; + } + + if (dialogContext.compositionComplete) { + settings.compositionComplete = dialogContext.compositionComplete; + } + + return settings; + }, + /** + * Gets the dialog model that is associated with the specified object. + * @method getDialog + * @param {object} obj The object for whom to retrieve the dialog. + * @return {Dialog} The dialog model. + */ + getDialog:function(obj){ + if(obj){ + return obj.__dialog__; + } + + return undefined; + }, + /** + * Closes the dialog associated with the specified object. + * @method close + * @param {object} obj The object whose dialog should be closed. + * @param {object} result* The results to return back to the dialog caller after closing. + */ + close:function(obj){ + var theDialog = this.getDialog(obj); + if(theDialog){ + var rest = Array.prototype.slice.call(arguments, 1); + theDialog.close.apply(theDialog, rest); + } + }, + /** + * Shows a dialog. + * @method show + * @param {object|string} obj The object (or moduleId) to display as a dialog. + * @param {object} [activationData] The data that should be passed to the object upon activation. + * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. + * @return {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. + */ + show: function(obj, activationData, context) { + var that = this; + var dialogContext = contexts[context || 'default']; + + return system.defer(function(dfd) { + ensureDialogInstance(obj).then(function(instance) { + var dialogActivator = activator.create(); + + dialogActivator.activateItem(instance, activationData).then(function (success) { + if (success) { + var theDialog = instance.__dialog__ = { + owner: instance, + context: dialogContext, + activator: dialogActivator, + close: function () { + var args = arguments; + dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) { + if (closeSuccess) { + dialogCount--; + dialogContext.removeHost(theDialog); + delete instance.__dialog__; + + if(args.length == 0){ + dfd.resolve(); + }else if(args.length == 1){ + dfd.resolve(args[0]) + }else{ + dfd.resolve.apply(dfd, args); + } + } + }); + } + }; + + theDialog.settings = that.createCompositionSettings(instance, dialogContext); + dialogContext.addHost(theDialog); + + dialogCount++; + composition.compose(theDialog.host, theDialog.settings); + } else { + dfd.resolve(false); + } + }); + }); + }).promise(); + }, + /** + * Shows a message box. + * @method showMessage + * @param {string} message The message to display in the dialog. + * @param {string} [title] The title message. + * @param {string[]} [options] The options to provide to the user. + * @return {Promise} A promise that resolves when the message box is closed and returns the selected option. + */ + showMessage:function(message, title, options){ + if(system.isString(this.MessageBox)){ + return dialog.show(this.MessageBox, [ + message, + title || MessageBox.defaultTitle, + options || MessageBox.defaultOptions + ]); + } + + return dialog.show(new this.MessageBox(message, title, options)); + }, + /** + * Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods. + * @method install + * @param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box. + */ + install:function(config){ + app.showDialog = function(obj, activationData, context) { + return dialog.show(obj, activationData, context); + }; + + app.showMessage = function(message, title, options) { + return dialog.showMessage(message, title, options); + }; + + if(config.messageBox){ + dialog.MessageBox = config.messageBox; + } + + if(config.messageBoxView){ + dialog.MessageBox.prototype.getView = function(){ + return config.messageBoxView; + }; + } + } + }; + + /** + * @class DialogContext + */ + dialog.addContext('default', { + blockoutOpacity: .2, + removeDelay: 200, + /** + * In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module. + * @method addHost + * @param {Dialog} theDialog The dialog model. + */ + addHost: function(theDialog) { + var body = $('body'); + var blockout = $('') + .css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity }) + .appendTo(body); + + var host = $('') + .css({ 'z-index': dialog.getNextZIndex() }) + .appendTo(body); + + theDialog.host = host.get(0); + theDialog.blockout = blockout.get(0); + + if (!dialog.isOpen()) { + theDialog.oldBodyMarginRight = body.css("margin-right"); + theDialog.oldInlineMarginRight = body.get(0).style.marginRight; + + var html = $("html"); + var oldBodyOuterWidth = body.outerWidth(true); + var oldScrollTop = html.scrollTop(); + $("html").css("overflow-y", "hidden"); + var newBodyOuterWidth = $("body").outerWidth(true); + body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight)) + "px"); + html.scrollTop(oldScrollTop); // necessary for Firefox + } + }, + /** + * This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup. + * @method removeHost + * @param {Dialog} theDialog The dialog model. + */ + removeHost: function(theDialog) { + $(theDialog.host).css('opacity', 0); + $(theDialog.blockout).css('opacity', 0); + + setTimeout(function() { + ko.removeNode(theDialog.host); + ko.removeNode(theDialog.blockout); + }, this.removeDelay); + + if (!dialog.isOpen()) { + var html = $("html"); + var oldScrollTop = html.scrollTop(); // necessary for Firefox. + html.css("overflow-y", "").scrollTop(oldScrollTop); + + if(theDialog.oldInlineMarginRight) { + $("body").css("margin-right", theDialog.oldBodyMarginRight); + } else { + $("body").css("margin-right", ''); + } + } + }, + /** + * This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model. + * @method compositionComplete + * @param {DOMElement} child The dialog view. + * @param {DOMElement} parent The parent view. + * @param {object} context The composition context. + */ + compositionComplete: function (child, parent, context) { + var $child = $(child); + var width = $child.width(); + var height = $child.height(); + var theDialog = dialog.getDialog(context.model); + + $child.css({ + 'margin-top': (-height / 2).toString() + 'px', + 'margin-left': (-width / 2).toString() + 'px' + }); + + $(theDialog.host).css('opacity', 1); + + if ($(child).hasClass('autoclose')) { + $(theDialog.blockout).click(function() { + theDialog.close(); + }); + } + + $('.autofocus', child).each(function() { + $(this).focus(); + }); + } + }); + + return dialog; +}); diff --git a/js/plugins/history.js b/js/plugins/history.js new file mode 100644 index 0000000..ec5c751 --- /dev/null +++ b/js/plugins/history.js @@ -0,0 +1,321 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * This module is based on Backbone's core history support. It abstracts away the low level details of working with browser history and url changes in order to provide a solid foundation for a router. + * @module history + * @requires system + * @requires jquery + */ +define(['durandal/system', 'jquery'], function (system, $) { + // Cached regex for stripping a leading hash/slash and trailing space. + var routeStripper = /^[#\/]|\s+$/g; + + // Cached regex for stripping leading and trailing slashes. + var rootStripper = /^\/+|\/+$/g; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Cached regex for removing a trailing slash. + var trailingSlash = /\/$/; + + // Update the hash location, either replacing the current entry, or adding + // a new one to the browser history. + function updateHash(location, fragment, replace) { + if (replace) { + var href = location.href.replace(/(javascript:|#).*$/, ''); + location.replace(href + '#' + fragment); + } else { + // Some browsers require that `hash` contains a leading #. + location.hash = '#' + fragment; + } + }; + + /** + * @class HistoryModule + * @static + */ + var history = { + /** + * The setTimeout interval used when the browser does not support hash change events. + * @property {string} interval + * @default 50 + */ + interval: 50, + /** + * Indicates whether or not the history module is actively tracking history. + * @property {string} active + */ + active: false + }; + + // Ensure that `History` can be used outside of the browser. + if (typeof window !== 'undefined') { + history.location = window.location; + history.history = window.history; + } + + /** + * Gets the true hash value. Cannot use location.hash directly due to a bug in Firefox where location.hash will always be decoded. + * @method getHash + * @param {string} [window] The optional window instance + * @return {string} The hash. + */ + history.getHash = function(window) { + var match = (window || history).location.href.match(/#(.*)$/); + return match ? match[1] : ''; + }; + + /** + * Get the cross-browser normalized URL fragment, either from the URL, the hash, or the override. + * @method getFragment + * @param {string} fragment The fragment. + * @param {boolean} forcePushState Should we force push state? + * @return {string} he fragment. + */ + history.getFragment = function(fragment, forcePushState) { + if (fragment == null) { + if (history._hasPushState || !history._wantsHashChange || forcePushState) { + fragment = history.location.pathname; + var root = history.root.replace(trailingSlash, ''); + if (!fragment.indexOf(root)) { + fragment = fragment.substr(root.length); + } + } else { + fragment = history.getHash(); + } + } + + return fragment.replace(routeStripper, ''); + }; + + /** + * Activate the hash change handling, returning `true` if the current URL matches an existing route, and `false` otherwise. + * @method activate + * @param {HistoryOptions} options. + * @return {boolean|undefined} Returns true/false from loading the url unless the silent option was selected. + */ + history.activate = function(options) { + if (history.active) { + system.error("History has already been activated."); + } + + history.active = true; + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + history.options = system.extend({}, { root: '/' }, history.options, options); + history.root = history.options.root; + history._wantsHashChange = history.options.hashChange !== false; + history._wantsPushState = !!history.options.pushState; + history._hasPushState = !!(history.options.pushState && history.history && history.history.pushState); + + var fragment = history.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + + // Normalize root to always include a leading and trailing slash. + history.root = ('/' + history.root + '/').replace(rootStripper, '/'); + + if (oldIE && history._wantsHashChange) { + history.iframe = $('').hide().appendTo('body')[0].contentWindow; + history.navigate(fragment, false); + } + + // Depending on whether we're using pushState or hashes, and whether + // 'onhashchange' is supported, determine how we check the URL state. + if (history._hasPushState) { + $(window).on('popstate', history.checkUrl); + } else if (history._wantsHashChange && ('onhashchange' in window) && !oldIE) { + $(window).on('hashchange', history.checkUrl); + } else if (history._wantsHashChange) { + history._checkUrlInterval = setInterval(history.checkUrl, history.interval); + } + + // Determine if we need to change the base url, for a pushState link + // opened by a non-pushState browser. + history.fragment = fragment; + var loc = history.location; + var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === history.root; + + // Transition from hashChange to pushState or vice versa if both are requested. + if (history._wantsHashChange && history._wantsPushState) { + // If we've started off with a route from a `pushState`-enabled + // browser, but we're currently in a browser that doesn't support it... + if (!history._hasPushState && !atRoot) { + history.fragment = history.getFragment(null, true); + history.location.replace(history.root + history.location.search + '#' + history.fragment); + // Return immediately as browser will do redirect to new url + return true; + + // Or if we've started out with a hash-based route, but we're currently + // in a browser where it could be `pushState`-based instead... + } else if (history._hasPushState && atRoot && loc.hash) { + this.fragment = history.getHash().replace(routeStripper, ''); + this.history.replaceState({}, document.title, history.root + history.fragment + loc.search); + } + } + + if (!history.options.silent) { + return history.loadUrl(); + } + }; + + /** + * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. + * @method deactivate + */ + history.deactivate = function() { + $(window).off('popstate', history.checkUrl).off('hashchange', history.checkUrl); + clearInterval(history._checkUrlInterval); + history.active = false; + }; + + /** + * Checks the current URL to see if it has changed, and if it has, calls `loadUrl`, normalizing across the hidden iframe. + * @method checkUrl + * @return {boolean} Returns true/false from loading the url. + */ + history.checkUrl = function() { + var current = history.getFragment(); + if (current === history.fragment && history.iframe) { + current = history.getFragment(history.getHash(history.iframe)); + } + + if (current === history.fragment) { + return false; + } + + if (history.iframe) { + history.navigate(current, false); + } + + history.loadUrl(); + }; + + /** + * Attempts to load the current URL fragment. A pass-through to options.routeHandler. + * @method loadUrl + * @return {boolean} Returns true/false from the route handler. + */ + history.loadUrl = function(fragmentOverride) { + var fragment = history.fragment = history.getFragment(fragmentOverride); + + return history.options.routeHandler ? + history.options.routeHandler(fragment) : + false; + }; + + /** + * Save a fragment into the hash history, or replace the URL state if the + * 'replace' option is passed. You are responsible for properly URL-encoding + * the fragment in advance. + * The options object can contain `trigger: false` if you wish to not have the + * route callback be fired, or `replace: true`, if + * you wish to modify the current URL without adding an entry to the history. + * @method navigate + * @param {string} fragment The url fragment to navigate to. + * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. + * @return {boolean} Returns true/false from loading the url. + */ + history.navigate = function(fragment, options) { + if (!history.active) { + return false; + } + + if(options === undefined) { + options = { + trigger: true + }; + }else if(system.isBoolean(options)) { + options = { + trigger: options + }; + } + + fragment = history.getFragment(fragment || ''); + + if (history.fragment === fragment) { + return; + } + + history.fragment = fragment; + var url = history.root + fragment; + + // If pushState is available, we use it to set the fragment as a real URL. + if (history._hasPushState) { + history.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + + // If hash changes haven't been explicitly disabled, update the hash + // fragment to store history. + } else if (history._wantsHashChange) { + updateHash(history.location, fragment, options.replace); + + if (history.iframe && (fragment !== history.getFragment(history.getHash(history.iframe)))) { + // Opening and closing the iframe tricks IE7 and earlier to push a + // history entry on hash-tag change. When replace is true, we don't + // want history. + if (!options.replace) { + history.iframe.document.open().close(); + } + + updateHash(history.iframe.location, fragment, options.replace); + } + + // If you've told us that you explicitly don't want fallback hashchange- + // based history, then `navigate` becomes a page refresh. + } else { + return history.location.assign(url); + } + + if (options.trigger) { + return history.loadUrl(fragment); + } + }; + + /** + * Navigates back in the browser history. + * @method navigateBack + */ + history.navigateBack = function() { + history.history.back(); + }; + + /** + * @class HistoryOptions + * @static + */ + + /** + * The function that will be called back when the fragment changes. + * @property {function} routeHandler + */ + + /** + * The url root used to extract the fragment when using push state. + * @property {string} root + */ + + /** + * Use hash change when present. + * @property {boolean} hashChange + * @default true + */ + + /** + * Use push state when present. + * @property {boolean} pushState + * @default false + */ + + /** + * Prevents loading of the current url when activating history. + * @property {boolean} silent + * @default false + */ + + return history; +}); diff --git a/js/plugins/http.js b/js/plugins/http.js new file mode 100644 index 0000000..8259a1b --- /dev/null +++ b/js/plugins/http.js @@ -0,0 +1,78 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Enables common http request scenarios. + * @module http + * @requires jquery + * @requires knockout + */ +define(['jquery', 'knockout'], function($, ko) { + /** + * @class HTTPModule + * @static + */ + return { + /** + * The name of the callback parameter to inject into jsonp requests by default. + * @property {string} callbackParam + * @default callback + */ + callbackParam:'callback', + /** + * Makes an HTTP GET request. + * @method get + * @param {string} url The url to send the get request to. + * @param {object} [query] An optional key/value object to transform into query string parameters. + * @return {Promise} A promise of the get response data. + */ + get:function(url, query) { + return $.ajax(url, { data: query }); + }, + /** + * Makes an JSONP request. + * @method jsonp + * @param {string} url The url to send the get request to. + * @param {object} [query] An optional key/value object to transform into query string parameters. + * @param {string} [callbackParam] The name of the callback parameter the api expects (overrides the default callbackParam). + * @return {Promise} A promise of the response data. + */ + jsonp: function (url, query, callbackParam) { + if (url.indexOf('=?') == -1) { + callbackParam = callbackParam || this.callbackParam; + + if (url.indexOf('?') == -1) { + url += '?'; + } else { + url += '&'; + } + + url += callbackParam + '=?'; + } + + return $.ajax({ + url: url, + dataType:'jsonp', + data:query + }); + }, + /** + * Makes an HTTP POST request. + * @method post + * @param {string} url The url to send the post request to. + * @param {object} data The data to post. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization. + * @return {Promise} A promise of the response data. + */ + post:function(url, data) { + return $.ajax({ + url: url, + data: ko.toJSON(data), + type: 'POST', + contentType: 'application/json', + dataType: 'json' + }); + } + }; +}); diff --git a/js/plugins/observable.js b/js/plugins/observable.js new file mode 100644 index 0000000..e1e3f03 --- /dev/null +++ b/js/plugins/observable.js @@ -0,0 +1,332 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Enables automatic observability of plain javascript object for ES5 compatible browsers. Also, converts promise properties into observables that are updated when the promise resolves. + * @module observable + * @requires system + * @requires binder + * @requires knockout + */ +define(['durandal/system', 'durandal/binder', 'knockout'], function(system, binder, ko) { + var observableModule, + toString = Object.prototype.toString, + nonObservableTypes = ['[object Function]', '[object String]', '[object Boolean]', '[object Number]', '[object Date]', '[object RegExp]'], + observableArrayMethods = ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'], + arrayMethods = ['pop', 'reverse', 'sort', 'shift', 'splice'], + additiveArrayFunctions = ['push', 'unshift'], + arrayProto = Array.prototype, + observableArrayFunctions = ko.observableArray.fn, + logConversion = false; + + /** + * You can call observable(obj, propertyName) to get the observable function for the specified property on the object. + * @class ObservableModule + */ + + function shouldIgnorePropertyName(propertyName){ + var first = propertyName[0]; + return first === '_' || first === '$'; + } + + function canConvertType(value) { + if (!value || system.isElement(value) || value.ko === ko || value.jquery) { + return false; + } + + var type = toString.call(value); + + return nonObservableTypes.indexOf(type) == -1 && !(value === true || value === false); + } + + function makeObservableArray(original, observable) { + var lookup = original.__observable__, notify = true; + + if(lookup && lookup.__full__){ + return; + } + + lookup = lookup || (original.__observable__ = {}); + lookup.__full__ = true; + + observableArrayMethods.forEach(function(methodName) { + original[methodName] = function() { + notify = false; + var methodCallResult = observableArrayFunctions[methodName].apply(observable, arguments); + notify = true; + return methodCallResult; + }; + }); + + arrayMethods.forEach(function(methodName) { + original[methodName] = function() { + if(notify){ + observable.valueWillMutate(); + } + + var methodCallResult = arrayProto[methodName].apply(original, arguments); + + if(notify){ + observable.valueHasMutated(); + } + + return methodCallResult; + }; + }); + + additiveArrayFunctions.forEach(function(methodName){ + original[methodName] = function() { + for (var i = 0, len = arguments.length; i < len; i++) { + convertObject(arguments[i]); + } + + if(notify){ + observable.valueWillMutate(); + } + + var methodCallResult = arrayProto[methodName].apply(original, arguments); + + if(notify){ + observable.valueHasMutated(); + } + + return methodCallResult; + }; + }); + + original['splice'] = function() { + for (var i = 2, len = arguments.length; i < len; i++) { + convertObject(arguments[i]); + } + + if(notify){ + observable.valueWillMutate(); + } + + var methodCallResult = arrayProto['splice'].apply(original, arguments); + + if(notify){ + observable.valueHasMutated(); + } + + return methodCallResult; + }; + + for (var i = 0, len = original.length; i < len; i++) { + convertObject(original[i]); + } + } + + /** + * Converts an entire object into an observable object by re-writing its attributes using ES5 getters and setters. Attributes beginning with '_' or '$' are ignored. + * @method convertObject + * @param {object} obj The target object to convert. + */ + function convertObject(obj){ + var lookup, value; + + if(!canConvertType(obj)){ + return; + } + + lookup = obj.__observable__; + + if(lookup && lookup.__full__){ + return; + } + + lookup = lookup || (obj.__observable__ = {}); + lookup.__full__ = true; + + if (system.isArray(obj)) { + var observable = ko.observableArray(obj); + makeObservableArray(obj, observable); + } else { + for (var propertyName in obj) { + if(shouldIgnorePropertyName(propertyName)){ + continue; + } + + if(!lookup[propertyName]){ + value = obj[propertyName]; + + if(!system.isFunction(value)){ + convertProperty(obj, propertyName, value); + } + } + } + } + + if(logConversion) { + system.log('Converted', obj); + } + } + + function innerSetter(observable, newValue, isArray) { + var val; + observable(newValue); + val = observable.peek(); + + //if this was originally an observableArray, then always check to see if we need to add/replace the array methods (if newValue was an entirely new array) + if (isArray) { + if (!val.destroyAll) { + //don't allow null, force to an empty array + if (!val) { + val = []; + observable(val); + } + + makeObservableArray(val, observable); + } + } else { + convertObject(val); + } + } + + /** + * Converts a normal property into an observable property using ES5 getters and setters. + * @method convertProperty + * @param {object} obj The target object on which the property to convert lives. + * @param {string} propertyName The name of the property to convert. + * @param {object} [original] The original value of the property. If not specified, it will be retrieved from the object. + * @return {KnockoutObservable} The underlying observable. + */ + function convertProperty(obj, propertyName, original){ + var observable, + isArray, + lookup = obj.__observable__ || (obj.__observable__ = {}); + + if(original === undefined){ + original = obj[propertyName]; + } + + if (system.isArray(original)) { + observable = ko.observableArray(original); + makeObservableArray(original, observable); + isArray = true; + } else if (typeof original == "function") { + if(ko.isObservable(original)){ + observable = original; + }else{ + return null; + } + } else if(system.isPromise(original)) { + observable = ko.observable(); + + original.then(function (result) { + if(system.isArray(result)) { + var oa = ko.observableArray(result); + makeObservableArray(result, oa); + result = oa; + } + + observable(result); + }); + } else { + observable = ko.observable(original); + convertObject(original); + } + + Object.defineProperty(obj, propertyName, { + configurable: true, + enumerable: true, + get: observable, + set: ko.isWriteableObservable(observable) ? (function (newValue) { + if (newValue && system.isPromise(newValue)) { + newValue.then(function (result) { + innerSetter(observable, result, system.isArray(result)); + }); + } else { + innerSetter(observable, newValue, isArray); + } + }) : undefined + }); + + lookup[propertyName] = observable; + return observable; + } + + /** + * Defines a computed property using ES5 getters and setters. + * @method defineProperty + * @param {object} obj The target object on which to create the property. + * @param {string} propertyName The name of the property to define. + * @param {function|object} evaluatorOrOptions The Knockout computed function or computed options object. + * @return {KnockoutComputed} The underlying computed observable. + */ + function defineProperty(obj, propertyName, evaluatorOrOptions) { + var ko = this, + computedOptions = { owner: obj, deferEvaluation: true }, + computed; + + if (typeof evaluatorOrOptions === 'function') { + computedOptions.read = evaluatorOrOptions; + } else { + if ('value' in evaluatorOrOptions) { + system.error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.'); + } + + if (typeof evaluatorOrOptions.get !== 'function') { + system.error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".'); + } + + computedOptions.read = evaluatorOrOptions.get; + computedOptions.write = evaluatorOrOptions.set; + } + + computed = ko.computed(computedOptions); + obj[propertyName] = computed; + + return convertProperty(obj, propertyName, computed); + } + + observableModule = function(obj, propertyName){ + var lookup, observable, value; + + if (!obj) { + return null; + } + + lookup = obj.__observable__; + if(lookup){ + observable = lookup[propertyName]; + if(observable){ + return observable; + } + } + + value = obj[propertyName]; + + if(ko.isObservable(value)){ + return value; + } + + return convertProperty(obj, propertyName, value); + }; + + observableModule.defineProperty = defineProperty; + observableModule.convertProperty = convertProperty; + observableModule.convertObject = convertObject; + + /** + * Installs the plugin into the view model binder's `beforeBind` hook so that objects are automatically converted before being bound. + * @method install + */ + observableModule.install = function(options) { + var original = binder.beforeBind; + + binder.binding = function(obj, view, instruction) { + if(instruction.applyBindings && !instruction.skipConversion){ + convertObject(obj); + } + + original(obj, view); + }; + + logConversion = options.logConversion; + }; + + return observableModule; +}); diff --git a/js/plugins/router.js b/js/plugins/router.js new file mode 100644 index 0000000..795ffe9 --- /dev/null +++ b/js/plugins/router.js @@ -0,0 +1,941 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Connects the history module's url and history tracking support to Durandal's activation and composition engine allowing you to easily build navigation-style applications. + * @module router + * @requires system + * @requires app + * @requires activator + * @requires events + * @requires composition + * @requires history + * @requires knockout + * @requires jquery + */ +define(['durandal/system', 'durandal/app', 'durandal/activator', 'durandal/events', 'durandal/composition', 'plugins/history', 'knockout', 'jquery'], function(system, app, activator, events, composition, history, ko, $) { + var optionalParam = /\((.*?)\)/g; + var namedParam = /(\(\?)?:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; + var startDeferred, rootRouter; + var trailingSlash = /\/$/; + + function routeStringToRegExp(routeString) { + routeString = routeString.replace(escapeRegExp, '\\$&') + .replace(optionalParam, '(?:$1)?') + .replace(namedParam, function(match, optional) { + return optional ? match : '([^\/]+)'; + }) + .replace(splatParam, '(.*?)'); + + return new RegExp('^' + routeString + '$'); + } + + function stripParametersFromRoute(route) { + var colonIndex = route.indexOf(':'); + var length = colonIndex > 0 ? colonIndex - 1 : route.length; + return route.substring(0, length); + } + + function hasChildRouter(instance) { + return instance.router && instance.router.loadUrl; + } + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + function compareArrays(first, second) { + if (!first || !second){ + return false; + } + + if (first.length != second.length) { + return false; + } + + for (var i = 0, len = first.length; i < len; i++) { + if (first[i] != second[i]) { + return false; + } + } + + return true; + } + + /** + * @class Router + * @uses Events + */ + + /** + * Triggered when the navigation logic has completed. + * @event router:navigation:complete + * @param {object} instance The activated instance. + * @param {object} instruction The routing instruction. + * @param {Router} router The router. + */ + + /** + * Triggered when the navigation has been cancelled. + * @event router:navigation:cancelled + * @param {object} instance The activated instance. + * @param {object} instruction The routing instruction. + * @param {Router} router The router. + */ + + /** + * Triggered right before a route is activated. + * @event router:route:activating + * @param {object} instance The activated instance. + * @param {object} instruction The routing instruction. + * @param {Router} router The router. + */ + + /** + * Triggered right before a route is configured. + * @event router:route:before-config + * @param {object} config The route config. + * @param {Router} router The router. + */ + + /** + * Triggered just after a route is configured. + * @event router:route:after-config + * @param {object} config The route config. + * @param {Router} router The router. + */ + + /** + * Triggered when the view for the activated instance is attached. + * @event router:navigation:attached + * @param {object} instance The activated instance. + * @param {object} instruction The routing instruction. + * @param {Router} router The router. + */ + + /** + * Triggered when the composition that the activated instance participates in is complete. + * @event router:navigation:composition-complete + * @param {object} instance The activated instance. + * @param {object} instruction The routing instruction. + * @param {Router} router The router. + */ + + /** + * Triggered when the router does not find a matching route. + * @event router:route:not-found + * @param {string} fragment The url fragment. + * @param {Router} router The router. + */ + + var createRouter = function() { + var queue = [], + isProcessing = ko.observable(false), + currentActivation, + currentInstruction, + activeItem = activator.create(); + + var router = { + /** + * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`. + * @property {object[]} handlers + */ + handlers: [], + /** + * The route configs that are registered. + * @property {object[]} routes + */ + routes: [], + /** + * The route configurations that have been designated as displayable in a nav ui (nav:true). + * @property {KnockoutObservableArray} navigationModel + */ + navigationModel: ko.observableArray([]), + /** + * The active item/screen based on the current navigation state. + * @property {Activator} activeItem + */ + activeItem: activeItem, + /** + * Indicates that the router (or a child router) is currently in the process of navigating. + * @property {KnockoutComputed} isNavigating + */ + isNavigating: ko.computed(function() { + var current = activeItem(); + var processing = isProcessing(); + var currentRouterIsProcesing = current + && current.router + && current.router != router + && current.router.isNavigating() ? true : false; + return processing || currentRouterIsProcesing; + }), + /** + * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing. + * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties. + * @property {KnockoutObservable} activeInstruction + */ + activeInstruction:ko.observable(null), + __router__:true + }; + + events.includeIn(router); + + activeItem.settings.areSameItem = function (currentItem, newItem, currentActivationData, newActivationData) { + if (currentItem == newItem) { + return compareArrays(currentActivationData, newActivationData); + } + + return false; + }; + + function completeNavigation(instance, instruction) { + system.log('Navigation Complete', instance, instruction); + + var fromModuleId = system.getModuleId(currentActivation); + if (fromModuleId) { + router.trigger('router:navigation:from:' + fromModuleId); + } + + currentActivation = instance; + currentInstruction = instruction; + + var toModuleId = system.getModuleId(currentActivation); + if (toModuleId) { + router.trigger('router:navigation:to:' + toModuleId); + } + + if (!hasChildRouter(instance)) { + router.updateDocumentTitle(instance, instruction); + } + + rootRouter.explicitNavigation = false; + rootRouter.navigatingBack = false; + router.trigger('router:navigation:complete', instance, instruction, router); + } + + function cancelNavigation(instance, instruction) { + system.log('Navigation Cancelled'); + + router.activeInstruction(currentInstruction); + + if (currentInstruction) { + router.navigate(currentInstruction.fragment, false); + } + + isProcessing(false); + rootRouter.explicitNavigation = false; + rootRouter.navigatingBack = false; + router.trigger('router:navigation:cancelled', instance, instruction, router); + } + + function redirect(url) { + system.log('Navigation Redirecting'); + + isProcessing(false); + rootRouter.explicitNavigation = false; + rootRouter.navigatingBack = false; + router.navigate(url, { trigger: true, replace: true }); + } + + function activateRoute(activator, instance, instruction) { + rootRouter.navigatingBack = !rootRouter.explicitNavigation && currentActivation != instruction.fragment; + router.trigger('router:route:activating', instance, instruction, router); + + activator.activateItem(instance, instruction.params).then(function(succeeded) { + if (succeeded) { + var previousActivation = currentActivation; + completeNavigation(instance, instruction); + + if (hasChildRouter(instance)) { + queueInstruction({ + router: instance.router, + fragment: instruction.fragment, + queryString: instruction.queryString + }); + } + + if (previousActivation == instance) { + router.attached(); + } + } else if(activator.settings.lifecycleData && activator.settings.lifecycleData.redirect){ + redirect(activator.settings.lifecycleData.redirect); + }else{ + cancelNavigation(instance, instruction); + } + + if (startDeferred) { + startDeferred.resolve(); + startDeferred = null; + } + }); + } + + /** + * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting. + * @method guardRoute + * @param {object} instance The module instance that is about to be activated by the router. + * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties. + * @return {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. + */ + function handleGuardedRoute(activator, instance, instruction) { + var resultOrPromise = router.guardRoute(instance, instruction); + if (resultOrPromise) { + if (resultOrPromise.then) { + resultOrPromise.then(function(result) { + if (result) { + if (system.isString(result)) { + redirect(result); + } else { + activateRoute(activator, instance, instruction); + } + } else { + cancelNavigation(instance, instruction); + } + }); + } else { + if (system.isString(resultOrPromise)) { + redirect(resultOrPromise); + } else { + activateRoute(activator, instance, instruction); + } + } + } else { + cancelNavigation(instance, instruction); + } + } + + function ensureActivation(activator, instance, instruction) { + if (router.guardRoute) { + handleGuardedRoute(activator, instance, instruction); + } else { + activateRoute(activator, instance, instruction); + } + } + + function canReuseCurrentActivation(instruction) { + return currentInstruction + && currentInstruction.config.moduleId == instruction.config.moduleId + && currentActivation + && ((currentActivation.canReuseForRoute && currentActivation.canReuseForRoute.apply(currentActivation, instruction.params)) + || (currentActivation.router && currentActivation.router.loadUrl)); + } + + function dequeueInstruction() { + if (isProcessing()) { + return; + } + + var instruction = queue.shift(); + queue = []; + + if (!instruction) { + return; + } + + if (instruction.router) { + var fullFragment = instruction.fragment; + if (instruction.queryString) { + fullFragment += "?" + instruction.queryString; + } + + instruction.router.loadUrl(fullFragment); + return; + } + + isProcessing(true); + router.activeInstruction(instruction); + + if (canReuseCurrentActivation(instruction)) { + ensureActivation(activator.create(), currentActivation, instruction); + } else { + system.acquire(instruction.config.moduleId).then(function(module) { + var instance = system.resolveObject(module); + ensureActivation(activeItem, instance, instruction); + }).fail(function(err){ + system.error('Failed to load routed module (' + instruction.config.moduleId + '). Details: ' + err.message); + }); + } + } + + function queueInstruction(instruction) { + queue.unshift(instruction); + dequeueInstruction(); + } + + // Given a route, and a URL fragment that it matches, return the array of + // extracted decoded parameters. Empty or unmatched parameters will be + // treated as `null` to normalize cross-browser behavior. + function createParams(routePattern, fragment, queryString) { + var params = routePattern.exec(fragment).slice(1); + + for (var i = 0; i < params.length; i++) { + var current = params[i]; + params[i] = current ? decodeURIComponent(current) : null; + } + + var queryParams = router.parseQueryString(queryString); + if (queryParams) { + params.push(queryParams); + } + + return { + params:params, + queryParams:queryParams + }; + } + + function configureRoute(config){ + router.trigger('router:route:before-config', config, router); + + if (!system.isRegExp(config)) { + config.title = config.title || router.convertRouteToTitle(config.route); + config.moduleId = config.moduleId || router.convertRouteToModuleId(config.route); + config.hash = config.hash || router.convertRouteToHash(config.route); + config.routePattern = routeStringToRegExp(config.route); + }else{ + config.routePattern = config.route; + } + + router.trigger('router:route:after-config', config, router); + + router.routes.push(config); + + router.route(config.routePattern, function(fragment, queryString) { + var paramInfo = createParams(config.routePattern, fragment, queryString); + queueInstruction({ + fragment: fragment, + queryString:queryString, + config: config, + params: paramInfo.params, + queryParams:paramInfo.queryParams + }); + }); + }; + + function mapRoute(config) { + if(system.isArray(config.route)){ + for(var i = 0, length = config.route.length; i < length; i++){ + var current = system.extend({}, config); + current.route = config.route[i]; + if(i > 0){ + delete current.nav; + } + configureRoute(current); + } + }else{ + configureRoute(config); + } + + return router; + } + + function addActiveFlag(config) { + if(config.isActive){ + return; + } + + config.isActive = ko.computed(function() { + var theItem = activeItem(); + return theItem && theItem.__moduleId__ == config.moduleId; + }); + } + + /** + * Parses a query string into an object. + * @method parseQueryString + * @param {string} queryString The query string to parse. + * @return {object} An object keyed according to the query string parameters. + */ + router.parseQueryString = function (queryString) { + var queryObject, pairs; + + if (!queryString) { + return null; + } + + pairs = queryString.split('&'); + + if (pairs.length == 0) { + return null; + } + + queryObject = {}; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + if (pair === '') { + continue; + } + + var parts = pair.split('='); + queryObject[parts[0]] = parts[1] && decodeURIComponent(parts[1].replace(/\+/g, ' ')); + } + + return queryObject; + }; + + /** + * Add a route to be tested when the url fragment changes. + * @method route + * @param {RegEx} routePattern The route pattern to test against. + * @param {function} callback The callback to execute when the route pattern is matched. + */ + router.route = function(routePattern, callback) { + router.handlers.push({ routePattern: routePattern, callback: callback }); + }; + + /** + * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`. + * @method loadUrl + * @param {string} fragment The URL fragment to find a match for. + * @return {boolean} True if a match was found, false otherwise. + */ + router.loadUrl = function(fragment) { + var handlers = router.handlers, + queryString = null, + coreFragment = fragment, + queryIndex = fragment.indexOf('?'); + + if (queryIndex != -1) { + coreFragment = fragment.substring(0, queryIndex); + queryString = fragment.substr(queryIndex + 1); + } + + if(router.relativeToParentRouter){ + var instruction = this.parent.activeInstruction(); + coreFragment = instruction.params.join('/'); + + if(coreFragment && coreFragment[0] == '/'){ + coreFragment = coreFragment.substr(1); + } + + if(!coreFragment){ + coreFragment = ''; + } + + coreFragment = coreFragment.replace('//', '/').replace('//', '/'); + } + + coreFragment = coreFragment.replace(trailingSlash, ''); + + for (var i = 0; i < handlers.length; i++) { + var current = handlers[i]; + if (current.routePattern.test(coreFragment)) { + current.callback(coreFragment, queryString); + return true; + } + } + + system.log('Route Not Found'); + router.trigger('router:route:not-found', fragment, router); + + if (currentInstruction) { + history.navigate(currentInstruction.fragment, { trigger:false, replace:true }); + } + + rootRouter.explicitNavigation = false; + rootRouter.navigatingBack = false; + + return false; + }; + + /** + * Updates the document title based on the activated module instance, the routing instruction and the app.title. + * @method updateDocumentTitle + * @param {object} instance The activated module. + * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config. + */ + router.updateDocumentTitle = function(instance, instruction) { + if (instruction.config.title) { + if (app.title) { + document.title = instruction.config.title + " | " + app.title; + } else { + document.title = instruction.config.title; + } + } else if (app.title) { + document.title = app.title; + } + }; + + /** + * Save a fragment into the hash history, or replace the URL state if the + * 'replace' option is passed. You are responsible for properly URL-encoding + * the fragment in advance. + * The options object can contain `trigger: false` if you wish to not have the + * route callback be fired, or `replace: true`, if + * you wish to modify the current URL without adding an entry to the history. + * @method navigate + * @param {string} fragment The url fragment to navigate to. + * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. + * @return {boolean} Returns true/false from loading the url. + */ + router.navigate = function(fragment, options) { + if(fragment && fragment.indexOf('://') != -1){ + window.location.href = fragment; + return true; + } + + rootRouter.explicitNavigation = true; + return history.navigate(fragment, options); + }; + + /** + * Navigates back in the browser history. + * @method navigateBack + */ + router.navigateBack = function() { + history.navigateBack(); + }; + + router.attached = function() { + setTimeout(function() { + isProcessing(false); + router.trigger('router:navigation:attached', currentActivation, currentInstruction, router); + dequeueInstruction(); + }, 10); + }; + + router.compositionComplete = function(){ + router.trigger('router:navigation:composition-complete', currentActivation, currentInstruction, router); + }; + + /** + * Converts a route to a hash suitable for binding to a link's href. + * @method convertRouteToHash + * @param {string} route + * @return {string} The hash. + */ + router.convertRouteToHash = function(route) { + if(router.relativeToParentRouter){ + var instruction = router.parent.activeInstruction(), + hash = instruction.config.hash + '/' + route; + + if(history._hasPushState){ + hash = '/' + hash; + } + + hash = hash.replace('//', '/').replace('//', '/'); + return hash; + } + + if(history._hasPushState){ + return route; + } + + return "#" + route; + }; + + /** + * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping. + * @method convertRouteToModuleId + * @param {string} route + * @return {string} The module id. + */ + router.convertRouteToModuleId = function(route) { + return stripParametersFromRoute(route); + }; + + /** + * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping. + * @method convertRouteToTitle + * @param {string} route + * @return {string} The title. + */ + router.convertRouteToTitle = function(route) { + var value = stripParametersFromRoute(route); + return value.substring(0, 1).toUpperCase() + value.substring(1); + }; + + /** + * Maps route patterns to modules. + * @method map + * @param {string|object|object[]} route A route, config or array of configs. + * @param {object} [config] The config for the specified route. + * @chainable + * @example + router.map([ + { route: '', title:'Home', moduleId: 'homeScreen', nav: true }, + { route: 'customer/:id', moduleId: 'customerDetails'} + ]); + */ + router.map = function(route, config) { + if (system.isArray(route)) { + for (var i = 0; i < route.length; i++) { + router.map(route[i]); + } + + return router; + } + + if (system.isString(route) || system.isRegExp(route)) { + if (!config) { + config = {}; + } else if (system.isString(config)) { + config = { moduleId: config }; + } + + config.route = route; + } else { + config = route; + } + + return mapRoute(config); + }; + + /** + * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property. + * @method buildNavigationModel + * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The defualt is 100. + * @chainable + */ + router.buildNavigationModel = function(defaultOrder) { + var nav = [], routes = router.routes; + defaultOrder = defaultOrder || 100; + + for (var i = 0; i < routes.length; i++) { + var current = routes[i]; + + if (current.nav) { + if (!system.isNumber(current.nav)) { + current.nav = defaultOrder; + } + + addActiveFlag(current); + nav.push(current); + } + } + + nav.sort(function(a, b) { return a.nav - b.nav; }); + router.navigationModel(nav); + + return router; + }; + + /** + * Configures how the router will handle unknown routes. + * @method mapUnknownRoutes + * @param {string|function} [config] If not supplied, then the router will map routes to modules with the same name. + * If a string is supplied, it represents the module id to route all unknown routes to. + * Finally, if config is a function, it will be called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there. + * @param {string} [replaceRoute] If config is a module id, then you can optionally provide a route to replace the url with. + * @chainable + */ + router.mapUnknownRoutes = function(config, replaceRoute) { + var catchAllRoute = "*catchall"; + var catchAllPattern = routeStringToRegExp(catchAllRoute); + + router.route(catchAllPattern, function (fragment, queryString) { + var paramInfo = createParams(catchAllPattern, fragment, queryString); + var instruction = { + fragment: fragment, + queryString: queryString, + config: { + route: catchAllRoute, + routePattern: catchAllPattern + }, + params: paramInfo.params, + queryParams: paramInfo.queryParams + }; + + if (!config) { + instruction.config.moduleId = fragment; + } else if (system.isString(config)) { + instruction.config.moduleId = config; + if(replaceRoute){ + history.navigate(replaceRoute, { trigger:false, replace:true }); + } + } else if (system.isFunction(config)) { + var result = config(instruction); + if (result && result.then) { + result.then(function() { + router.trigger('router:route:before-config', instruction.config, router); + router.trigger('router:route:after-config', instruction.config, router); + queueInstruction(instruction); + }); + return; + } + } else { + instruction.config = config; + instruction.config.route = catchAllRoute; + instruction.config.routePattern = catchAllPattern; + } + + router.trigger('router:route:before-config', instruction.config, router); + router.trigger('router:route:after-config', instruction.config, router); + queueInstruction(instruction); + }); + + return router; + }; + + /** + * Resets the router by removing handlers, routes, event handlers and previously configured options. + * @method reset + * @chainable + */ + router.reset = function() { + currentInstruction = currentActivation = undefined; + router.handlers = []; + router.routes = []; + router.off(); + delete router.options; + return router; + }; + + /** + * Makes all configured routes and/or module ids relative to a certain base url. + * @method makeRelative + * @param {string|object} settings If string, the value is used as the base for routes and module ids. If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route. + * @chainable + */ + router.makeRelative = function(settings){ + if(system.isString(settings)){ + settings = { + moduleId:settings, + route:settings + }; + } + + if(settings.moduleId && !endsWith(settings.moduleId, '/')){ + settings.moduleId += '/'; + } + + if(settings.route && !endsWith(settings.route, '/')){ + settings.route += '/'; + } + + if(settings.fromParent){ + router.relativeToParentRouter = true; + } + + router.on('router:route:before-config').then(function(config){ + if(settings.moduleId){ + config.moduleId = settings.moduleId + config.moduleId; + } + + if(settings.route){ + if(config.route === ''){ + config.route = settings.route.substring(0, settings.route.length - 1); + }else{ + config.route = settings.route + config.route; + } + } + }); + + return router; + }; + + /** + * Creates a child router. + * @method createChildRouter + * @return {Router} The child router. + */ + router.createChildRouter = function() { + var childRouter = createRouter(); + childRouter.parent = router; + return childRouter; + }; + + return router; + }; + + /** + * @class RouterModule + * @extends Router + * @static + */ + rootRouter = createRouter(); + rootRouter.explicitNavigation = false; + rootRouter.navigatingBack = false; + + /** + * Activates the router and the underlying history tracking mechanism. + * @method activate + * @return {Promise} A promise that resolves when the router is ready. + */ + rootRouter.activate = function(options) { + return system.defer(function(dfd) { + startDeferred = dfd; + rootRouter.options = system.extend({ routeHandler: rootRouter.loadUrl }, rootRouter.options, options); + + history.activate(rootRouter.options); + + if(history._hasPushState){ + var routes = rootRouter.routes, + i = routes.length; + + while(i--){ + var current = routes[i]; + current.hash = current.hash.replace('#', ''); + } + } + + $(document).delegate("a", 'click', function(evt){ + rootRouter.explicitNavigation = true; + + if(history._hasPushState){ + if(!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey){ + // Get the anchor href and protcol + var href = $(this).attr("href"); + var protocol = this.protocol + "//"; + + // Ensure the protocol is not part of URL, meaning its relative. + // Stop the event bubbling to ensure the link will not cause a page refresh. + if (!href || (href.charAt(0) !== "#" && href.slice(protocol.length) !== protocol)) { + evt.preventDefault(); + history.navigate(href); + } + } + } + }); + }).promise(); + }; + + /** + * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. + * @method deactivate + */ + rootRouter.deactivate = function() { + history.deactivate(); + }; + + /** + * Installs the router's custom ko binding handler. + * @method install + */ + rootRouter.install = function(){ + ko.bindingHandlers.router = { + init: function() { + return { controlsDescendantBindings: true }; + }, + update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var settings = ko.utils.unwrapObservable(valueAccessor()) || {}; + + if (settings.__router__) { + settings = { + model:settings.activeItem(), + attached:settings.attached, + compositionComplete:settings.compositionComplete, + activate: false + }; + } else { + var theRouter = ko.utils.unwrapObservable(settings.router || viewModel.router) || rootRouter; + settings.model = theRouter.activeItem(); + settings.attached = theRouter.attached; + settings.compositionComplete = theRouter.compositionComplete; + settings.activate = false; + } + + composition.compose(element, settings, bindingContext); + } + }; + + ko.virtualElements.allowedBindings.router = true; + }; + + return rootRouter; +}); diff --git a/js/plugins/serializer.js b/js/plugins/serializer.js new file mode 100644 index 0000000..7a00834 --- /dev/null +++ b/js/plugins/serializer.js @@ -0,0 +1,138 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Serializes and deserializes data to/from JSON. + * @module serializer + * @requires system + */ +define(['durandal/system'], function(system) { + /** + * @class SerializerModule + * @static + */ + return { + /** + * The name of the attribute that the serializer should use to identify an object's type. + * @property {string} typeAttribute + * @default type + */ + typeAttribute: 'type', + /** + * The amount of space to use for indentation when writing out JSON. + * @property {string|number} space + * @default undefined + */ + space:undefined, + /** + * The default replacer function used during serialization. By default properties starting with '_' or '$' are removed from the serialized object. + * @method replacer + * @param {string} key The object key to check. + * @param {object} value The object value to check. + * @return {object} The value to serialize. + */ + replacer: function(key, value) { + if(key){ + var first = key[0]; + if(first === '_' || first === '$'){ + return undefined; + } + } + + return value; + }, + /** + * Serializes the object. + * @method serialize + * @param {object} object The object to serialize. + * @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults. + * @return {string} The JSON string. + */ + serialize: function(object, settings) { + settings = (settings === undefined) ? {} : settings; + + if(system.isString(settings) || system.isNumber(settings)) { + settings = { space: settings }; + } + + return JSON.stringify(object, settings.replacer || this.replacer, settings.space || this.space); + }, + /** + * Gets the type id for an object instance, using the configured `typeAttribute`. + * @method getTypeId + * @param {object} object The object to serialize. + * @return {string} The type. + */ + getTypeId: function(object) { + if (object) { + return object[this.typeAttribute]; + } + + return undefined; + }, + /** + * Maps type ids to object constructor functions. Keys are type ids and values are functions. + * @property {object} typeMap. + */ + typeMap: {}, + /** + * Adds a type id/constructor function mampping to the `typeMap`. + * @method registerType + * @param {string} typeId The type id. + * @param {function} constructor The constructor. + */ + registerType: function() { + var first = arguments[0]; + + if (arguments.length == 1) { + var id = first[this.typeAttribute] || system.getModuleId(first); + this.typeMap[id] = first; + } else { + this.typeMap[first] = arguments[1]; + } + }, + /** + * The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping. + * @method reviver + * @param {string} key The attribute key. + * @param {object} value The object value associated with the key. + * @param {function} getTypeId A custom function used to get the type id from a value. + * @param {object} getConstructor A custom function used to get the constructor function associated with a type id. + * @return {object} The value. + */ + reviver: function(key, value, getTypeId, getConstructor) { + var typeId = getTypeId(value); + if (typeId) { + var ctor = getConstructor(typeId); + if (ctor) { + if (ctor.fromJSON) { + return ctor.fromJSON(value); + } + + return new ctor(value); + } + } + + return value; + }, + /** + * Deserialize the JSON. + * @method deserialize + * @param {string} text The JSON string. + * @param {object} [settings] Settings can specify a reviver, getTypeId function or getConstructor function. + * @return {object} The deserialized object. + */ + deserialize: function(text, settings) { + var that = this; + settings = settings || {}; + + var getTypeId = settings.getTypeId || function(object) { return that.getTypeId(object); }; + var getConstructor = settings.getConstructor || function(id) { return that.typeMap[id]; }; + var reviver = settings.reviver || function(key, value) { return that.reviver(key, value, getTypeId, getConstructor); }; + + return JSON.parse(text, reviver); + } + }; +}); diff --git a/js/plugins/widget.js b/js/plugins/widget.js new file mode 100644 index 0000000..61c6c5d --- /dev/null +++ b/js/plugins/widget.js @@ -0,0 +1,193 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * Layers the widget sugar on top of the composition system. + * @module widget + * @requires system + * @requires composition + * @requires jquery + * @requires knockout + */ +define(['durandal/system', 'durandal/composition', 'jquery', 'knockout'], function(system, composition, $, ko) { + var kindModuleMaps = {}, + kindViewMaps = {}, + bindableSettings = ['model', 'view', 'kind'], + widgetDataKey = 'durandal-widget-data'; + + function extractParts(element, settings){ + var data = ko.utils.domData.get(element, widgetDataKey); + + if(!data){ + data = { + parts:composition.cloneNodes(ko.virtualElements.childNodes(element)) + }; + + ko.virtualElements.emptyNode(element); + ko.utils.domData.set(element, widgetDataKey, data); + } + + settings.parts = data.parts; + } + + /** + * @class WidgetModule + * @static + */ + var widget = { + getSettings: function(valueAccessor) { + var settings = ko.utils.unwrapObservable(valueAccessor()) || {}; + + if (system.isString(settings)) { + return { kind: settings }; + } + + for (var attrName in settings) { + if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) { + settings[attrName] = ko.utils.unwrapObservable(settings[attrName]); + } else { + settings[attrName] = settings[attrName]; + } + } + + return settings; + }, + /** + * Creates a ko binding handler for the specified kind. + * @method registerKind + * @param {string} kind The kind to create a custom binding handler for. + */ + registerKind: function(kind) { + ko.bindingHandlers[kind] = { + init: function() { + return { controlsDescendantBindings: true }; + }, + update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var settings = widget.getSettings(valueAccessor); + settings.kind = kind; + extractParts(element, settings); + widget.create(element, settings, bindingContext, true); + } + }; + + ko.virtualElements.allowedBindings[kind] = true; + }, + /** + * Maps views and module to the kind identifier if a non-standard pattern is desired. + * @method mapKind + * @param {string} kind The kind name. + * @param {string} [viewId] The unconventional view id to map the kind to. + * @param {string} [moduleId] The unconventional module id to map the kind to. + */ + mapKind: function(kind, viewId, moduleId) { + if (viewId) { + kindViewMaps[kind] = viewId; + } + + if (moduleId) { + kindModuleMaps[kind] = moduleId; + } + }, + /** + * Maps a kind name to it's module id. First it looks up a custom mapped kind, then falls back to `convertKindToModulePath`. + * @method mapKindToModuleId + * @param {string} kind The kind name. + * @return {string} The module id. + */ + mapKindToModuleId: function(kind) { + return kindModuleMaps[kind] || widget.convertKindToModulePath(kind); + }, + /** + * Converts a kind name to it's module path. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`. + * @method convertKindToModulePath + * @param {string} kind The kind name. + * @return {string} The module path. + */ + convertKindToModulePath: function(kind) { + return 'widgets/' + kind + '/viewmodel'; + }, + /** + * Maps a kind name to it's view id. First it looks up a custom mapped kind, then falls back to `convertKindToViewPath`. + * @method mapKindToViewId + * @param {string} kind The kind name. + * @return {string} The view id. + */ + mapKindToViewId: function(kind) { + return kindViewMaps[kind] || widget.convertKindToViewPath(kind); + }, + /** + * Converts a kind name to it's view id. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`. + * @method convertKindToViewPath + * @param {string} kind The kind name. + * @return {string} The view id. + */ + convertKindToViewPath: function(kind) { + return 'widgets/' + kind + '/view'; + }, + createCompositionSettings: function(element, settings) { + if (!settings.model) { + settings.model = this.mapKindToModuleId(settings.kind); + } + + if (!settings.view) { + settings.view = this.mapKindToViewId(settings.kind); + } + + settings.preserveContext = true; + settings.activate = true; + settings.activationData = settings; + settings.mode = 'templated'; + + return settings; + }, + /** + * Creates a widget. + * @method create + * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the target element for the widget. + * @param {object} settings The widget settings. + * @param {object} [bindingContext] The current binding context. + */ + create: function(element, settings, bindingContext, fromBinding) { + if(!fromBinding){ + settings = widget.getSettings(function() { return settings; }, element); + } + + var compositionSettings = widget.createCompositionSettings(element, settings); + + composition.compose(element, compositionSettings, bindingContext); + }, + /** + * Installs the widget module by adding the widget binding handler and optionally registering kinds. + * @method install + * @param {object} config The module config. Add a `kinds` array with the names of widgets to automatically register. You can also specify a `bindingName` if you wish to use another name for the widget binding, such as "control" for example. + */ + install:function(config){ + config.bindingName = config.bindingName || 'widget'; + + if(config.kinds){ + var toRegister = config.kinds; + + for(var i = 0; i < toRegister.length; i++){ + widget.registerKind(toRegister[i]); + } + } + + ko.bindingHandlers[config.bindingName] = { + init: function() { + return { controlsDescendantBindings: true }; + }, + update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var settings = widget.getSettings(valueAccessor); + extractParts(element, settings); + widget.create(element, settings, bindingContext, true); + } + }; + + ko.virtualElements.allowedBindings[config.bindingName] = true; + } + }; + + return widget; +}); diff --git a/js/system.js b/js/system.js new file mode 100644 index 0000000..17c2c30 --- /dev/null +++ b/js/system.js @@ -0,0 +1,427 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The system module encapsulates the most basic features used by other modules. + * @module system + * @requires require + * @requires jquery + */ +define(['require', 'jquery'], function(require, $) { + var isDebugging = false, + nativeKeys = Object.keys, + hasOwnProperty = Object.prototype.hasOwnProperty, + toString = Object.prototype.toString, + system, + treatAsIE8 = false, + nativeIsArray = Array.isArray, + slice = Array.prototype.slice; + + //see http://patik.com/blog/complete-cross-browser-console-log/ + // Tell IE9 to use its built-in console + if (Function.prototype.bind && (typeof console === 'object' || typeof console === 'function') && typeof console.log == 'object') { + try { + ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'] + .forEach(function(method) { + console[method] = this.call(console[method], console); + }, Function.prototype.bind); + } catch (ex) { + treatAsIE8 = true; + } + } + + // callback for dojo's loader + // note: if you wish to use Durandal with dojo's AMD loader, + // currently you must fork the dojo source with the following + // dojo/dojo.js, line 1187, the last line of the finishExec() function: + // (add) signal("moduleLoaded", [module.result, module.mid]); + // an enhancement request has been submitted to dojo to make this + // a permanent change. To view the status of this request, visit: + // http://bugs.dojotoolkit.org/ticket/16727 + + if (require.on) { + require.on("moduleLoaded", function(module, mid) { + system.setModuleId(module, mid); + }); + } + + // callback for require.js loader + if (typeof requirejs !== 'undefined') { + requirejs.onResourceLoad = function(context, map, depArray) { + system.setModuleId(context.defined[map.id], map.id); + }; + } + + var noop = function() { }; + + var log = function() { + try { + // Modern browsers + if (typeof console != 'undefined' && typeof console.log == 'function') { + // Opera 11 + if (window.opera) { + var i = 0; + while (i < arguments.length) { + console.log('Item ' + (i + 1) + ': ' + arguments[i]); + i++; + } + } + // All other modern browsers + else if ((slice.call(arguments)).length == 1 && typeof slice.call(arguments)[0] == 'string') { + console.log((slice.call(arguments)).toString()); + } else { + console.log.apply(console, slice.call(arguments)); + } + } + // IE8 + else if ((!Function.prototype.bind || treatAsIE8) && typeof console != 'undefined' && typeof console.log == 'object') { + Function.prototype.call.call(console.log, console, slice.call(arguments)); + } + + // IE7 and lower, and other old browsers + } catch (ignore) { } + }; + + var logError = function(error) { + if(error instanceof Error){ + throw error; + } + + throw new Error(error); + }; + + /** + * @class SystemModule + * @static + */ + system = { + /** + * Durandal's version. + * @property {string} version + */ + version: "2.0.0", + /** + * A noop function. + * @method noop + */ + noop: noop, + /** + * Gets the module id for the specified object. + * @method getModuleId + * @param {object} obj The object whose module id you wish to determine. + * @return {string} The module id. + */ + getModuleId: function(obj) { + if (!obj) { + return null; + } + + if (typeof obj == 'function') { + return obj.prototype.__moduleId__; + } + + if (typeof obj == 'string') { + return null; + } + + return obj.__moduleId__; + }, + /** + * Sets the module id for the specified object. + * @method setModuleId + * @param {object} obj The object whose module id you wish to set. + * @param {string} id The id to set for the specified object. + */ + setModuleId: function(obj, id) { + if (!obj) { + return; + } + + if (typeof obj == 'function') { + obj.prototype.__moduleId__ = id; + return; + } + + if (typeof obj == 'string') { + return; + } + + obj.__moduleId__ = id; + }, + /** + * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned. + * @method resolveObject + * @param {object} module The module to use to get/create the default object for. + * @return {object} The default object for the module. + */ + resolveObject: function(module) { + if (system.isFunction(module)) { + return new module(); + } else { + return module; + } + }, + /** + * Gets/Sets whether or not Durandal is in debug mode. + * @method debug + * @param {boolean} [enable] Turns on/off debugging. + * @return {boolean} Whether or not Durandal is current debugging. + */ + debug: function(enable) { + if (arguments.length == 1) { + isDebugging = enable; + if (isDebugging) { + this.log = log; + this.error = logError; + this.log('Debug:Enabled'); + } else { + this.log('Debug:Disabled'); + this.log = noop; + this.error = noop; + } + } + + return isDebugging; + }, + /** + * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. + * @method log + * @param {object} info* The objects to log. + */ + log: noop, + /** + * Logs an error. + * @method error + * @param {string|Error} obj The error to report. + */ + error: noop, + /** + * Asserts a condition by throwing an error if the condition fails. + * @method assert + * @param {boolean} condition The condition to check. + * @param {string} message The message to report in the error if the condition check fails. + */ + assert: function (condition, message) { + if (!condition) { + system.error(new Error(message || 'Assert:Failed')); + } + }, + /** + * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. + * @method defer + * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. + * @return {Deferred} The deferred object. + */ + defer: function(action) { + return $.Deferred(action); + }, + /** + * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid). + * @method guid + * @return {string} The guid. + */ + guid: function() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); + }, + /** + * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function or an array of ids. If more than one or an array is passed, then the promise will resolve with an array of module instances. + * @method acquire + * @param {string|string[]} moduleId The id(s) of the modules to load. + * @return {Promise} A promise for the loaded module(s). + */ + acquire: function() { + var modules, + first = arguments[0], + arrayRequest = false; + + if(system.isArray(first)){ + modules = first; + arrayRequest = true; + }else{ + modules = slice.call(arguments, 0); + } + + return this.defer(function(dfd) { + require(modules, function() { + var args = arguments; + setTimeout(function() { + if(args.length > 1 || arrayRequest){ + dfd.resolve(slice.call(args, 0)); + }else{ + dfd.resolve(args[0]); + } + }, 1); + }, function(err){ + dfd.reject(err); + }); + }).promise(); + }, + /** + * Extends the first object with the properties of the following objects. + * @method extend + * @param {object} obj The target object to extend. + * @param {object} extension* Uses to extend the target object. + */ + extend: function(obj) { + var rest = slice.call(arguments, 1); + + for (var i = 0; i < rest.length; i++) { + var source = rest[i]; + + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + } + + return obj; + }, + /** + * Uses a setTimeout to wait the specified milliseconds. + * @method wait + * @param {number} milliseconds The number of milliseconds to wait. + * @return {Promise} + */ + wait: function(milliseconds) { + return system.defer(function(dfd) { + setTimeout(dfd.resolve, milliseconds); + }).promise(); + } + }; + + /** + * Gets all the owned keys of the specified object. + * @method keys + * @param {object} object The object whose owned keys should be returned. + * @return {string[]} The keys. + */ + system.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) { + throw new TypeError('Invalid object'); + } + + var keys = []; + + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) { + keys[keys.length] = key; + } + } + + return keys; + }; + + /** + * Determines if the specified object is an html element. + * @method isElement + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + system.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + /** + * Determines if the specified object is an array. + * @method isArray + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + system.isArray = nativeIsArray || function(obj) { + return toString.call(obj) == '[object Array]'; + }; + + /** + * Determines if the specified object is...an object. ie. Not an array, string, etc. + * @method isObject + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + system.isObject = function(obj) { + return obj === Object(obj); + }; + + /** + * Determines if the specified object is a boolean. + * @method isBoolean + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + system.isBoolean = function(obj) { + return typeof(obj) === "boolean"; + }; + + /** + * Determines if the specified object is a promise. + * @method isPromise + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + system.isPromise = function(obj) { + return obj && system.isFunction(obj.then); + }; + + /** + * Determines if the specified object is a function arguments object. + * @method isArguments + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + /** + * Determines if the specified object is a function. + * @method isFunction + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + /** + * Determines if the specified object is a string. + * @method isString + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + /** + * Determines if the specified object is a number. + * @method isNumber + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + /** + * Determines if the specified object is a date. + * @method isDate + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + /** + * Determines if the specified object is a boolean. + * @method isBoolean + * @param {object} object The object to check. + * @return {boolean} True if matches the type, false otherwise. + */ + + //isArguments, isFunction, isString, isNumber, isDate, isRegExp. + var isChecks = ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp']; + + function makeIsFunction(name) { + var value = '[object ' + name + ']'; + system['is' + name] = function(obj) { + return toString.call(obj) == value; + }; + } + + for (var i = 0; i < isChecks.length; i++) { + makeIsFunction(isChecks[i]); + } + + return system; +}); diff --git a/js/transitions/entrance.js b/js/transitions/entrance.js new file mode 100644 index 0000000..3d5e6e2 --- /dev/null +++ b/js/transitions/entrance.js @@ -0,0 +1,79 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The entrance transition module. + * @module entrance + * @requires system + * @requires composition + * @requires jquery + */ +define(['durandal/system', 'durandal/composition', 'jquery'], function(system, composition, $) { + var fadeOutDuration = 100; + var endValues = { + marginRight: 0, + marginLeft: 0, + opacity: 1 + }; + var clearValues = { + marginLeft: '', + marginRight: '', + opacity: '', + display: '' + }; + + /** + * @class EntranceModule + * @constructor + */ + var entrance = function(context) { + return system.defer(function(dfd) { + function endTransition() { + dfd.resolve(); + } + + function scrollIfNeeded() { + if (!context.keepScrollPosition) { + $(document).scrollTop(0); + } + } + + if (!context.child) { + $(context.activeView).fadeOut(fadeOutDuration, endTransition); + } else { + var duration = context.duration || 500; + var fadeOnly = !!context.fadeOnly; + + function startTransition() { + scrollIfNeeded(); + context.triggerAttach(); + + var startValues = { + marginLeft: fadeOnly ? '0' : '20px', + marginRight: fadeOnly ? '0' : '-20px', + opacity: 0, + display: 'block' + }; + + var $child = $(context.child); + + $child.css(startValues); + $child.animate(endValues, duration, 'swing', function () { + $child.css(clearValues); + endTransition(); + }); + } + + if (context.activeView) { + $(context.activeView).fadeOut(fadeOutDuration, startTransition); + } else { + startTransition(); + } + } + }).promise(); + }; + + return entrance; +}); diff --git a/js/viewEngine.js b/js/viewEngine.js new file mode 100644 index 0000000..a2dd397 --- /dev/null +++ b/js/viewEngine.js @@ -0,0 +1,159 @@ +/** + * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Available via the MIT license. + * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. + */ +/** + * The viewEngine module provides information to the viewLocator module which is used to locate the view's source file. The viewEngine also transforms a view id into a view instance. + * @module viewEngine + * @requires system + * @requires jquery + */ +define(['durandal/system', 'jquery'], function (system, $) { + var parseMarkup; + + if ($.parseHTML) { + parseMarkup = function (html) { + return $.parseHTML(html); + }; + } else { + parseMarkup = function (html) { + return $(html).get(); + }; + } + + /** + * @class ViewEngineModule + * @static + */ + return { + /** + * The file extension that view source files are expected to have. + * @property {string} viewExtension + * @default .html + */ + viewExtension: '.html', + /** + * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). + * @property {string} viewPlugin + * @default text + */ + viewPlugin: 'text', + /** + * Determines if the url is a url for a view, according to the view engine. + * @method isViewUrl + * @param {string} url The potential view url. + * @return {boolean} True if the url is a view url, false otherwise. + */ + isViewUrl: function (url) { + return url.indexOf(this.viewExtension, url.length - this.viewExtension.length) !== -1; + }, + /** + * Converts a view url into a view id. + * @method convertViewUrlToViewId + * @param {string} url The url to convert. + * @return {string} The view id. + */ + convertViewUrlToViewId: function (url) { + return url.substring(0, url.length - this.viewExtension.length); + }, + /** + * Converts a view id into a full RequireJS path. + * @method convertViewIdToRequirePath + * @param {string} viewId The view id to convert. + * @return {string} The require path. + */ + convertViewIdToRequirePath: function (viewId) { + return this.viewPlugin + '!' + viewId + this.viewExtension; + }, + /** + * Parses the view engine recognized markup and returns DOM elements. + * @method parseMarkup + * @param {string} markup The markup to parse. + * @return {DOMElement[]} The elements. + */ + parseMarkup: parseMarkup, + /** + * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`. + * @method processMarkup + * @param {string} markup The markup to process. + * @return {DOMElement} The view. + */ + processMarkup: function (markup) { + var allElements = this.parseMarkup(markup); + return this.ensureSingleElement(allElements); + }, + /** + * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped. + * @method ensureSingleElement + * @param {DOMElement[]} allElements The elements. + * @return {DOMElement} A single element. + */ + ensureSingleElement:function(allElements){ + if (allElements.length == 1) { + return allElements[0]; + } + + var withoutCommentsOrEmptyText = []; + + for (var i = 0; i < allElements.length; i++) { + var current = allElements[i]; + if (current.nodeType != 8) { + if (current.nodeType == 3) { + var result = /\S/.test(current.nodeValue); + if (!result) { + continue; + } + } + + withoutCommentsOrEmptyText.push(current); + } + } + + if (withoutCommentsOrEmptyText.length > 1) { + return $(withoutCommentsOrEmptyText).wrapAll('').parent().get(0); + } + + return withoutCommentsOrEmptyText[0]; + }, + /** + * Creates the view associated with the view id. + * @method createView + * @param {string} viewId The view id whose view should be created. + * @return {Promise} A promise of the view. + */ + createView: function(viewId) { + var that = this; + var requirePath = this.convertViewIdToRequirePath(viewId); + + return system.defer(function(dfd) { + system.acquire(requirePath).then(function(markup) { + var element = that.processMarkup(markup); + element.setAttribute('data-view', viewId); + dfd.resolve(element); + }).fail(function(err){ + that.createFallbackView(viewId, requirePath, err).then(function(element){ + element.setAttribute('data-view', viewId); + dfd.resolve(element); + }); + }); + }).promise(); + }, + /** + * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development. + * @method createFallbackView + * @param {string} viewId The view id whose view should be created. + * @param {string} requirePath The require path that was attempted. + * @param {Error} requirePath The error that was returned from the attempt to locate the default view. + * @return {Promise} A promise for the fallback view. + */ + createFallbackView: function (viewId, requirePath, err) { + var that = this, + message = 'View Not Found. Searched for "' + viewId + '" via path "' + requirePath + '".'; + + return system.defer(function(dfd) { + dfd.resolve(that.processMarkup('