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 = $('