diff --git a/app/assets/javascripts/angular/controllers/listen.js b/app/assets/javascripts/angular/controllers/listen.js index 3442e34f..3d410b66 100644 --- a/app/assets/javascripts/angular/controllers/listen.js +++ b/app/assets/javascripts/angular/controllers/listen.js @@ -4,11 +4,12 @@ * @param $scope * @param $resource * @param $routeParams - * @param AudioRecording * @param AudioEvent * @constructor + * @param Tag + * @param Media */ -function ListenCtrl($scope, $resource, $routeParams, AudioRecording, AudioEvent, Tag) { +function ListenCtrl($scope, $resource, $routeParams, Media, AudioEvent, Tag) { $scope.errorState = !GUID_REGEXP.test($routeParams.recordingId); @@ -19,57 +20,55 @@ function ListenCtrl($scope, $resource, $routeParams, AudioRecording, AudioEvent, else { var recordingId = $scope.recordingId = $routeParams.recordingId; - $scope.recording = AudioRecording.get($routeParams); - - // HACK: - $scope.recordingurl = "/media/" + recordingId + "_0_120_0_11025.mp3"; +// +// $scope.recording = AudioRecording.get($routeParams); +// +// // HACK: +// $scope.recordingurl = "/media/" + recordingId + "_0_120_0_11025.mp3"; +// +// +// var spectrogramResource = $resource('/media/:recordingId', {recordingId: '@recordingId'}, { +// get: { method: 'GET', params: {recordingId: '@recordingId'}, isArray: false } +// }); +// $scope.spectrogram = spectrogramResource.get($routeParams); +// +// // HACK: +// $scope.spectrogram.url = "/media/" + recordingId + "_0_120_0_11025_512_g.png" + "?" + angularCopies.toKeyValue($scope.authTokenParams()); - var spectrogramResource = $resource('/media/:recordingId', {recordingId: '@recordingId'}, { - get: { method: 'GET', params: {recordingId: '@recordingId'}, isArray: false } - }); - $scope.spectrogram = spectrogramResource.get($routeParams); + //$scope.model = $scope; - // HACK: - $scope.spectrogram.url = "/media/" + recordingId + "_0_120_0_11025_512_g.png" + "?" + angularCopies.toKeyValue($scope.authTokenParams()); - $scope.$on('event:auth-loginRequired', function () { - $scope.spectrogram.url = "/media/" + recordingId + "_0_120_0_11025_512_g.png" + "?" + angularCopies.toKeyValue($scope.authTokenParams()); - }); - $scope.$on('event:auth-loginConfirmed', function () { - $scope.spectrogram.url = "/media/" + recordingId + "_0_120_0_11025_512_g.png" + "?" + angularCopies.toKeyValue($scope.authTokenParams()); - }); + var formatPaths = function () { + if ($scope.media && $scope.media.hasOwnProperty('recordingId')) { + $scope.media.imageUrl = $scope.media.spectrogramBaseUrl.format($scope.media) + "?" + $scope.authTokenQuery(); + $scope.media.audioUrl = $scope.media.audioBaseUrl.format($scope.media) + "?" + $scope.authTokenQuery(); + } + }; + $scope.$on('event:auth-loginRequired', formatPaths); + $scope.$on('event:auth-loginConfirmed', formatPaths); + $scope.media = Media.get($routeParams, {}, + function mediaGetSuccess() { + // reformat url's + formatPaths(); + }, + function mediaGetFailure() { + throw "boo booos"; + }); - // var audioEventResource = $resource('/audio_events?by_audio_id=:recordingId', {recordingId: '@recordingId'}, { - // get: - // }); - $scope.audio_events = AudioEvent.query({by_audio_id: recordingId}); + // TODO: add time bounds + $scope.audioEvents = AudioEvent.query({byAudioId: recordingId}); - // HACK: - // this should be treated as readonly -// $scope.tags = [ -// {text: "HALLO!", type_of_tag: null, is_taxanomic: false, id: -1}, -// {text: "Koala", type_of_tag: "common_name", is_taxanomic: true, id: -2}, -// {text: "Corrus Ovvu", type_of_tag: "species_name", is_taxanomic: true, id: -3}, -// {text: "Cawwing", type_of_tag: "sounds_like", is_taxanomic: false, id: -4} -// ]; $scope.tags = Tag.query(); $scope.limits = { - time_min: 0.0, - time_max: 120.0, - freq_min: 0.0, - freq_max: 11025.0 + timeMin: 0.0, + timeMax: 120.0, + freqMin: 0.0, + freqMax: 11025.0 }; - $scope.selectedAnnotation = { - audio_event_tags: [-1], - start_time_seconds: 0.05, - end_time_seconds: 15.23, - low_frequency_hertz:1000, - high_frequency_hertz: 8753 - }; $scope.clearSelected = function() { $scope.selectedAnnotation = {}; @@ -79,8 +78,8 @@ function ListenCtrl($scope, $resource, $routeParams, AudioRecording, AudioEvent, var a = angular.copy(this.selectedAnnotation); // prep tags - a.audio_event_tags_attributes = a.audio_event_tags.map(function (v) {return {tag_id:v};}); - delete a.audio_event_tags + a.audio_event_tags_attributes = a.audioEventTags.map(function (v) {return {tag_id:v};}); + delete a.audioEventTtags a.audio_recording_id = recordingId; @@ -89,8 +88,8 @@ function ListenCtrl($scope, $resource, $routeParams, AudioRecording, AudioEvent, console.log("Annotation creation successful"); // now update tag-list - $scope.audio_events.push(response); - $scope.selected_Annotation = response; + $scope.audioEvents.push(response); + $scope.selectedAnnotation = response; }, function createAnnotationFailure(response, getResponseHeaders) { @@ -114,4 +113,4 @@ function ListenCtrl($scope, $resource, $routeParams, AudioRecording, AudioEvent, } } -ListenCtrl.$inject = ['$scope', '$resource', '$routeParams', 'AudioRecording', 'AudioEvent', 'Tag']; \ No newline at end of file +ListenCtrl.$inject = ['$scope', '$resource', '$routeParams', 'Media', 'AudioEvent', 'Tag']; \ No newline at end of file diff --git a/app/assets/javascripts/angular/directives/auth.js b/app/assets/javascripts/angular/directives/auth.js index c65266da..076c2244 100644 --- a/app/assets/javascripts/angular/directives/auth.js +++ b/app/assets/javascripts/angular/directives/auth.js @@ -17,11 +17,15 @@ angular.module('angular-auth', ['http-auth-interceptor']) login.hide(); scope.$on('event:auth-loginRequired', function () { + // TODO: add extra checks to stop multiple animations + if (login.is(':animated')) { // noop } else { + console.warn("sliding login window down"); login.slideDown('slow', function () { + main.hide(); }); } diff --git a/app/assets/javascripts/angular/directives/directives.js b/app/assets/javascripts/angular/directives/directives.js index f05debe4..0dc5a63c 100644 --- a/app/assets/javascripts/angular/directives/directives.js +++ b/app/assets/javascripts/angular/directives/directives.js @@ -93,6 +93,18 @@ bawds.directive('bawAnnotationViewer', function () { + function resizeOrMove(b, box) { + if (b.id === box.id) { + b.left = box.left; + b.top = box.top; + b.width = box.width; + b.height = box.height; + } + else { + throw "Box ids do not match on resizing or move event"; + } + } + return { restrict: 'AE', scope: { @@ -112,30 +124,45 @@ scope.$canvas = $($element.find(".annotation-viewer img + div")[0]); // init drawabox - scope.model.audio_events = scope.model.audio_events || []; + scope.model.audioEvents = scope.model.audioEvents || []; scope.model.selectedEvents = scope.model.selectedEvents || []; scope.$canvas.drawabox({ - "newBox": function(){ - console.log("newBox"); + "newBox": function (newBox) { + console.log("newBox", newBox); + + scope.model.audioEvents = newBox; }, - "boxSelected": function(){ - console.log("boxSelected") + "boxSelected": function (selectedBox) { + console.log("boxSelected", selectedBox); + + // support for multiple selections - remove the clear + scope.model.selectedEvents.length = 0; + scope.model.selectedEvents.shift(selectedBox); + }, + "boxResizing": function (box) { + console.log("boxResizing", box); + resizeOrMove(scope.model.selectedEvents[0], box); + }, - "boxResizing": function(){ - console.log("boxResizing") + "boxResized": function (box) { + console.log("boxResized", box); + resizeOrMove(scope.model.selectedEvents[0], box); }, - "boxResized": function(){ - console.log("boxResized") + "boxMoving": function (box) { + console.log("boxMoving"); + resizeOrMove(scope.model.selectedEvents[0], box); }, - "boxMoving": function(){ - console.log("boxMoving")} - , - "boxMoved": function(){ - console.log("boxMoved") + "boxMoved": function (box) { + console.log("boxMoved"); + resizeOrMove(scope.model.selectedEvents[0], box); }, - "boxDeleted": function(){ - console.log("boxDeleted") + "boxDeleted": function (deletedBox) { + console.log("boxDeleted"); + + // TODO: is this done by reference? does it even work?; + _(scope.model.audioEvents).reject(function(item){return item.id === deletedBox.id;}); + _(scope.model.selectedEvents).reject(function(item){return item.id === deletedBox.id;}); } }); diff --git a/app/assets/javascripts/angular/services/angularjs-rails-resource.js b/app/assets/javascripts/angular/services/angularjs-rails-resource.js new file mode 100644 index 00000000..bc806ea1 --- /dev/null +++ b/app/assets/javascripts/angular/services/angularjs-rails-resource.js @@ -0,0 +1,283 @@ +// Adapted from https://github.com/tpodom/angularjs-rails-resource/blob/master/vendor/assets/javascripts/angularjs/rails/resource.js + +// Copyright (c) 2012 Tommy Odom +// +// MIT License +// https://github.com/tpodom/angularjs-rails-resource + +//(function (undefined) { +//angular.module('rails', ['ng']); + +function transformObject(data, transform) { + var newKey; + + if (data && angular.isObject(data)) { + angular.forEach(data, function (value, key) { + newKey = transform(key); + + if (newKey !== key) { + data[newKey] = value; + delete data[key]; + } + + transformObject(value, transform); + }); + } +} + +function stampObject(object, value) { + if (angular.isObject(object)) { + try { + // mark this object as having been transformed + Object.defineProperty(object, "__railsJsonRenamer__", {configurable: true, value: value}) + } + catch (e) { + console.warn("Object.defineProperty failed in stampObject"); + } + return object; + } + else { + return object; + } +} + +function camelize(key) { + if (!angular.isString(key)) { + return key; + } + + // should this match more than word and digit characters? + return key.replace(/_[\w\d]/g, function (match, index, string) { + return index === 0 ? match : string.charAt(index + 1).toUpperCase(); + }); +} + +function underscore(key) { + if (!angular.isString(key)) { + return key; + } + + return key.replace(/[A-Z]/g, function (match, index) { + return index === 0 ? match : '_' + match.toLowerCase(); + }); +} + +angular.module('rails', []) + .factory('railsFieldRenamingTransformer', function () { + + return function railsFieldRenamingTransformer(data, headers) { + // TODO: add conditions + // probs only want to do this if headers contains app/json + // and only if object has a __railsJsonRenamer__ + // or if request is going to our server? + + transformObject(data, underscore); + + stampObject(data, "camelCased->underscore"); + + return data; + }; + }) + + .factory('railsFieldRenamingInterceptor', function () { + + + return function railsFieldRenamingInterceptor($injector) { + return (function (p) { + p.then(function(response) { + if ((response.headers()["content-type"] || "").indexOf("application/json") >= 0) { + transformObject(response.data, camelize); + + stampObject(response.data, "underscored->camelCased"); + } + + return response; + }); + return p; + }); + }; + }) + + .factory('railsRootWrappingTransformer', function () { + return function railsRootWrappingTransformer(data, resource) { + var result = {}; + result[angular.isArray(data) ? resource.rootPluralName : resource.rootName] = data; + return result; + }; + }) + + .factory('railsRootWrappingInterceptor', function () { + return function railsRootWrappingInterceptor(promise) { + var resource = promise.resource; + + if (!resource) { + return promise; + } + + return promise.then(function (response) { + if (response.data && response.data.hasOwnProperty(resource.rootName)) { + response.data = response.data[resource.rootName]; + } else if (response.data && response.data.hasOwnProperty(resource.rootPluralName)) { + response.data = response.data[resource.rootPluralName]; + } + + return response; + }); + }; + }) + +/** + * Configure the default $httpRequest + */ +.config(['$httpProvider','railsFieldRenamingTransformerProvider', 'railsFieldRenamingInterceptorProvider', function ($httpProvider, railsFieldRenamingTransformer, railsFieldRenamingInterceptor) { +// + // + $httpProvider.responseInterceptors.push( railsFieldRenamingInterceptor.$get()); + + $httpProvider.defaults.transformRequest.push(railsFieldRenamingInterceptor.$get()); +}]); + + + +// angular.module('rails').factory('railsResourceFactory', ['$http', '$q', '$injector', function ($http, $q, $injector) { +// +// function railsResourceFactory(config) { +// var transformers = config.requestTransformers || ['railsRootWrappingTransformer', 'railsFieldRenamingTransformer'], +// interceptors = config.responseInterceptors || ['railsFieldRenamingInterceptor', 'railsRootWrappingInterceptor']; +// +// function RailsResource(value) { +// angular.extend(this, value || {}); +// } +// +// RailsResource.url = config.url; +// RailsResource.rootName = config.name; +// RailsResource.rootPluralName = config.pluralName || config.name + 's'; +// RailsResource.httpConfig = config.httpConfig || {}; +// RailsResource.requestTransformers = []; +// RailsResource.responseInterceptors = []; +// RailsResource.defaultParams = config.defaultParams; +// +// // copied from $HttpProvider to support interceptors being dependency names or anonymous factory functions +// angular.forEach(interceptors, function (interceptor) { +// RailsResource.responseInterceptors.push( +// angular.isString(interceptor) +// ? $injector.get(interceptor) +// : $injector.invoke(interceptor) +// ); +// }); +// +// angular.forEach(transformers, function (transformer) { +// RailsResource.requestTransformers.push( +// angular.isString(transformer) +// ? $injector.get(transformer) +// : $injector.invoke(transformer) +// ); +// }); +// +// RailsResource.transformData = function (data) { +// angular.forEach(RailsResource.requestTransformers, function (transformer) { +// data = transformer(data, RailsResource); +// }); +// +// return data; +// }; +// +// RailsResource.callInterceptors = function (promise) { +// +// angular.forEach(RailsResource.responseInterceptors, function (interceptor) { +// promise.resource = RailsResource; +// promise = interceptor(promise); +// }); +// +// return promise; +// }; +// +// RailsResource.processResponse = function (promise) { +// promise = RailsResource.callInterceptors(promise); +// +// return promise.then(function (response) { +// var result; +// +// if (angular.isArray(response.data)) { +// result = []; +// +// angular.forEach(response.data, function (value) { +// result.push(new RailsResource(value)); +// }); +// } else if (angular.isObject(response.data)) { +// result = new RailsResource(response.data); +// } else { +// result = response.data; +// } +// +// return result; +// }); +// }; +// +// RailsResource.getHttpConfig = function (queryParams) { +// var config = angular.copy(RailsResource.httpConfig, {}); +// +// if (RailsResource.defaultParams) { +// config.params = RailsResource.defaultParams; +// } +// +// if (queryParams) { +// config.params = angular.extend(config.params || {}, queryParams); +// } +// +// return config; +// }; +// +// RailsResource.resourceUrl = function (id) { +// return RailsResource.url + '/' + id; +// }; +// +// RailsResource.query = function (queryParams) { +// return RailsResource.processResponse($http.get(RailsResource.url, RailsResource.getHttpConfig(queryParams))); +// }; +// +// RailsResource.get = function (id) { +// return RailsResource.processResponse($http.get(RailsResource.resourceUrl(id), RailsResource.getHttpConfig())); +// }; +// +// RailsResource.prototype.processResponse = function (promise) { +// promise = promise.then(function (response) { +// // store off the data in case something (like our root unwrapping) assigns data as a new object +// response.originalData = response.data; +// return response; +// }); +// +// promise = RailsResource.callInterceptors(promise); +// +// return promise.then(angular.bind(this, function (response) { +// // we may not have response data +// if (response.hasOwnProperty('data') && angular.isObject(response.data)) { +// angular.extend(this, response.data); +// } +// +// return this; +// })); +// }; +// +// RailsResource.prototype.create = function () { +// // clone so we can manipulate w/o modifying our instance +// var data = RailsResource.transformData(angular.copy(this, {})); +// return this.processResponse($http.post(RailsResource.url, data, RailsResource.getHttpConfig())); +// }; +// +// RailsResource.prototype.update = function () { +// // clone so we can manipulate w/o modifying our instance +// var data = RailsResource.transformData(angular.copy(this, {})); +// return this.processResponse($http.put(RailsResource.resourceUrl(this.id), data, RailsResource.getHttpConfig())); +// }; +// +// RailsResource.prototype.remove = RailsResource.prototype.delete = function (id) { +// return this.processResponse($http.delete(RailsResource.resourceUrl(this.id), RailsResource.getHttpConfig())); +// }; +// +// return RailsResource; +// } +// +// return railsResourceFactory; +// }]); +//}()); \ No newline at end of file diff --git a/app/assets/javascripts/angular/services/services.js b/app/assets/javascripts/angular/services/services.js index 7a81f077..204247b9 100644 --- a/app/assets/javascripts/angular/services/services.js +++ b/app/assets/javascripts/angular/services/services.js @@ -43,6 +43,18 @@ return $resource('/tags/:tagId', {tagId: '@tagId'}, {}); }); + bawss.factory('Media', function($resource){ + var mediaResource = $resource('/media/:recordingId', {recordingId: '@recordingId'}); + + // this is a read only service, remove unnecessary methods + delete mediaResource.save; + delete mediaResource.remove; + delete mediaResource.delete; + //delete mediaResource.update; + + return mediaResource; + }); + // authentication bawss.factory('Authenticator', ['$rootScope', 'authService', '$http', function($rootScope, authService, $http){ return { @@ -117,7 +129,7 @@ function openIdLogin(url) { var popPath = "/security/auth/open_id?openid_url=" + angularCopies.fixedEncodeURIComponent(url); popUpWindow(popPath, 700, 500, function(data) { - if (data.response === "ok") { + if (data && data.response === "ok") { Authenticator.loginSuccess(data); } else { diff --git a/app/assets/javascripts/app.js b/app/assets/javascripts/app.js index 140cde5e..de8a71ab 100644 --- a/app/assets/javascripts/app.js +++ b/app/assets/javascripts/app.js @@ -3,14 +3,22 @@ /* App Module */ // global definition -var bawApp = (function () { +//noinspection JSCheckFunctionSignatures +var bawApp = (function (undefined) { var exports = { }; - // Helper function - - + /** + * Helper function to add a bunch of common routes for a page + * @param resourceName + * @param singularResourceName + * @param id + * @param controllerMany + * @param controllerOne + * @param addManageView + * @return {*|Object} + */ function whenDefaults(resourceName, singularResourceName, id, controllerMany, controllerOne, addManageView) { var path = "/" + resourceName; var detailsPath = path + "/" + id; @@ -42,7 +50,8 @@ var bawApp = (function () { 'bawApp.filters', /* our filters.js */ 'baw.services', /* our services.js */ 'http-auth-interceptor', /* the auth module */ - 'angular-auth' /* the auth module */ + 'angular-auth', /* the auth module */ + 'rails' /* a module designed to rewrite object keys */ ]); app.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { @@ -83,17 +92,18 @@ var bawApp = (function () { when('/', {templateUrl: '/assets/home.html', controller: HomeCtrl}). when('/404', {controller: ErrorCtrl}). when('/404?path=:errorPath', {controller: ErrorCtrl}). - otherwise( - {redirectTo: function (params, location, search) { - return '/404?path=' + location; - } + otherwise({ + redirectTo: function (params, location, search) { + return '/404?path=' + location; + } }); // location config $locationProvider.html5Mode(true); + }]); + - }]); app.run(['$rootScope', '$location', '$route', '$http', function ($rootScope, $location, $route, $http) { exports.print = $rootScope.print = function () { @@ -155,10 +165,16 @@ var bawApp = (function () { $rootScope.authorisationToken = null; $rootScope.authTokenParams = function() { - return { - auth_token: $rootScope.authorisationToken - }; - } + if ($rootScope.authorisationToken) { + return { + auth_token: $rootScope.authorisationToken + }; + } + return {}; + }; + $rootScope.authTokenQuery = function() { + return angularCopies.toKeyValue($rootScope.authTokenParams()); + }; }]); diff --git a/app/assets/templates/annotation_viewer.html b/app/assets/templates/annotation_viewer.html index 44560e95..1171a6c1 100644 --- a/app/assets/templates/annotation_viewer.html +++ b/app/assets/templates/annotation_viewer.html @@ -5,7 +5,7 @@
- +
diff --git a/app/assets/templates/attributions.html b/app/assets/templates/attributions.html index 3d287c28..e40d6343 100644 --- a/app/assets/templates/attributions.html +++ b/app/assets/templates/attributions.html @@ -5,4 +5,59 @@

Attributions

  • - \ No newline at end of file + + + +// core-js / js-extensions / 100-String.format.js +//console.debug("begin string.toformat.js"); +/***** Begin String.format - MIT License ************************************ + +Copyright (c) 2009 - Michael J. Ryan (http://tracker1.info) + +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. + +=============================================================================== +Thanks for the inspiration - http://blairmitchelmore.com/javascript/string.format + +//inline arguments +String.format( +"some string with {0} and {1} injected using argument {{number}}", +'first value', +'second value' +); +returns: 'some string with first value and second value injected argument {number}' + +//single array +String.format( +"some string with {0} and {1} injected using array {{number}}", +[ 'first value', 'second value' ] +); +returns: 'some string with first value and second value injected using array {number}' + +//single object +String.format( +"some string with {first} and {second} value injected using {{propertyName}}", +{ +first:'first value', +second:'second value' +} +); +returns: 'some string with first value and second value injected using {propertyName}' + +******************************************************************************/ \ No newline at end of file diff --git a/app/assets/templates/home.html b/app/assets/templates/home.html index b7cbc04e..2a84fd2f 100644 --- a/app/assets/templates/home.html +++ b/app/assets/templates/home.html @@ -22,7 +22,4 @@

    Download annotations

    csv format.

    -

    - I am logged not in. -

    \ No newline at end of file diff --git a/app/assets/templates/listen.html b/app/assets/templates/listen.html index c8ad06fd..6596d40f 100644 --- a/app/assets/templates/listen.html +++ b/app/assets/templates/listen.html @@ -1,43 +1,37 @@
    - demo - demo + demo empty
    Something has gone wrong - can't load this page.
    -

    Listen

    +

    Listen

    -

    Listen and annotate.

    +

    Listen and annotate.

    -

    Spectrogram

    - +

    Spectrogram

    + -

    Audio Controls

    - +

    Audio Controls

    + -

    - Annotation edit -

    +

    + Annotation edit +

    \ No newline at end of file diff --git a/app/controllers/audio_events_controller.rb b/app/controllers/audio_events_controller.rb index b89ff3e7..b79a3649 100644 --- a/app/controllers/audio_events_controller.rb +++ b/app/controllers/audio_events_controller.rb @@ -2,7 +2,7 @@ class AudioEventsController < ApplicationController # GET /audio_events # GET /audio_events.json def index - if params[:by_audio_id] + if params[:byAudioId] return by_audio_id end @@ -16,7 +16,7 @@ def index def by_audio_id # TODO: check if quid - id = params[:by_audio_id] + id = params[:byAudioId] @audio_events = AudioEvent diff --git a/app/controllers/media_controller.rb b/app/controllers/media_controller.rb index 0e235962..9b1e0a0a 100644 --- a/app/controllers/media_controller.rb +++ b/app/controllers/media_controller.rb @@ -3,6 +3,17 @@ class MediaController < ApplicationController include FileCacher, Mime + AUDIO_COMPONENTS = ['recording_id', 'start_offset', 'end_offset', 'channel', 'sample_rate', 'audio_format'] + SPECTROGRAM_COMPONENTS = ['recording_id', 'start_offset', 'end_offset', 'channel', 'sample_rate', 'window', 'color', 'image_format'] + + + AUDIO_BASE_URL_CC = '/media/{%s}_{%s}_{%s}_{%s}_{%s}{%s}' % (AUDIO_COMPONENTS.map { |s| s.camelize :lower }) + SPECTROGRAM_BASE_URL_CC = '/media/{%s}_{%s}_{%s}_{%s}_{%s}_{%s}_{%s}{%s}' %(SPECTROGRAM_COMPONENTS.map { |s| s.camelize :lower }) + + AUDIO_BASE_URL_US = '/media/{%s}_{%s}_{%s}_{%s}_{%s}{%s}' % AUDIO_COMPONENTS + SPECTROGRAM_BASE_URL_US = '/media/{%s}_{%s}_{%s}_{%s}_{%s}_{%s}_{%s}{%s}' % SPECTROGRAM_COMPONENTS + + #respond_to :xml, :json, :html, :png, :ogg, :oga, :webm, :webma, :mp3 def index @@ -53,9 +64,9 @@ def item # if the format is a supported image format, locate a cached spectrogram or generate it, then stream it back. #if image_media_types.include? final_format_requested - recording = AudioRecording.find_by_uuid(@file_info[:id]) - @file_info[:date] = recording.recorded_date.strftime "%Y%m%d" - @file_info[:time] = recording.recorded_date.strftime "%H%M%S" + recording = AudioRecording.find_by_uuid(@file_info[:id]) + @file_info[:date] = recording.recorded_date.strftime "%Y%m%d" + @file_info[:time] = recording.recorded_date.strftime "%H%M%S" @file_info[:original_format] = Mime::Type.file_extension_of recording.media_type #@file_info[:requested_media_type] = final_format_requested #@file_info[:requested_extension] = requested_extension @@ -73,42 +84,59 @@ def item # respond with file info in requested format # channel should use the 0,1,2,4,8,... format + url_format_underscore = params["urlFormat"] == "underscore" + file_info_to_send = { - :start_offset => @file_info[:start_offset].blank? ? 0 : @file_info[:start_offset], - :end_offset => @file_info[:end_offset].blank? ? recording.duration_seconds : @file_info[:end_offset], - :original_duration => recording.duration_seconds, - :date => @file_info[:date], - :time => @file_info[:time], - :id => @file_info[:id], - :channel => @file_info[:channel].blank? ? 0 : @file_info[:channel], # default to mixing down to mono - :sample_rate => @file_info[:sample_rate].blank? ? recording.sample_rate_hertz : @file_info[:sample_rate], - :window => @file_info[:window], - :colour => @file_info[:colour], - :original_format => @file_info[:original_format], - :format => final_format_requested, - :info_url => "/media/#{@file_info[:id]}" + :start_offset => @file_info[:start_offset].blank? ? 0 : @file_info[:start_offset], + :end_offset => @file_info[:end_offset].blank? ? recording.duration_seconds : @file_info[:end_offset], + + #:original_duration => recording.duration_seconds, + #:date => @file_info[:date], + #:time => @file_info[:time], + #:original_format => @file_info[:original_format], + :original => recording, + + :recording_id => @file_info[:id], + + :channel => @file_info[:channel].blank? ? 0 : @file_info[:channel], # default to mixing down to mono + :sample_rate => @file_info[:sample_rate].blank? ? recording.sample_rate_hertz : @file_info[:sample_rate], + :window => @file_info[:window] || SharedSettings.settings[:cached_spectrogram_defaults][0][:window], + :color => @file_info[:colour] || SharedSettings.settings[:cached_spectrogram_defaults][0][:colour], + :audio_format => final_format_requested || SharedSettings.settings[:cached_audio_defaults][0][:format], + :image_format => SharedSettings.settings[:cached_spectrogram_defaults][0][:format], + + :info_url => "/media/#{@file_info[:id]}", + :audio_base_url => (url_format_underscore ? AUDIO_BASE_URL_US : AUDIO_BASE_URL_CC), + :spectrogram_base_url => (url_format_underscore ? SPECTROGRAM_BASE_URL_US : SPECTROGRAM_BASE_URL_CC) , + + :options => { + :colors => Spectrogram.colour_options, + :window_size => Spectrogram.window_options, + :audio_formats => audio_media_types.collect { |mt| mt.symbol }, + :image_formats => image_media_types.collect { |mt| mt.symbol }, + } } - unless file_info_to_send[:start_offset].nil? - base_audio_segment_url = "/media/#{file_info_to_send[:id]}_#{file_info_to_send[:start_offset]}_#{file_info_to_send[:end_offset]}_"+ - "#{file_info_to_send[:channel]}_#{file_info_to_send[:sample_rate]}." - - file_info_to_send[:audio_base_url] = base_audio_segment_url - end - - unless file_info_to_send[:window].nil? - file_info_to_send[:spectrogram_url] = - "/media/#{file_info_to_send[:id]}_#{file_info_to_send[:start_offset]}_#{file_info_to_send[:end_offset]}_"+ - "#{file_info_to_send[:channel]}_#{file_info_to_send[:sample_rate]}_"+ - "#{file_info_to_send[:window]}_#{file_info_to_send[:colour]}.png" - - file_info_to_send[:color_description] = Spectrogram.colour_options - - end + #unless file_info_to_send[:start_offset].nil? + # base_audio_segment_url = "/media/#{file_info_to_send[:id]}_#{file_info_to_send[:start_offset]}_#{file_info_to_send[:end_offset]}_"+ + # "#{file_info_to_send[:channel]}_#{file_info_to_send[:sample_rate]}." + # + # file_info_to_send[:audio_base_url] = base_audio_segment_url + #end + # + #unless file_info_to_send[:window].nil? + # file_info_to_send[:spectrogram_url] = + # "/media/#{file_info_to_send[:id]}_#{file_info_to_send[:start_offset]}_#{file_info_to_send[:end_offset]}_"+ + # "#{file_info_to_send[:channel]}_#{file_info_to_send[:sample_rate]}_"+ + # "#{file_info_to_send[:window]}_#{file_info_to_send[:colour]}.png" + # + # file_info_to_send[:color_description] = Spectrogram.colour_options + # + #end respond_to do |format| - format.any(:xml, :html) {render :xml => file_info_to_send} - format.json {render :json => file_info_to_send} + format.any(:xml, :html) { render :xml => file_info_to_send } + format.json { render :json => file_info_to_send } format.all { head :bad_request } end end @@ -128,7 +156,7 @@ def update return head(:bad_request) unless Rails.env == 'development' # iterate through all original audio folders, and check that the audio recordings there are in the database - Dir.glob("#{dir}/*").each_with_object({}) { |file, hash| } + Dir.glob("#{dir}/*").each_with_object({ }) { |file, hash| } end @@ -137,7 +165,7 @@ def update def read_dir(dir) # from http://stackoverflow.com/questions/6166103/traversing-directories-and-reading-from-files-in-ruby-on-rails - Dir.glob("#{dir}/*").each_with_object({}) do |f, h| + Dir.glob("#{dir}/*").each_with_object({ }) do |f, h| if File.file?(f) h[f] = open(f).read elsif File.directory?(f) diff --git a/lib/assets/javascripts/100-String.format.js b/lib/assets/javascripts/100-String.format.js new file mode 100644 index 00000000..84b3d41b --- /dev/null +++ b/lib/assets/javascripts/100-String.format.js @@ -0,0 +1,240 @@ +//console.debug("begin string.toformat.js"); +/***** Begin String.format - MIT License ************************************ + +Copyright (c) 2009 - Michael J. Ryan (http://tracker1.info) + +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. + +=============================================================================== +Thanks for the inspiration - http://blairmitchelmore.com/javascript/string.format + +//inline arguments +String.format( + "some string with {0} and {1} injected using argument {{number}}", + 'first value', + 'second value' +); +returns: 'some string with first value and second value injected argument {number}' + +//single array +String.format( + "some string with {0} and {1} injected using array {{number}}", + [ 'first value', 'second value' ] +); +returns: 'some string with first value and second value injected using array {number}' + +//single object +String.format( + "some string with {first} and {second} value injected using {{propertyName}}", + { + first:'first value', + second:'second value' + } +); +returns: 'some string with first value and second value injected using {propertyName}' + +******************************************************************************/ +(function() { + + //returns true for null, undefined and empty string + function isEmpty(obj) { + if (typeof obj == 'undefined' || obj === null || obj === '') return true; + if (typeof obj == 'number' && isNaN(obj)) return true; + if (obj instanceof Date && isNaN(Number(obj))) return true; + return false; + } + + //gets the format method to use for the object instance + // don't expose this method, it isn't safe for use outside this script + function getFormatter(obj) { + //it's a string, undefined or null, use default toString method + if (typeof obj == "string" || typeof obj == "undefined" || obj === null) { + return String.prototype.toString; + } + + //it has a format method + if (typeof obj.format == "function") { + return obj.format; + } + + //determin the constructor base & prototype to use + var ctor = function(o) { + if (typeof o == 'number') return Number; + if (typeof o == 'boolean') return Boolean; + return o.constructor; + }(obj); + var proto = ctor.prototype; + + //prototype has a format method use it (why was it overriden/deleted from the instance?) + if (proto && typeof proto.format == 'function') return ctor.prototype.format; + + //object has a toString method use it + if (typeof obj.toString == 'function') return obj.toString; + + //prototype has a toString method use it + if (proto && typeof proto.toString == 'function') return proto.toString; + + //use the string's toString method - final resort + return String.prototype.toString; + } + + + //convert an object to a string with an optional format to use + function stringFromAny(obj, format) { + //the object is nothing, use an empty string + if (isEmpty(obj)) + return ""; + + //get the formatter to use for the object + var formatter = getFormatter(obj); + + //a formatter was found, use it + if (formatter) { + if (isEmpty(format)) { + try { + return formatter.call(obj); + } catch(err) { + //errors with Microsoft Ajax Toolkit + try { + return formatter.call(obj,""); + } catch(err1) { + if (typeof console != "undefined") (console.error || console.log)(err1); + return ""; //unable to format + } + } + } else { + return formatter.call(obj,format); + } + } + else + return ""; //no formatter, use empty string, this should *NEVER* happen. + } + + + //basic format, used when a single, or no arguments are passed in + function basicFormat(source) { + //null argument, return empty string + if (isEmpty(source)) + return ""; + + //it's a string, return it as-is + if (typeof source == "string") + return String(source); + + //it has a formatter, use that + if (source && source.format) + return source.format(); + + //it's an array, use it as one - recursive call + if (source && source.length) + return String.format.apply(source[0], Array.prototype.slice.call(arguments, 0, 1)); + + //force it to a string + return String(source); + } + + //normalize arguments into parameter array + function setParams() { + var undef; //undefined value + + //remove first item from stack + var params = Array.prototype.slice.call(arguments, 1); + + //only one param + if (params.length == 1) { + //set the params to the instance of the one param + params = params[0]; + + //use an empty string for null and undefined valuse + if (params === null || params === undef) return ['']; + + //reference to the type of params + var t = typeof params; + + //if it (has format or not an object) and not an array) + if ((params.format || t != 'object') && t != 'array' ) + params = [ params ]; //put the param inside an array + } + + //return normalized input parameters + return params; + } + + function stringformat(source, params) { + //only one argument, force it to a proper string. + if ( arguments.length < 2 ) { + basicFormat(source); + } + + //normalize the input parameters + params = setParams.apply(null, arguments); + var outerLength = arguments.length; + + //run a replace method against the source string, matching against + // named/numbered parameters + // + // will match on escaped braces {{ or }} + // or an embedded code {code} with optional format {code:format} + var ret = source.replace( + /\{\{|\}\}|\{([^}: ]+?)(?::([^}]*?))?\}/g, + function(match, num, format) { + if (match == "{{") return "{"; //unescape the nested { + if (match == "}}") return "}"; //unescape the nested } + if (typeof params[num] == "undefined") { + //if there was only one parameter, and the match is "0", and there's no "0" in params, use the params as the binding formatter + //should fix "... {0:...}".toFormat(singleItem) + if (num === "0" && outerLength == 2) return stringFromAny(params, format); + + return match; //no param value available + } + + return stringFromAny(params[num], format); //convert the input replacement to a proper string + } + ); + return ret; + } + + //main string formatter + if (typeof String.format != "function") { + String.format = stringformat; + } + if (typeof String.asFormat != "function") { + String.asFormat = stringformat; + } + + + //create a format method for string instances + if (typeof String.prototype.format != "function") { + String.prototype.format = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return stringformat.apply(null, args); + }; + } + if (typeof String.prototype.asFormat != "function") { + String.prototype.asFormat = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return stringformat.apply(null, args); + }; + } + +})(); + +//console.debug("begin string.toformat.js"); \ No newline at end of file diff --git a/lib/assets/javascripts/angular-http-auth.js b/lib/assets/javascripts/angular-http-auth.js index 4cf57bec..afb7232c 100644 --- a/lib/assets/javascripts/angular-http-auth.js +++ b/lib/assets/javascripts/angular-http-auth.js @@ -41,7 +41,9 @@ angular.module('http-auth-interceptor', []) return { loginConfirmed: function() { - $rootScope.$broadcast('event:auth-loginConfirmed'); + console.info("authService::event:auth-loginConfirmed"); + $rootScope.$broadcast('event:auth-loginConfirmed'); + retryAll(); } } @@ -63,6 +65,8 @@ angular.module('http-auth-interceptor', []) if (response.status === 401) { var deferred = $q.defer(); authServiceProvider.pushToBuffer(response.config, deferred); + + console.info("authService::event:auth-loginRequired"); $rootScope.$broadcast('event:auth-loginRequired'); return deferred.promise; } diff --git a/lib/assets/javascripts/functions.js b/lib/assets/javascripts/functions.js index a20cdd50..f91e483a 100644 --- a/lib/assets/javascripts/functions.js +++ b/lib/assets/javascripts/functions.js @@ -1,19 +1,19 @@ -/** - * String format function - * http://www.isurinder.com/blog/post/2011/04/02/StringFormat-In-JavaScript.aspx#.UKWRyvgzpQs - * @type {Function} - */ -String.format = String.prototype.format = function() { - var i=0; - var string = (typeof(this) == "function" && !(i++)) ? arguments[0] : this; - - for (; i < arguments.length; i++){ - string = string.replace(/\{\d+?\}/, arguments[i]); - } - - return string; -}; +///** +// * String format function +// * http://www.isurinder.com/blog/post/2011/04/02/StringFormat-In-JavaScript.aspx#.UKWRyvgzpQs +// * @type {Function} +// */ +//String.format = String.prototype.format = function() { +// var i=0; +// var string = (typeof(this) == "function" && !(i++)) ? arguments[0] : this; +// +// for (; i < arguments.length; i++){ +// string = string.replace(/\{\d+?\}/, arguments[i]); +// } +// +// return string; +//}; /** * Generates a unique number for the page. Unique only for each refresh. @@ -47,6 +47,23 @@ function fluidIf(test, truthyAction, falseyAction){ } +function toType (obj) { + return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() +} + + +if(!Array.prototype.indexOf) { + Array.prototype.indexOf = function(what, i) { + i = i || 0; + var L = this.length; + while (i < L) { + if(this[i] === what) return i; + ++i; + } + return -1; + }; +} + /** * Is it a valid guid? * @type {RegExp} @@ -92,6 +109,7 @@ function popUpWindow(provider_url, width, height, callback) { var angularCopies = new (function Angular() { this.fixedEncodeURIComponent = function fixedEncodeURIComponent(str) { + str = str || ""; return encodeURIComponent(str) .replace(/!/g, '%21') .replace(/'/g, '%27') @@ -108,6 +126,7 @@ var angularCopies = new (function Angular() { return parts.length ? parts.join('&') : ''; }; function encodeUriQuery(val, pctEncodeSpaces) { + val = val || ""; return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). diff --git a/vendor/assets/javascripts/underscore/underscore.js b/vendor/assets/javascripts/underscore/underscore.js new file mode 100644 index 00000000..4d83099f --- /dev/null +++ b/vendor/assets/javascripts/underscore/underscore.js @@ -0,0 +1,1221 @@ +// Underscore.js 1.4.3 +// http://underscorejs.org +// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var push = ArrayProto.push, + slice = ArrayProto.slice, + concat = ArrayProto.concat, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object via a string identifier, + // for Closure Compiler "advanced" mode. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.4.3'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + if (iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + for (var key in obj) { + if (_.has(obj, key)) { + if (iterator.call(context, obj[key], key, obj) === breaker) return; + } + } + } + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = _.collect = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results[results.length] = iterator.call(context, value, index, list); + }); + return results; + }; + + var reduceError = 'Reduce of empty array with no initial value'; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var length = obj.length; + if (length !== +length) { + var keys = _.keys(obj); + length = keys.length; + } + each(obj, function(value, index, list) { + index = keys ? keys[--length] : --length; + if (!initial) { + memo = obj[index]; + initial = true; + } else { + memo = iterator.call(context, memo, obj[index], index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, iterator, context) { + var result; + any(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, iterator, context) { + return _.filter(obj, function(value, index, list) { + return !iterator.call(context, value, index, list); + }, context); + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); + each(obj, function(value, index, list) { + if (!(result = result && iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result || (result = iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if the array or object contains a given value (using `===`). + // Aliased as `include`. + _.contains = _.include = function(obj, target) { + if (obj == null) return false; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + return any(obj, function(value) { + return value === target; + }); + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + return _.map(obj, function(value) { + return (_.isFunction(method) ? method : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, function(value){ return value[key]; }); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // with specific `key:value` pairs. + _.where = function(obj, attrs) { + if (_.isEmpty(attrs)) return []; + return _.filter(obj, function(value) { + for (var key in attrs) { + if (attrs[key] !== value[key]) return false; + } + return true; + }); + }; + + // Return the maximum element or (element-based computation). + // Can't optimize arrays of integers longer than 65,535 elements. + // See: https://bugs.webkit.org/show_bug.cgi?id=80797 + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.max.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return -Infinity; + var result = {computed : -Infinity, value: -Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed >= result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.min.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return Infinity; + var result = {computed : Infinity, value: Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed < result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Shuffle an array. + _.shuffle = function(obj) { + var rand; + var index = 0; + var shuffled = []; + each(obj, function(value) { + rand = _.random(index++); + shuffled[index - 1] = shuffled[rand]; + shuffled[rand] = value; + }); + return shuffled; + }; + + // An internal function to generate lookup iterators. + var lookupIterator = function(value) { + return _.isFunction(value) ? value : function(obj){ return obj[value]; }; + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, value, context) { + var iterator = lookupIterator(value); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value : value, + index : index, + criteria : iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index < right.index ? -1 : 1; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(obj, value, context, behavior) { + var result = {}; + var iterator = lookupIterator(value || _.identity); + each(obj, function(value, index) { + var key = iterator.call(context, value, index, obj); + behavior(result, key, value); + }); + return result; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = function(obj, value, context) { + return group(obj, value, context, function(result, key, value) { + (_.has(result, key) ? result[key] : (result[key] = [])).push(value); + }); + }; + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = function(obj, value, context) { + return group(obj, value, context, function(result, key) { + if (!_.has(result, key)) result[key] = 0; + result[key]++; + }); + }; + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator, context) { + iterator = iterator == null ? _.identity : lookupIterator(iterator); + var value = iterator.call(context, obj); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >>> 1; + iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely convert anything iterable into a real, live array. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (obj.length === +obj.length) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. The **guard** check allows it to work with + // `_.map`. + _.initial = function(array, n, guard) { + return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. The **guard** check allows it to work with `_.map`. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if ((n != null) && !guard) { + return slice.call(array, Math.max(array.length - n, 0)); + } else { + return array[array.length - 1]; + } + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, (n == null) || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, output) { + each(input, function(value) { + if (_.isArray(value)) { + shallow ? push.apply(output, value) : flatten(value, shallow, output); + } else { + output.push(value); + } + }); + return output; + }; + + // Return a completely flattened version of an array. + _.flatten = function(array, shallow) { + return flatten(array, shallow, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iterator, context) { + if (_.isFunction(isSorted)) { + context = iterator; + iterator = isSorted; + isSorted = false; + } + var initial = iterator ? _.map(array, iterator, context) : array; + var results = []; + var seen = []; + each(initial, function(value, index) { + if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { + seen.push(value); + results.push(array[index]); + } + }); + return results; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(concat.apply(ArrayProto, arguments)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.indexOf(other, item) >= 0; + }); + }); + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); + return _.filter(array, function(value){ return !_.contains(rest, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var args = slice.call(arguments); + var length = _.max(_.pluck(args, 'length')); + var results = new Array(length); + for (var i = 0; i < length; i++) { + results[i] = _.pluck(args, "" + i); + } + return results; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + if (list == null) return {}; + var result = {}; + for (var i = 0, l = list.length; i < l; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i = 0, l = array.length; + if (isSorted) { + if (typeof isSorted == 'number') { + i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); + } else { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); + for (; i < l; i++) if (array[i] === item) return i; + return -1; + }; + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item, from) { + if (array == null) return -1; + var hasIndex = from != null; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { + return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); + } + var i = (hasIndex ? from : array.length); + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var len = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(len); + + while(idx < len) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Reusable constructor function for prototype setting. + var ctor = function(){}; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Binding with arguments is also known as `curry`. + // Delegates to **ECMAScript 5**'s native `Function.bind` if available. + // We check for `func.bind` first, to fail fast when `func` is undefined. + _.bind = function(func, context) { + var args, bound; + if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError; + args = slice.call(arguments, 2); + return bound = function() { + if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); + ctor.prototype = func.prototype; + var self = new ctor; + ctor.prototype = null; + var result = func.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) return result; + return self; + }; + }; + + // Bind all of an object's methods to that object. Useful for ensuring that + // all callbacks defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length == 0) funcs = _.functions(obj); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(null, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. + _.throttle = function(func, wait) { + var context, args, timeout, result; + var previous = 0; + var later = function() { + previous = new Date; + timeout = null; + result = func.apply(context, args); + }; + return function() { + var now = new Date; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0) { + clearTimeout(timeout); + timeout = null; + previous = now; + result = func.apply(context, args); + } else if (!timeout) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, result; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) result = func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) result = func.apply(context, args); + return result; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + memo = func.apply(this, arguments); + func = null; + return memo; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return function() { + var args = [func]; + push.apply(args, arguments); + return wrapper.apply(this, args); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = arguments; + return function() { + var args = arguments; + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + if (times <= 0) return func(); + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var values = []; + for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); + return values; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var pairs = []; + for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + each(keys, function(key) { + if (key in obj) copy[key] = obj[key]; + }); + return copy; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + for (var key in obj) { + if (!_.contains(keys, key)) copy[key] = obj[key]; + } + return copy; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + if (obj[prop] == null) obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. + if (a === b) return a !== 0 || 1 / a == 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className != toString.call(b)) return false; + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') return false; + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) return bStack[length] == b; + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0, result = true; + // Recursively compare objects and arrays. + if (className == '[object Array]') { + // Compare array lengths to determine if a deep comparison is necessary. + size = a.length; + result = size == b.length; + if (result) { + // Deep compare the contents, ignoring non-numeric properties. + while (size--) { + if (!(result = eq(a[size], b[size], aStack, bStack))) break; + } + } + } else { + // Objects with different constructors are not equivalent, but `Object`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && + _.isFunction(bCtor) && (bCtor instanceof bCtor))) { + return false; + } + // Deep compare objects. + for (var key in a) { + if (_.has(a, key)) { + // Count the expected number of properties. + size++; + // Deep compare each member. + if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; + } + } + // Ensure that both objects contain the same number of properties. + if (result) { + for (key in b) { + if (_.has(b, key) && !(size--)) break; + } + result = !size; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b, [], []); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (_.has(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) == '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. + each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) == '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return !!(obj && _.has(obj, 'callee')); + }; + } + + // Optimize `isFunction` if appropriate. + if (typeof (/./) !== 'function') { + _.isFunction = function(obj) { + return typeof obj === 'function'; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj != +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + // Run a function **n** times. + _.times = function(n, iterator, context) { + var accum = Array(n); + for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + (0 | Math.random() * (max - min + 1)); + }; + + // List of HTML entities for escaping. + var entityMap = { + escape: { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '/': '/' + } + }; + entityMap.unescape = _.invert(entityMap.escape); + + // Regexes containing the keys and values listed immediately above. + var entityRegexes = { + escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), + unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') + }; + + // Functions for escaping and unescaping strings to/from HTML interpolation. + _.each(['escape', 'unescape'], function(method) { + _[method] = function(string) { + if (string == null) return ''; + return ('' + string).replace(entityRegexes[method], function(match) { + return entityMap[method][match]; + }); + }; + }); + + // If the value of the named property is a function then invoke it; + // otherwise, return it. + _.result = function(object, property) { + if (object == null) return null; + var value = object[property]; + return _.isFunction(value) ? value.call(object) : value; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + each(_.functions(obj), function(name){ + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result.call(this, func.apply(_, args)); + }; + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = '' + ++idCounter; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(text, data, settings) { + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = new RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset) + .replace(escaper, function(match) { return '\\' + escapes[match]; }); + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } + if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } + if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + "return __p;\n"; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled function source as a convenience for precompilation. + template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function, which will delegate to the wrapper. + _.chain = function(obj) { + return _(obj).chain(); + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(obj) { + return this._chain ? _(obj).chain() : obj; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; + return result.call(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result.call(this, method.apply(this._wrapped, arguments)); + }; + }); + + _.extend(_.prototype, { + + // Start chaining a wrapped Underscore object. + chain: function() { + this._chain = true; + return this; + }, + + // Extracts the result from a wrapped and chained object. + value: function() { + return this._wrapped; + } + + }); + +}).call(this); diff --git a/vendor/assets/javascripts/vendor.js b/vendor/assets/javascripts/vendor.js new file mode 100644 index 00000000..e69de29b