diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bab620de --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-journal + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore Byebug command history file. +.byebug_history diff --git a/Gemfile b/Gemfile new file mode 100644 index 00000000..59294af0 --- /dev/null +++ b/Gemfile @@ -0,0 +1,76 @@ +source 'https://rubygems.org' + +git_source(:github) do |repo_name| + repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") + "https://github.com/#{repo_name}.git" +end + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '~> 5.0.1' +# Use sqlite3 as the database for Active Record +# gem 'sqlite3' +# Use pg as tbe database for Active Record +gem 'pg' +gem 'pg_search' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Use SCSS for stylesheets +gem 'sass-rails', '~> 5.0' +# Use Uglifier as compressor for JavaScript assets +gem 'uglifier', '>= 1.3.0' +# Use CoffeeScript for .coffee assets and views +gem 'coffee-rails', '~> 4.2' +# See https://github.com/rails/execjs#readme for more supported runtimes +# gem 'therubyracer', platforms: :ruby + +# Use jquery as the JavaScript library +gem 'jquery-rails' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.5' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +gem 'angularjs-rails' +gem 'angular_rails_csrf' +gem 'devise' +gem 'faker' +source "https://rails-assets.org" do + gem "rails-assets-angular-devise" +end + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + # gem 'hirb' + gem 'byebug', platform: :mri + gem "better_errors" + gem "binding_of_caller" + gem 'pry-byebug' +end + +group :development, :test do + gem 'rspec-rails' + gem 'factory_girl_rails', '~> 4.0' + gem 'guard-rspec', require: false + gem 'rails-controller-testing' +end + +group :test do + gem 'shoulda-matchers', '~> 3.1' + gem 'capybara', '~> 2.8' + gem 'launchy' +end + +group :development do + # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. + gem 'web-console', '>= 3.3.0' + gem 'listen', '~> 3.0.5' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 00000000..1772b3c9 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,285 @@ +GEM + remote: https://rubygems.org/ + remote: https://rails-assets.org/ + specs: + actioncable (5.0.1) + actionpack (= 5.0.1) + nio4r (~> 1.2) + websocket-driver (~> 0.6.1) + actionmailer (5.0.1) + actionpack (= 5.0.1) + actionview (= 5.0.1) + activejob (= 5.0.1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (5.0.1) + actionview (= 5.0.1) + activesupport (= 5.0.1) + rack (~> 2.0) + rack-test (~> 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.0.1) + activesupport (= 5.0.1) + builder (~> 3.1) + erubis (~> 2.7.0) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + activejob (5.0.1) + activesupport (= 5.0.1) + globalid (>= 0.3.6) + activemodel (5.0.1) + activesupport (= 5.0.1) + activerecord (5.0.1) + activemodel (= 5.0.1) + activesupport (= 5.0.1) + arel (~> 7.0) + activesupport (5.0.1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (~> 0.7) + minitest (~> 5.1) + tzinfo (~> 1.1) + addressable (2.4.0) + angular_rails_csrf (2.0.0) + railties (>= 3, < 5.1) + angularjs-rails (1.6.1) + arel (7.1.4) + bcrypt (3.1.11) + better_errors (2.1.1) + coderay (>= 1.0.0) + erubis (>= 2.6.6) + rack (>= 0.9.0) + binding_of_caller (0.7.2) + debug_inspector (>= 0.0.1) + builder (3.2.3) + byebug (9.0.6) + capybara (2.10.1) + addressable + mime-types (>= 1.16) + nokogiri (>= 1.3.3) + rack (>= 1.0.0) + rack-test (>= 0.5.4) + xpath (~> 2.0) + coderay (1.1.1) + coffee-rails (4.2.1) + coffee-script (>= 2.2.0) + railties (>= 4.0.0, < 5.2.x) + coffee-script (2.4.1) + coffee-script-source + execjs + coffee-script-source (1.12.2) + concurrent-ruby (1.0.4) + debug_inspector (0.0.2) + devise (4.2.0) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0, < 5.1) + responders + warden (~> 1.2.3) + diff-lcs (1.2.5) + erubis (2.7.0) + execjs (2.7.0) + factory_girl (4.7.0) + activesupport (>= 3.0.0) + factory_girl_rails (4.7.0) + factory_girl (~> 4.7.0) + railties (>= 3.0.0) + faker (1.6.6) + i18n (~> 0.5) + ffi (1.9.17) + formatador (0.2.5) + globalid (0.3.7) + activesupport (>= 4.1.0) + guard (2.14.0) + formatador (>= 0.2.4) + listen (>= 2.7, < 4.0) + lumberjack (~> 1.0) + nenv (~> 0.1) + notiffany (~> 0.0) + pry (>= 0.9.12) + shellany (~> 0.0) + thor (>= 0.18.1) + guard-compat (1.2.1) + guard-rspec (4.7.3) + guard (~> 2.1) + guard-compat (~> 1.1) + rspec (>= 2.99.0, < 4.0) + i18n (0.8.0) + jbuilder (2.6.1) + activesupport (>= 3.0.0, < 5.1) + multi_json (~> 1.2) + jquery-rails (4.2.2) + rails-dom-testing (>= 1, < 3) + railties (>= 4.2.0) + thor (>= 0.14, < 2.0) + launchy (2.4.3) + addressable (~> 2.3) + listen (3.0.8) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + loofah (2.0.3) + nokogiri (>= 1.5.9) + lumberjack (1.0.10) + mail (2.6.4) + mime-types (>= 1.16, < 4) + method_source (0.8.2) + mime-types (3.1) + mime-types-data (~> 3.2015) + mime-types-data (3.2016.0521) + mini_portile2 (2.1.0) + minitest (5.10.1) + multi_json (1.12.1) + nenv (0.3.0) + nio4r (1.2.1) + nokogiri (1.7.0.1) + mini_portile2 (~> 2.1.0) + notiffany (0.1.1) + nenv (~> 0.1) + shellany (~> 0.0) + orm_adapter (0.5.0) + pg (0.19.0) + pg_search (1.0.6) + activerecord (>= 3.1) + activesupport (>= 3.1) + arel + pry (0.10.4) + coderay (~> 1.1.0) + method_source (~> 0.8.1) + slop (~> 3.4) + pry-byebug (3.4.0) + byebug (~> 9.0) + pry (~> 0.10) + puma (3.7.0) + rack (2.0.1) + rack-test (0.6.3) + rack (>= 1.0) + rails (5.0.1) + actioncable (= 5.0.1) + actionmailer (= 5.0.1) + actionpack (= 5.0.1) + actionview (= 5.0.1) + activejob (= 5.0.1) + activemodel (= 5.0.1) + activerecord (= 5.0.1) + activesupport (= 5.0.1) + bundler (>= 1.3.0, < 2.0) + railties (= 5.0.1) + sprockets-rails (>= 2.0.0) + rails-assets-angular (1.6.1) + rails-assets-angular-devise (1.3.0) + rails-assets-angular (>= 1.2.0, < 2) + rails-controller-testing (1.0.1) + actionpack (~> 5.x) + actionview (~> 5.x) + activesupport (~> 5.x) + rails-dom-testing (2.0.2) + activesupport (>= 4.2.0, < 6.0) + nokogiri (~> 1.6) + rails-html-sanitizer (1.0.3) + loofah (~> 2.0) + railties (5.0.1) + actionpack (= 5.0.1) + activesupport (= 5.0.1) + method_source + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (12.0.0) + rb-fsevent (0.9.8) + rb-inotify (0.9.8) + ffi (>= 0.5.0) + responders (2.3.0) + railties (>= 4.2.0, < 5.1) + rspec (3.5.0) + rspec-core (~> 3.5.0) + rspec-expectations (~> 3.5.0) + rspec-mocks (~> 3.5.0) + rspec-core (3.5.4) + rspec-support (~> 3.5.0) + rspec-expectations (3.5.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.5.0) + rspec-mocks (3.5.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.5.0) + rspec-rails (3.5.2) + actionpack (>= 3.0) + activesupport (>= 3.0) + railties (>= 3.0) + rspec-core (~> 3.5.0) + rspec-expectations (~> 3.5.0) + rspec-mocks (~> 3.5.0) + rspec-support (~> 3.5.0) + rspec-support (3.5.0) + sass (3.4.23) + sass-rails (5.0.6) + railties (>= 4.0.0, < 6) + sass (~> 3.1) + sprockets (>= 2.8, < 4.0) + sprockets-rails (>= 2.0, < 4.0) + tilt (>= 1.1, < 3) + shellany (0.0.1) + shoulda-matchers (3.1.1) + activesupport (>= 4.0.0) + slop (3.6.0) + sprockets (3.7.1) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.2.0) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.19.4) + thread_safe (0.3.5) + tilt (2.0.6) + tzinfo (1.2.2) + thread_safe (~> 0.1) + uglifier (3.0.4) + execjs (>= 0.3.0, < 3) + warden (1.2.6) + rack (>= 1.0) + web-console (3.4.0) + actionview (>= 5.0) + activemodel (>= 5.0) + debug_inspector + railties (>= 5.0) + websocket-driver (0.6.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.2) + xpath (2.0.0) + nokogiri (~> 1.3) + +PLATFORMS + ruby + +DEPENDENCIES + angular_rails_csrf + angularjs-rails + better_errors + binding_of_caller + byebug + capybara (~> 2.8) + coffee-rails (~> 4.2) + devise + factory_girl_rails (~> 4.0) + faker + guard-rspec + jbuilder (~> 2.5) + jquery-rails + launchy + listen (~> 3.0.5) + pg + pg_search + pry-byebug + puma (~> 3.0) + rails (~> 5.0.1) + rails-assets-angular-devise! + rails-controller-testing + rspec-rails + sass-rails (~> 5.0) + shoulda-matchers (~> 3.1) + tzinfo-data + uglifier (>= 1.3.0) + web-console (>= 3.3.0) + +BUNDLED WITH + 1.12.5 diff --git a/Rakefile b/Rakefile new file mode 100644 index 00000000..e85f9139 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js new file mode 100644 index 00000000..b16e53d6 --- /dev/null +++ b/app/assets/config/manifest.js @@ -0,0 +1,3 @@ +//= link_tree ../images +//= link_directory ../javascripts .js +//= link_directory ../stylesheets .css diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 00000000..e69de29b diff --git a/app/assets/javascripts/app.js b/app/assets/javascripts/app.js new file mode 100644 index 00000000..c34e8db8 --- /dev/null +++ b/app/assets/javascripts/app.js @@ -0,0 +1,5 @@ +// ---------------------------------------- +// App +// ---------------------------------------- + +var Djello = angular.module('Djello', ['ui.router', 'restangular', 'Devise', 'xeditable', 'angularModalService']); \ No newline at end of file diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js new file mode 100644 index 00000000..944160ec --- /dev/null +++ b/app/assets/javascripts/application.js @@ -0,0 +1,31 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, +// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// compiled file. JavaScript code in this file should be added after the last require_* statement. +// +// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details +// about supported directives. +// +//= require jquery +//= require jquery_ujs +//= require underscore +//= require angular +//= require angular-ui-router +//= require angular-devise +//= require restangular +//= require ngAnimate +//= require bootstrap-3.3.7 +//= require angular-modal-service +//= require xeditable.min + +//= require static_pages +//= require app +//= require services/underscore_service +//= require configs/restangular_config +//= require configs/router_config + +//= require_tree . diff --git a/app/assets/javascripts/boards.coffee b/app/assets/javascripts/boards.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/boards.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/javascripts/cable.js b/app/assets/javascripts/cable.js new file mode 100644 index 00000000..71ee1e66 --- /dev/null +++ b/app/assets/javascripts/cable.js @@ -0,0 +1,13 @@ +// Action Cable provides the framework to deal with WebSockets in Rails. +// You can generate new channels where WebSocket features live using the rails generate channel command. +// +//= require action_cable +//= require_self +//= require_tree ./channels + +(function() { + this.App || (this.App = {}); + + App.cable = ActionCable.createConsumer(); + +}).call(this); diff --git a/app/assets/javascripts/cards.coffee b/app/assets/javascripts/cards.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/cards.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/javascripts/channels/.keep b/app/assets/javascripts/channels/.keep new file mode 100644 index 00000000..e69de29b diff --git a/app/assets/javascripts/configs/restangular_config.js b/app/assets/javascripts/configs/restangular_config.js new file mode 100644 index 00000000..6bdac1ec --- /dev/null +++ b/app/assets/javascripts/configs/restangular_config.js @@ -0,0 +1,21 @@ +// ---------------------------------------- +// Restangular +// ---------------------------------------- + +Djello.config(['RestangularProvider', function(RestangularProvider) { + + RestangularProvider.setBaseUrl('/api/v1'); + RestangularProvider.setRequestSuffix('.json'); + +}]); + +Djello.config( + ["$httpProvider", + function($httpProvider) { + var token = $('meta[name=csrf-token]') + .attr('content'); + $httpProvider + .defaults + .headers + .common['X-CSRF-Token'] = token; + }]); \ No newline at end of file diff --git a/app/assets/javascripts/configs/router_config.js b/app/assets/javascripts/configs/router_config.js new file mode 100644 index 00000000..1bce2033 --- /dev/null +++ b/app/assets/javascripts/configs/router_config.js @@ -0,0 +1,54 @@ +// ---------------------------------------- +// Router +// ---------------------------------------- + +Djello.config(['$urlRouterProvider', '$stateProvider', + function($urlRouterProvider, $stateProvider) { + + $urlRouterProvider.otherwise('/dashboard'); + + $stateProvider + .state('dashboard', { + url: '/dashboard', + templateUrl: '/templates/dashboard.html', + controller: 'DashboardCtrl', + resolve: { + boards: ['BoardService', function(BoardService){ + return BoardService.getBoards(); + }] + } + }) + .state('dashboard.show', { + url: '/:id', + views: { + 'list@dashboard': { + templateUrl: '/templates/board_show.html', + controller: 'BoardShowCtrl', + } + }, + resolve: { + board: ['BoardService', '$stateParams', function(BoardService, $stateParams){ + return BoardService.getBoard($stateParams.id); + }], + users: ['UserService', function(UserService){ + return UserService.all().$object; + }] + } + }); + }]); + +Djello.config(['$locationProvider', function($locationProvider) { + $locationProvider.hashPrefix(''); +}]); + +Djello.run(function(editableOptions) { + editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default' +}); + +Djello.run(['$rootScope', function($rootScope) { + $rootScope.$on("$stateChangeError", console.error.bind(console)); +}]); + + + + diff --git a/app/assets/javascripts/controllers/board_show_ctrl.js b/app/assets/javascripts/controllers/board_show_ctrl.js new file mode 100644 index 00000000..fe6824e4 --- /dev/null +++ b/app/assets/javascripts/controllers/board_show_ctrl.js @@ -0,0 +1,83 @@ +Djello.controller('BoardShowCtrl', ['$scope', 'Auth', 'board', 'BoardService', 'ListService', 'CardService', 'ModalService', '$stateParams', 'users', + function($scope, Auth, board, BoardService, ListService, CardService, ModalService, $stateParams, users) { + Auth.currentUser().then(function(user) { + $scope.currentUser = user; + }, function(response) { + console.log(response); + }); + + $scope.board = board; + $scope.lists = board.lists; + _.each($scope.lists, function(list) { + list.cardParams = {}; + list.showForm = false; + }) + $scope.listParams = { title: "new list", board_id: board.id }; + + $scope.createList = function(board) { + board.createList($scope.listParams) + .then(function(response) { + console.log(response); + }, function(response) { + console.error(response); + }); + } + + $scope.createCard = function(list) { + list.createCard(list.cardParams) + .then(function(card) { + console.log(card); + ListService.updateCardActivity($scope.lists, list.id, card); + }, function(response) { + console.error(response); + }); + } + + $scope.changeList = function(list, title) { + params = {title: title}; + ListService.updateList(list, params); + } + + $scope.changeCard = function(card, title) { + params = {title: title}; + CardService.updateCard(card, params) + .then(function(card) { + ListService.updateCardActivity($scope.lists, card.list_id, card); + }) + } + + $scope.deleteList = function(list) { + list.remove().then( function(list) { + new_lists = _.reject(board.lists , function(l) { return l.id === list.id }); + angular.copy(new_lists, $scope.lists); + }) + } + + $scope.show = function(card) { + ModalService.showModal({ + templateUrl: 'templates/cardModal.html', + controller: "CardModalCtrl", + inputs: { + cardParams: card, + users: users, + } + }).then(function(modal) { + modal.element.modal(); + modal.close.then(function(card) { + if (card != undefined && card.delete === true) { + card.remove().then( function(card) { + list = _.find($scope.lists, function(list) { return list.id === card.list_id }); + new_cards = _.reject(list.cards, function(c) { return c.id === card.id }); + angular.copy(new_cards, list.cards); + console.log(list.cards); + }) + } else if (card != undefined) { + CardService.updateCard(card, card).then( function(card) { + ListService.updateCardActivity($scope.lists, card.list_id, card); + }) + } + }); + }); + }; + +}]); diff --git a/app/assets/javascripts/controllers/card_modal_ctrl.js b/app/assets/javascripts/controllers/card_modal_ctrl.js new file mode 100644 index 00000000..09c3490d --- /dev/null +++ b/app/assets/javascripts/controllers/card_modal_ctrl.js @@ -0,0 +1,34 @@ +Djello.controller('CardModalCtrl', ['$scope', 'close', 'cardParams', 'CardService', 'users', + function($scope, close, cardParams, CardService, users) { + + $scope.card = cardParams; + $scope.cardParams = cardParams; + $scope.users = CardService.filterMembers($scope.card, users); + + // when you need to close the modal, call close + $scope.close = function(result) { + close(result, 500); // close, but give 500ms for bootstrap to animate + }; + + $scope.destroy = function(result) { + result.delete = true; + close(result, 500); + }; + + $scope.deleteMember = function(card, member) { + CardService.destroyMember(card, member).then( function(member) { + new_members = _.reject($scope.card.card_members, function(m) { return m.id === member.id}); + angular.copy(new_members, $scope.card.card_members); + $scope.users.push(member); + }) + } + + $scope.addMember = function(card, member) { + CardService.addMember(card, member).then( function(member) { + $scope.card.card_members.push(member); + new_users = _.reject($scope.users, function(user) { return user.id === member.id }); + angular.copy(new_users, $scope.users); + }) + } + +}]); \ No newline at end of file diff --git a/app/assets/javascripts/controllers/dashboard_ctrl.js b/app/assets/javascripts/controllers/dashboard_ctrl.js new file mode 100644 index 00000000..4a852547 --- /dev/null +++ b/app/assets/javascripts/controllers/dashboard_ctrl.js @@ -0,0 +1,46 @@ +Djello.controller('DashboardCtrl', ['$scope', 'Auth', 'boards', 'BoardService', '$state', + function($scope, Auth, boards, BoardService, $state) { + Auth.currentUser() + .then(function(user) { + $scope.currentUser = user; + console.log(user); + }, function(response) { + console.log(response); + }); + + $scope.boards = boards; + $scope.currentBoard = $scope.boards[0]; + + $scope.deleteBoard = function(board) { + if (!board) return; + BoardService.deleteBoard(board).then( function() { + BoardService.getBoards().then( function(boards) { + angular.copy(boards,$scope.boards); + $scope.currentBoard = $scope.boards[0]; + $scope.boardChanged($scope.currentBoard); + }) + }) + } + + $scope.createBoard = function() { + params = { title: "New Board", user_id: $scope.currentUser.id } + BoardService.createBoard(params).then( function(createdBoard) { + BoardService.getBoards().then( function(boards) { + angular.copy(boards,$scope.boards); + $scope.currentBoard = $scope.boards[0]; + $scope.boardChanged($scope.currentBoard); + }) + }) + } + + $scope.changeBoard = function(board, title) { + params = {title: title}; + BoardService.updateBoard(board, params); + } + + $scope.boardChanged = function(board) { + $state.go('dashboard.show', {"id": board.id}); + } + + $state.go('dashboard.show', {"id": boards[0].id}); +}]); \ No newline at end of file diff --git a/app/assets/javascripts/filters/reverse.js b/app/assets/javascripts/filters/reverse.js new file mode 100644 index 00000000..34e1bbc9 --- /dev/null +++ b/app/assets/javascripts/filters/reverse.js @@ -0,0 +1,5 @@ +Djello.filter('reverse', function() { + return function(items) { + return items.slice().reverse(); + }; +}); \ No newline at end of file diff --git a/app/assets/javascripts/lists.coffee b/app/assets/javascripts/lists.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/lists.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/javascripts/members.coffee b/app/assets/javascripts/members.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/members.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/javascripts/services/board_service.js b/app/assets/javascripts/services/board_service.js new file mode 100644 index 00000000..6f546c98 --- /dev/null +++ b/app/assets/javascripts/services/board_service.js @@ -0,0 +1,75 @@ +// ---------------------------------------- +// BoardService +// ---------------------------------------- + +Djello.factory('BoardService', + ['_', 'Restangular', 'ListService', + function(_, Restangular, ListService) { + + Restangular.extendModel('boards', function(model) { + model.createList = function(params) { + params.board_id = model.id; + return ListService.createList(params) + .then(function(response) { + Restangular.restangularizeElement(model, response, 'lists'); + model.lists.push(response); + return response; + }); + }; + return model; + }); + + var _restangularizeListCards = function(list) { + list.cards = Restangular + .restangularizeCollection(list, list.cards, 'cards'); + } + + var _restangularizeBoardLists = function(board) { + board.lists = Restangular + .restangularizeCollection(board, board.lists, 'lists'); + _.each(board.lists, function(list) { + _restangularizeListCards(list); + }) + }; + + + var _restangularizeBoardsLists = function(boards) { + _.each(boards, function(board) { + _restangularizeBoardLists(board); + }); + }; + + var BoardService = {}; + + BoardService.getBoards = function(){ + return Restangular.all('boards').getList().then( function(boards) { + _restangularizeBoardsLists(boards); + return boards; + }) + }; + + BoardService.createBoard = function(formData){ + var board = { board: formData }; + return Restangular.all("boards").post(board); + }; + + BoardService.getBoard = function(id){ + return Restangular.one('boards', id).get().then( function(board) { + _restangularizeBoardLists(board); + return board; + }) + }; + + + BoardService.updateBoard = function(board, formParams){ + var boardData = { board: formParams }; + return board.patch(boardData); + }; + + BoardService.deleteBoard = function(board){ + return board.remove(); + } + + return BoardService; + + }]); diff --git a/app/assets/javascripts/services/card_service.js b/app/assets/javascripts/services/card_service.js new file mode 100644 index 00000000..8ab9aa20 --- /dev/null +++ b/app/assets/javascripts/services/card_service.js @@ -0,0 +1,38 @@ +// ---------------------------------------- +// CardService +// ---------------------------------------- + +Djello.factory('CardService', + ['_', 'Restangular', + function(_, Restangular) { + + var CardService = {}; + + CardService.createCard = function(formData){ + var card = { card: formData }; + return Restangular.all("cards").post(card); + }; + + CardService.updateCard = function(card, formParams){ + var cardData = { "card": formParams }; + return card.patch(cardData); + }; + + CardService.destroyMember = function(card, member){ + return card.customDELETE('destroy_member', {user_id: member.id }); + } + + CardService.addMember = function(card, member){ + return card.customPOST('', 'add_member', {user_id: member.id}); + } + + CardService.filterMembers = function(card, users){ + _.each(card.card_members, function(member) { + users = _.reject(users, function(user) { return user.id === member.id }); + }) + return users; + } + + return CardService; + + }]); diff --git a/app/assets/javascripts/services/list_service.js b/app/assets/javascripts/services/list_service.js new file mode 100644 index 00000000..c54e061a --- /dev/null +++ b/app/assets/javascripts/services/list_service.js @@ -0,0 +1,47 @@ +// ---------------------------------------- +// ListService +// ---------------------------------------- + +Djello.factory('ListService', + ['_', 'Restangular', 'CardService', + function(_, Restangular, CardService) { + + Restangular.extendModel('lists', function(model) { + model.createCard = function(params) { + params.list_id = model.id; + return CardService.createCard(params) + .then(function(response) { + Restangular.restangularizeElement(model, response, 'cards'); + model.cards.push(response); + model.cardParams = {}; + return response; + }); + }; + return model; + }); + + var ListService = {}; + + ListService.createList = function(formData){ + var list = { list: formData }; + return Restangular.all('lists').post(list); + }; + + ListService.updateList = function(list, formParams){ + var listData = { "list": formParams }; + return list.patch(listData); + }; + + ListService.updateCardActivity = function(lists, list_id, card){ + target_list = _.find(lists, function(l) { return l.id === list_id}) + if (target_list == undefined) return; + target_card = _.find(target_list.cards, function(c) { return c.id === card.id}) + if (target_card != undefined) { + angular.copy(card, target_card); + } + return; + } + + return ListService; + + }]); diff --git a/app/assets/javascripts/services/underscore_service.js b/app/assets/javascripts/services/underscore_service.js new file mode 100644 index 00000000..f2aebf86 --- /dev/null +++ b/app/assets/javascripts/services/underscore_service.js @@ -0,0 +1,7 @@ +// ---------------------------------------- +// UnderScoreService +// ---------------------------------------- + +Djello.factory('_', ['$window', function($window) { + return $window._; +}]); \ No newline at end of file diff --git a/app/assets/javascripts/services/user_service.js b/app/assets/javascripts/services/user_service.js new file mode 100644 index 00000000..228f6d71 --- /dev/null +++ b/app/assets/javascripts/services/user_service.js @@ -0,0 +1,17 @@ +// ---------------------------------------- +// UserService +// ---------------------------------------- + +Djello.factory('UserService', + ['_', 'Restangular', + function(_, Restangular) { + + var UserService = {}; + + UserService.all = function() { + return Restangular.all('users').getList(); + } + + return UserService; + + }]); diff --git a/app/assets/javascripts/static_pages.coffee b/app/assets/javascripts/static_pages.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/static_pages.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/javascripts/users.coffee b/app/assets/javascripts/users.coffee new file mode 100644 index 00000000..24f83d18 --- /dev/null +++ b/app/assets/javascripts/users.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 00000000..0ebd7fe8 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/app/assets/stylesheets/boards.scss b/app/assets/stylesheets/boards.scss new file mode 100644 index 00000000..4bbe565a --- /dev/null +++ b/app/assets/stylesheets/boards.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the boards controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/cards.scss b/app/assets/stylesheets/cards.scss new file mode 100644 index 00000000..6ca2e944 --- /dev/null +++ b/app/assets/stylesheets/cards.scss @@ -0,0 +1,8 @@ +// Place all the styles related to the cards controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ +.card { + border: 0.5px solid #666; + margin: 10px; + padding: 10px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/lists.scss b/app/assets/stylesheets/lists.scss new file mode 100644 index 00000000..f1b9c59a --- /dev/null +++ b/app/assets/stylesheets/lists.scss @@ -0,0 +1,7 @@ +// Place all the styles related to the lists controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ +.list { + border: 1px solid #333; + margin-top: 10px; +} \ No newline at end of file diff --git a/app/assets/stylesheets/members.scss b/app/assets/stylesheets/members.scss new file mode 100644 index 00000000..43b5cefe --- /dev/null +++ b/app/assets/stylesheets/members.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the members controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/static_pages.scss b/app/assets/stylesheets/static_pages.scss new file mode 100644 index 00000000..40608b2f --- /dev/null +++ b/app/assets/stylesheets/static_pages.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the static_pages controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/users.scss b/app/assets/stylesheets/users.scss new file mode 100644 index 00000000..1efc835c --- /dev/null +++ b/app/assets/stylesheets/users.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the users controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 00000000..d6726972 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 00000000..0ff5442f --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 00000000..6e55282e --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,10 @@ +class ApplicationController < ActionController::Base + protect_from_forgery with: :exception + before_action :configure_permitted_parameters, if: :devise_controller? + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) + end +end diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb new file mode 100644 index 00000000..58c541ca --- /dev/null +++ b/app/controllers/boards_controller.rb @@ -0,0 +1,91 @@ +class BoardsController < ApplicationController + before_action :require_login + before_action :set_board, :except => [:index, :create] + + def index + @boards = Board.where(user_id: current_user.id).order(:created_at => :desc) + respond_to do |format| + format.json { render :json => resource_to_json, :status => 200 } + end + end + + def create + @board = Board.new(board_params) + respond_to do |format| + if @board.save + flash.now[:error] = 'board created' + format.json { render :json => resource_to_json, :status => 201 } + else + flash.now[:error] = 'board not created' + format.json { render :json => board_errors, :status => 422 } + end + end + end + + def show + respond_to do |format| + format.json { render :json => resource_to_json, :status => 200 } + end + end + + def update + respond_to do |format| + if @board.update(board_params) + flash.now[:error] = 'Board updated' + format.json { render :json => resource_to_json, :status => 200 } + else + flash.now[:error] = 'Board not updated' + format.json { render :json => board_errors, :status => 422 } + end + end + end + + def destroy + respond_to do |format| + if @board.destroy + flash.now[:error] = 'board destroyed' + format.json { render :json => @board, :status => 200 } + else + flash.now[:error] = 'board not destroyed' + format.json { render :json => board_errors, :status => 422 } + end + end + end + + private + def set_board + @board = Board.find_by_id(params[:id]) + unless @board + flash.now[:error] = 'Could not find board' + respond_to do |format| + format.json { render :json => board_errors , :status => 422 } + end + end + end + + def board_params + params.require(:board).permit(:title, :user_id) + end + + def board_errors + if @board + error = @board.errors.full_messages.to_json + else + error = flash.now[:error] + end + { :errors => error } + end + + def require_login + unless current_user + redirect_to new_user_session_path + end + end + + def resource_to_json + resource = action_name == 'index' ? @boards : @board + resource.to_json(:include => {:lists => {:include => {:cards => + {:include => [:card_members, :activities => {:include => :user}] }}}}) + end + +end diff --git a/app/controllers/cards_controller.rb b/app/controllers/cards_controller.rb new file mode 100644 index 00000000..230ce9a0 --- /dev/null +++ b/app/controllers/cards_controller.rb @@ -0,0 +1,114 @@ +class CardsController < ApplicationController + before_action :set_card, :except => [:index, :create] + + def create + @card = Card.new(card_params) + respond_to do |format| + if @card.save + card_create_activity(@card, current_user) + flash.now[:error] = 'card created' + format.json { render :json => resource_to_json, :status => 201 } + else + flash.now[:error] = 'card not created' + format.json { render :json => card_errors, :status => 422 } + end + end + end + + def update + respond_to do |format| + old_card = @card.deep_dup + if @card.update(card_params) + card_update_activity(old_card, @card, current_user, card_params) + flash.now[:error] = 'card updated' + format.json { render :json => resource_to_json, :status => 200 } + else + flash.now[:error] = 'card not updated' + format.json { render :json => card_errors, :status => 422 } + end + end + end + + def destroy + respond_to do |format| + if @card.destroy + flash.now[:error] = 'card destroyed' + format.json { render :json => @card, :status => 200 } + else + flash.now[:error] = 'card not destroyed' + format.json { render :json => card_errors, :status => 422 } + end + end + end + + def destroy_member + @member = User.find(params[:user_id]) + respond_to do |format| + if @member && @card.members.destroy(@card.members.where(user_id: params[:user_id])) + flash.now[:error] = 'card member destroyed' + format.json { render :json => @member, :status => 200 } + else + flash.now[:error] = 'card member not destroyed' + format.json { render :json => card_errors, :status => 422 } + end + end + end + + def add_member + respond_to do |format| + @user = User.find(params[:user_id]) + if @user && @card.card_members << @user + flash.now[:error] = 'card member added' + format.json { render :json => @user, :status => 200 } + else + flash.now[:error] = 'card member not added' + format.json { render :json => card_errors, :status => 422 } + end + end + end + + private + def set_card + @card = Card.find_by_id(params[:id]) + unless @card + flash.now[:error] = 'Could not find card' + respond_to do |format| + format.json { render :json => card_errors , :status => 422 } + end + end + end + + def card_params + params.require(:card).permit(:title, :desc, :list_id) + end + + def card_create_activity(card, user) + Activity.create(activity: "added this card to the \"#{card.list.board.title}\" board", + card_id: card.id, user_id: user.id) + end + + def card_update_activity(old_card, saved_card, user, params) + if (params["title"] != old_card["title"]) + Activity.create(activity: "changed the title of the card to \"#{params["title"]}\"", + card_id: saved_card.id, user_id: user.id) + elsif (params["desc"] != old_card["desc"]) + Activity.create(activity: "changed the description of the card to \"#{params["desc"]}\"", + card_id: saved_card.id, user_id: user.id) + end + end + + def card_errors + if @card + error = @card.errors.full_messages.to_json + else + error = flash.now[:error] + end + { :errors => error } + end + + def resource_to_json + resource = action_name == 'index' ? @cards : @card + resource.to_json(:include => [:card_members, :activities => {:include => :user }]) + end + +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/app/controllers/lists_controller.rb b/app/controllers/lists_controller.rb new file mode 100644 index 00000000..7393c90d --- /dev/null +++ b/app/controllers/lists_controller.rb @@ -0,0 +1,69 @@ +class ListsController < ApplicationController + before_action :set_list, :except => [:index, :create] + + def create + @list = List.new(list_params) + respond_to do |format| + if @list.save + flash.now[:error] = 'list created' + format.json { render :json => resource_to_json, :status => 201 } + else + flash.now[:error] = 'list not created' + format.json { render :json => list_errors, :status => 422 } + end + end + end + + def update + respond_to do |format| + if @list.update(list_params) + flash.now[:error] = 'list updated' + format.json { render :json => resource_to_json, :status => 200 } + else + flash.now[:error] = 'list not updated' + format.json { render :json => list_errors, :status => 422 } + end + end + end + + def destroy + respond_to do |format| + if @list.destroy + flash.now[:error] = 'list destroyed' + format.json { render :json => @list, :status => 200 } + else + flash.now[:error] = 'list not destroyed' + format.json { render :json => list_errors, :status => 422 } + end + end + end + + private + def set_list + @list = List.find_by_id(params[:id]) + unless @list + flash.now[:error] = 'Could not find list' + respond_to do |format| + format.json { render :json => list_errors , :status => 422 } + end + end + end + + def list_params + params.require(:list).permit(:title, :board_id) + end + + def list_errors + if @list + error = @list.errors.full_messages.to_json + else + error = flash.now[:error] + end + { :errors => error } + end + + def resource_to_json + resource = action_name == 'index' ? @lists : @list + resource.to_json(:include => :cards) + end +end diff --git a/app/controllers/members_controller.rb b/app/controllers/members_controller.rb new file mode 100644 index 00000000..26a2cbb0 --- /dev/null +++ b/app/controllers/members_controller.rb @@ -0,0 +1,46 @@ +class MembersController < ApplicationController + + def destroy + respond_to do |format| + if @member.destroy + flash.now[:error] = 'member destroyed' + format.json { render :json => @member, :status => 200 } + else + flash.now[:error] = 'member not destroyed' + format.json { render :json => member_errors, :status => 422 } + end + end + end + + private + + private + def set_member + @member= Member.find_by_id(params[:id]) + unless @member + flash.now[:error] = 'Could not find member' + respond_to do |format| + format.json { render :json => member_errors , :status => 422 } + end + end + end + + def member_params + params.require(:member).permit(:user_id, :card_id) + end + + def member_errors + if @member + error = @member.errors.full_messages.to_json + else + error = flash.now[:error] + end + { :errors => error } + end + + def resource_to_json + resource = action_name == 'index' ? @members : @member + resource.to_json + end + +end diff --git a/app/controllers/static_pages_controller.rb b/app/controllers/static_pages_controller.rb new file mode 100644 index 00000000..62680549 --- /dev/null +++ b/app/controllers/static_pages_controller.rb @@ -0,0 +1,3 @@ +class StaticPagesController < ApplicationController + before_action :authenticate_user! +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 00000000..d8e4e79d --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,34 @@ +class UsersController < ApplicationController + + def index + @users = User.order(:created_at => :desc) + respond_to do |format| + format.json { render :json => resource_to_json, :status => 200 } + end + end + + private + def set_user + @user = User.find_by_id(params[:id]) + unless @user + flash.now[:error] = 'Could not find user' + respond_to do |format| + format.json { render :json => user_errors , :status => 422 } + end + end + end + + def user_errors + if @user + error = @user.errors.full_messages.to_json + else + error = flash.now[:error] + end + { :errors => error } + end + + def resource_to_json + resource = action_name == 'index' ? @users : @user + resource.to_json + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 00000000..de6be794 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/helpers/boards_helper.rb b/app/helpers/boards_helper.rb new file mode 100644 index 00000000..8b8af150 --- /dev/null +++ b/app/helpers/boards_helper.rb @@ -0,0 +1,2 @@ +module BoardsHelper +end diff --git a/app/helpers/cards_helper.rb b/app/helpers/cards_helper.rb new file mode 100644 index 00000000..82dc1f45 --- /dev/null +++ b/app/helpers/cards_helper.rb @@ -0,0 +1,2 @@ +module CardsHelper +end diff --git a/app/helpers/lists_helper.rb b/app/helpers/lists_helper.rb new file mode 100644 index 00000000..bf2e0db4 --- /dev/null +++ b/app/helpers/lists_helper.rb @@ -0,0 +1,2 @@ +module ListsHelper +end diff --git a/app/helpers/members_helper.rb b/app/helpers/members_helper.rb new file mode 100644 index 00000000..e3fa623c --- /dev/null +++ b/app/helpers/members_helper.rb @@ -0,0 +1,2 @@ +module MembersHelper +end diff --git a/app/helpers/static_pages_helper.rb b/app/helpers/static_pages_helper.rb new file mode 100644 index 00000000..2d63e79e --- /dev/null +++ b/app/helpers/static_pages_helper.rb @@ -0,0 +1,2 @@ +module StaticPagesHelper +end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb new file mode 100644 index 00000000..2310a240 --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 00000000..a009ace5 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 00000000..286b2239 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/app/models/activity.rb b/app/models/activity.rb new file mode 100644 index 00000000..fdc704a3 --- /dev/null +++ b/app/models/activity.rb @@ -0,0 +1,4 @@ +class Activity < ApplicationRecord + belongs_to :card + belongs_to :user +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 00000000..10a4cba8 --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/app/models/board.rb b/app/models/board.rb new file mode 100644 index 00000000..db14555b --- /dev/null +++ b/app/models/board.rb @@ -0,0 +1,4 @@ +class Board < ApplicationRecord + belongs_to :user + has_many :lists, dependent: :destroy +end diff --git a/app/models/card.rb b/app/models/card.rb new file mode 100644 index 00000000..ee6689ef --- /dev/null +++ b/app/models/card.rb @@ -0,0 +1,6 @@ +class Card < ApplicationRecord + belongs_to :list + has_many :members, dependent: :destroy + has_many :card_members, through: :members, :source => :user + has_many :activities +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/app/models/list.rb b/app/models/list.rb new file mode 100644 index 00000000..b6a9e423 --- /dev/null +++ b/app/models/list.rb @@ -0,0 +1,4 @@ +class List < ApplicationRecord + belongs_to :board + has_many :cards, dependent: :destroy +end diff --git a/app/models/member.rb b/app/models/member.rb new file mode 100644 index 00000000..30a47ffe --- /dev/null +++ b/app/models/member.rb @@ -0,0 +1,4 @@ +class Member < ApplicationRecord + belongs_to :user + belongs_to :card +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 00000000..356e6375 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,10 @@ +class User < ApplicationRecord + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :trackable, :validatable + has_many :boards + has_many :members, dependent: :destroy + has_many :cards, through: :members + has_many :activities +end diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 00000000..2dc668fc --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,16 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +
+ +
+ <%= f.submit "Resend confirmation instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 00000000..dc55f64f --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/password_change.html.erb b/app/views/devise/mailer/password_change.html.erb new file mode 100644 index 00000000..b41daf47 --- /dev/null +++ b/app/views/devise/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 00000000..f667dc12 --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 00000000..41e148bf --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 00000000..6a796b05 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,25 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New password" %>
+ <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum)
+ <% end %> + <%= f.password_field :password, autofocus: true, autocomplete: "off" %> +
+ +
+ <%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.submit "Change my password" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 00000000..3d6d11aa --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,16 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.submit "Send me reset password instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 00000000..ee0522de --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,48 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.label :username %>
+ <%= f.text_field :username, autofocus: true %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= f.label :password %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "off" %> + <% if @minimum_password_length %> +
+ <%= @minimum_password_length %> characters minimum + <% end %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.label :current_password %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "off" %> +
+ +
+ <%= f.submit "Update" %> +
+<% end %> + +

Cancel my account

+ +

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 00000000..7d7925ec --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,34 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.label :username %>
+ <%= f.text_field :username, autofocus: true %> +
+ +
+ <%= f.label :password %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %>
+ <%= f.password_field :password, autocomplete: "off" %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %> +
+ +
+ <%= f.submit "Sign up" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 00000000..b261cfd1 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,26 @@ +

Log in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "off" %> +
+ + <% if devise_mapping.rememberable? -%> +
+ <%= f.check_box :remember_me %> + <%= f.label :remember_me %> +
+ <% end -%> + +
+ <%= f.submit "Log in" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 00000000..e6a3e419 --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>
+ <% end -%> +<% end -%> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 00000000..16586bc7 --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,16 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %> +
+ +
+ <%= f.submit "Resend unlock instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 00000000..bc9a8868 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,36 @@ + + + + ProjectDjello + <%= csrf_meta_tags %> + + + + + + + <%= stylesheet_link_tag 'application', media: 'all' %> + <%= javascript_include_tag 'application' %> + + + + + + +
+ <%= yield %> +
+ + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000..cbd34d2e --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000..37f0bddb --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/static_pages/index.html b/app/views/static_pages/index.html new file mode 100644 index 00000000..f182cddd --- /dev/null +++ b/app/views/static_pages/index.html @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 00000000..66e9889e --- /dev/null +++ b/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/bin/rails b/bin/rails new file mode 100755 index 00000000..5badb2fd --- /dev/null +++ b/bin/rails @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/bin/rake b/bin/rake new file mode 100755 index 00000000..d87d5f57 --- /dev/null +++ b/bin/rake @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 00000000..e620b4da --- /dev/null +++ b/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/bin/spring b/bin/spring new file mode 100755 index 00000000..fb2ec2eb --- /dev/null +++ b/bin/spring @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby + +# This file loads spring without using Bundler, in order to be fast. +# It gets overwritten when you run the `spring binstub` command. + +unless defined?(Spring) + require 'rubygems' + require 'bundler' + + lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) + spring = lockfile.specs.detect { |spec| spec.name == "spring" } + if spring + Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path + gem 'spring', spring.version + require 'spring/binstub' + end +end diff --git a/bin/update b/bin/update new file mode 100755 index 00000000..a8e4462f --- /dev/null +++ b/bin/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/config.ru b/config.ru new file mode 100644 index 00000000..f7ba0b52 --- /dev/null +++ b/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 00000000..8c858810 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,18 @@ +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ProjectDjello + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + config.to_prepare do + DeviseController.respond_to :html, :json + end + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 00000000..30f5120d --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 00000000..0bbde6f7 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,9 @@ +development: + adapter: async + +test: + adapter: async + +production: + adapter: redis + url: redis://localhost:6379/1 diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 00000000..fd5e518b --- /dev/null +++ b/config/database.yml @@ -0,0 +1,32 @@ +# SQLite version 3.x +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' +# + +default: &default + adapter: postgresql + pool: 5 + timeout: 5000 + +development: + adapter: postgresql + database: project_djello/development # name this whatever you want + host: localhost + pool: 5 # Not required + timeout: 5000 # Not required + +test: + adapter: postgresql + database: project_djello/test # name this whatever you want + host: localhost + pool: 5 # Not required + timeout: 5000 # Not required + +production: + adapter: postgresql + database: project_djello/production # name this whatever you want + host: localhost + pool: 5 # Not required + timeout: 5000 \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 00000000..426333bb --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 00000000..3a256281 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,60 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker + + # For Devise + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 00000000..34c0b7fc --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,86 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Compress JavaScripts and CSS. + config.assets.js_compressor = :uglifier + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Mount Action Cable outside main process or domain + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "project_djello_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 00000000..30587ef6 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,42 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=3600' + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 00000000..51639b67 --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 00000000..01ef3e66 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,11 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Add additional assets to the asset load path +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in app/assets folder are already added. +# Rails.application.config.assets.precompile += %w( search.js ) diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb new file mode 100644 index 00000000..59385cdf --- /dev/null +++ b/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/config/initializers/cookies_serializer.rb b/config/initializers/cookies_serializer.rb new file mode 100644 index 00000000..5a6a32d3 --- /dev/null +++ b/config/initializers/cookies_serializer.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. + +# Specify a serializer for the signed and encrypted cookie jars. +# Valid options are :json, :marshal, and :hybrid. +Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 00000000..64b59629 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,274 @@ +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = '9070162a5e5eae9a49e415065d8bf497f4841aee0909f334f58d155cc3581f251a64b4841130cd416e2b91f53b4b90e399a6d52b3ebf9eb5667d00b4be94c40c' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ActionMailer::Base' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 11. If + # using other algorithms, it sets how many times you want the password to be hashed. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # algorithm), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 11 + + # Set up a pepper to generate the hashed password. + # config.pepper = '889941c677d0fe91803da9081825d9afb6b36f01bfcf04f80f0b772426fc96f7038c492223366a0f5f98c0c7e18332e2f7594fe0ae9498d6173d1723070bccbc' + + # Send a notification email when the user's password is changed + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. Default is 0.days, meaning + # the user cannot access the website without confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [:email] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [:email] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [:email] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> Configuration for :encryptable + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ['*/*', :html] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using OmniAuth, Devise cannot automatically set OmniAuth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' +end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000..4a994e1e --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 00000000..ac033bf9 --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb new file mode 100644 index 00000000..dc189968 --- /dev/null +++ b/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/config/initializers/new_framework_defaults.rb b/config/initializers/new_framework_defaults.rb new file mode 100644 index 00000000..671abb69 --- /dev/null +++ b/config/initializers/new_framework_defaults.rb @@ -0,0 +1,24 @@ +# Be sure to restart your server when you modify this file. +# +# This file contains migration options to ease your Rails 5.0 upgrade. +# +# Read the Guide for Upgrading Ruby on Rails for more info on each option. + +# Enable per-form CSRF tokens. Previous versions had false. +Rails.application.config.action_controller.per_form_csrf_tokens = true + +# Enable origin-checking CSRF mitigation. Previous versions had false. +Rails.application.config.action_controller.forgery_protection_origin_check = true + +# Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. +# Previous versions had false. +ActiveSupport.to_time_preserves_timezone = true + +# Require `belongs_to` associations by default. Previous versions had false. +Rails.application.config.active_record.belongs_to_required_by_default = true + +# Do not halt callback chains when a callback returns false. Previous versions had true. +ActiveSupport.halt_callback_chains_on_return_false = false + +# Configure SSL options to enable HSTS with subdomains. Previous versions had false. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb new file mode 100644 index 00000000..657f89ec --- /dev/null +++ b/config/initializers/session_store.rb @@ -0,0 +1,3 @@ +# Be sure to restart your server when you modify this file. + +Rails.application.config.session_store :cookie_store, key: '_project_djello_session' diff --git a/config/initializers/wrap_parameters.rb b/config/initializers/wrap_parameters.rb new file mode 100644 index 00000000..bbfc3961 --- /dev/null +++ b/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 00000000..bd4c3ebc --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,62 @@ +# Additional translations at https://github.com/plataformatec/devise/wiki/I18n + +en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your email address before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock instructions" + password_change: + subject: "Password Changed" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated from %{kind} account." + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + updated: "Your password has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." + signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." + updated: "Your account has been updated successfully." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." + errors: + messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" + expired: "has expired, please request a new one" + not_found: "not found" + not_locked: "was not locked" + not_saved: + one: "1 error prohibited this %{resource} from being saved:" + other: "%{count} errors prohibited this %{resource} from being saved:" diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 00000000..06539571 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 00000000..c7f311f8 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 00000000..2c557d10 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,21 @@ +Rails.application.routes.draw do + devise_for :users + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html + root 'static_pages#index' + + scope :api do + scope :v1 do + resources :users, only: [:index] + resources :boards do + resources :lists, only: [:update, :destroy] do + resources :cards, only: [:update, :destroy] do + delete 'destroy_member', on: :member + post 'add_member', on: :member + end + end + end + resources :lists, only: [:create] + resources :cards, only: [:create] + end + end +end diff --git a/config/secrets.yml b/config/secrets.yml new file mode 100644 index 00000000..41c0b198 --- /dev/null +++ b/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 4c73385c46e87b64e230a530655c14501daef9190dd3a1a396dac5032780c3b447ddf3e986b5d22c098f56d46229469e250b5584808c39241266454edaefc9c7 + +test: + secret_key_base: 9869e4bef56f991f0e22d1c331d288be14fd339149f7b5c65cc20a2e7a02210bd389894c0ad0375730d039ac2e29a88b2ced3ebc256c47e4ee3a439470773ed6 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/config/spring.rb b/config/spring.rb new file mode 100644 index 00000000..c9119b40 --- /dev/null +++ b/config/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/db/migrate/20170203031625_devise_create_users.rb b/db/migrate/20170203031625_devise_create_users.rb new file mode 100644 index 00000000..6204aa0f --- /dev/null +++ b/db/migrate/20170203031625_devise_create_users.rb @@ -0,0 +1,43 @@ +class DeviseCreateUsers < ActiveRecord::Migration[5.0] + def change + create_table :users do |t| + ## Database authenticatable + t.string :username, null: false, default: "" + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + t.integer :sign_in_count, default: 0, null: false + t.datetime :current_sign_in_at + t.datetime :last_sign_in_at + t.inet :current_sign_in_ip + t.inet :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20170203072335_create_boards.rb b/db/migrate/20170203072335_create_boards.rb new file mode 100644 index 00000000..46eaa02e --- /dev/null +++ b/db/migrate/20170203072335_create_boards.rb @@ -0,0 +1,10 @@ +class CreateBoards < ActiveRecord::Migration[5.0] + def change + create_table :boards do |t| + t.string :title + t.integer :user_id + + t.timestamps + end + end +end diff --git a/db/migrate/20170203072410_create_lists.rb b/db/migrate/20170203072410_create_lists.rb new file mode 100644 index 00000000..148a9298 --- /dev/null +++ b/db/migrate/20170203072410_create_lists.rb @@ -0,0 +1,10 @@ +class CreateLists < ActiveRecord::Migration[5.0] + def change + create_table :lists do |t| + t.string :title + t.integer :board_id + + t.timestamps + end + end +end diff --git a/db/migrate/20170203072513_create_cards.rb b/db/migrate/20170203072513_create_cards.rb new file mode 100644 index 00000000..098bd834 --- /dev/null +++ b/db/migrate/20170203072513_create_cards.rb @@ -0,0 +1,11 @@ +class CreateCards < ActiveRecord::Migration[5.0] + def change + create_table :cards do |t| + t.string :title + t.text :desc + t.integer :list_id + + t.timestamps + end + end +end diff --git a/db/migrate/20170203072606_create_members.rb b/db/migrate/20170203072606_create_members.rb new file mode 100644 index 00000000..37738c31 --- /dev/null +++ b/db/migrate/20170203072606_create_members.rb @@ -0,0 +1,11 @@ +class CreateMembers < ActiveRecord::Migration[5.0] + def change + create_table :members do |t| + t.integer :user_id + t.integer :card_id + + t.timestamps + end + add_index :members, [:user_id, :card_id], unique: true + end +end diff --git a/db/migrate/20170210025118_add_desc_to_lists.rb b/db/migrate/20170210025118_add_desc_to_lists.rb new file mode 100644 index 00000000..bd05df0d --- /dev/null +++ b/db/migrate/20170210025118_add_desc_to_lists.rb @@ -0,0 +1,5 @@ +class AddDescToLists < ActiveRecord::Migration[5.0] + def change + add_column :lists, :desc, :text + end +end diff --git a/db/migrate/20170213030553_create_activities.rb b/db/migrate/20170213030553_create_activities.rb new file mode 100644 index 00000000..92c8fdba --- /dev/null +++ b/db/migrate/20170213030553_create_activities.rb @@ -0,0 +1,11 @@ +class CreateActivities < ActiveRecord::Migration[5.0] + def change + create_table :activities do |t| + t.text :activity + t.integer :user_id + t.integer :card_id + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 00000000..e21670bb --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,75 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 20170213030553) do + + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "activities", force: :cascade do |t| + t.text "activity" + t.integer "user_id" + t.integer "card_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "boards", force: :cascade do |t| + t.string "title" + t.integer "user_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "cards", force: :cascade do |t| + t.string "title" + t.text "desc" + t.integer "list_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "lists", force: :cascade do |t| + t.string "title" + t.integer "board_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.text "desc" + end + + create_table "members", force: :cascade do |t| + t.integer "user_id" + t.integer "card_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["user_id", "card_id"], name: "index_members_on_user_id_and_card_id", unique: true, using: :btree + end + + create_table "users", force: :cascade do |t| + t.string "username", default: "", null: false + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.integer "sign_in_count", default: 0, null: false + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.inet "current_sign_in_ip" + t.inet "last_sign_in_ip" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", unique: true, using: :btree + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree + end + +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 00000000..471cedb5 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,32 @@ +# User.destroy_all +Board.destroy_all +List.destroy_all +Card.destroy_all +Member.destroy_all + +MULTIPLIER = 5 + +puts "creating users..." +MULTIPLIER.times do + User.create(username: Faker::Name.name, email: Faker::Internet.email, + password: "password", password_confirmation: "password"); +end + +puts "creating boards..." +MULTIPLIER.times do + Board.create(title: Faker::Hipster.sentence(3, true), user_id: User.pluck(:id).sample); +end + +puts "creating lists..." +(5 * MULTIPLIER).times do + List.create(title: Faker::Hipster.sentence(3, true), desc: Faker::Hipster.paragraph, + board_id: Board.pluck(:id).sample); +end + +puts "creating cards..." +(10 * MULTIPLIER).times do + card = Card.create(title: Faker::Hipster.sentence(3, true), desc: Faker::Hipster.paragraph, + list_id: List.pluck(:id).sample); + card.card_member_ids = User.pluck(:id) +end + diff --git a/lib/assets/.keep b/lib/assets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 00000000..e69de29b diff --git a/log/.keep b/log/.keep new file mode 100644 index 00000000..e69de29b diff --git a/public/404.html b/public/404.html new file mode 100644 index 00000000..b612547f --- /dev/null +++ b/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/422.html b/public/422.html new file mode 100644 index 00000000..a21f82b3 --- /dev/null +++ b/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/500.html b/public/500.html new file mode 100644 index 00000000..061abc58 --- /dev/null +++ b/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/apple-touch-icon-precomposed.png b/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..e69de29b diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 00000000..e69de29b diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 00000000..e69de29b diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 00000000..3c9c7c01 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/public/templates/board_show.html b/public/templates/board_show.html new file mode 100644 index 00000000..39ef9b21 --- /dev/null +++ b/public/templates/board_show.html @@ -0,0 +1,28 @@ +
+
+
+

{{ list.title || "empty" }}

+ + {{ list.desc || "empty" }} +
+
+
+

{{ card.title }}

+
+
+ +
Add a Card
+
+
+ +
+
+ + Cancel +
+
+ +
+
+
+Add a List \ No newline at end of file diff --git a/public/templates/cardModal.html b/public/templates/cardModal.html new file mode 100644 index 00000000..30a73077 --- /dev/null +++ b/public/templates/cardModal.html @@ -0,0 +1,41 @@ + diff --git a/public/templates/dashboard.html b/public/templates/dashboard.html new file mode 100644 index 00000000..c2724bfc --- /dev/null +++ b/public/templates/dashboard.html @@ -0,0 +1,20 @@ +
+
+ + +
+
+ Delete Board | + New Board +
+
+
+

{{ currentBoard.title || "empty" }} +

+ + +
+ \ No newline at end of file diff --git a/spec/controllers/boards_controller_spec.rb b/spec/controllers/boards_controller_spec.rb new file mode 100644 index 00000000..6ba914cf --- /dev/null +++ b/spec/controllers/boards_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe BoardsController, type: :controller do + +end diff --git a/spec/controllers/cards_controller_spec.rb b/spec/controllers/cards_controller_spec.rb new file mode 100644 index 00000000..deda938d --- /dev/null +++ b/spec/controllers/cards_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe CardsController, type: :controller do + +end diff --git a/spec/controllers/lists_controller_spec.rb b/spec/controllers/lists_controller_spec.rb new file mode 100644 index 00000000..d8072588 --- /dev/null +++ b/spec/controllers/lists_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe ListsController, type: :controller do + +end diff --git a/spec/controllers/members_controller_spec.rb b/spec/controllers/members_controller_spec.rb new file mode 100644 index 00000000..2627288e --- /dev/null +++ b/spec/controllers/members_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe MembersController, type: :controller do + +end diff --git a/spec/controllers/static_pages_controller_spec.rb b/spec/controllers/static_pages_controller_spec.rb new file mode 100644 index 00000000..331c7250 --- /dev/null +++ b/spec/controllers/static_pages_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe StaticPagesController, type: :controller do + +end diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb new file mode 100644 index 00000000..e2c3d3b5 --- /dev/null +++ b/spec/controllers/users_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe UsersController, type: :controller do + +end diff --git a/spec/factories/activities.rb b/spec/factories/activities.rb new file mode 100644 index 00000000..0cc9712b --- /dev/null +++ b/spec/factories/activities.rb @@ -0,0 +1,7 @@ +FactoryGirl.define do + factory :activity do + activity "MyText" + user_id 1 + card_id 1 + end +end diff --git a/spec/factories/boards.rb b/spec/factories/boards.rb new file mode 100644 index 00000000..ab978567 --- /dev/null +++ b/spec/factories/boards.rb @@ -0,0 +1,6 @@ +FactoryGirl.define do + factory :board do + title "MyString" + user_id 1 + end +end diff --git a/spec/factories/cards.rb b/spec/factories/cards.rb new file mode 100644 index 00000000..f987c0af --- /dev/null +++ b/spec/factories/cards.rb @@ -0,0 +1,7 @@ +FactoryGirl.define do + factory :card do + title "MyString" + desc "MyText" + list_id 1 + end +end diff --git a/spec/factories/lists.rb b/spec/factories/lists.rb new file mode 100644 index 00000000..bb76dd60 --- /dev/null +++ b/spec/factories/lists.rb @@ -0,0 +1,6 @@ +FactoryGirl.define do + factory :list do + title "MyString" + board_id 1 + end +end diff --git a/spec/factories/members.rb b/spec/factories/members.rb new file mode 100644 index 00000000..22e47b4e --- /dev/null +++ b/spec/factories/members.rb @@ -0,0 +1,6 @@ +FactoryGirl.define do + factory :member do + user_id 1 + card_id 1 + end +end diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 00000000..96b2b0ce --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,5 @@ +FactoryGirl.define do + factory :user do + + end +end diff --git a/spec/helpers/boards_helper_spec.rb b/spec/helpers/boards_helper_spec.rb new file mode 100644 index 00000000..e5639ad2 --- /dev/null +++ b/spec/helpers/boards_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the BoardsHelper. For example: +# +# describe BoardsHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe BoardsHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/cards_helper_spec.rb b/spec/helpers/cards_helper_spec.rb new file mode 100644 index 00000000..cd756fa9 --- /dev/null +++ b/spec/helpers/cards_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the CardsHelper. For example: +# +# describe CardsHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe CardsHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/lists_helper_spec.rb b/spec/helpers/lists_helper_spec.rb new file mode 100644 index 00000000..022e789b --- /dev/null +++ b/spec/helpers/lists_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the ListsHelper. For example: +# +# describe ListsHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe ListsHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/members_helper_spec.rb b/spec/helpers/members_helper_spec.rb new file mode 100644 index 00000000..9019b391 --- /dev/null +++ b/spec/helpers/members_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the MembersHelper. For example: +# +# describe MembersHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe MembersHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/static_pages_helper_spec.rb b/spec/helpers/static_pages_helper_spec.rb new file mode 100644 index 00000000..85e45424 --- /dev/null +++ b/spec/helpers/static_pages_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the StaticPagesHelper. For example: +# +# describe StaticPagesHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe StaticPagesHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/users_helper_spec.rb b/spec/helpers/users_helper_spec.rb new file mode 100644 index 00000000..b2e34440 --- /dev/null +++ b/spec/helpers/users_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the UsersHelper. For example: +# +# describe UsersHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe UsersHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/activity_spec.rb b/spec/models/activity_spec.rb new file mode 100644 index 00000000..b80b07e7 --- /dev/null +++ b/spec/models/activity_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Activity, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/board_spec.rb b/spec/models/board_spec.rb new file mode 100644 index 00000000..77f3fe83 --- /dev/null +++ b/spec/models/board_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Board, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/card_spec.rb b/spec/models/card_spec.rb new file mode 100644 index 00000000..6f49b4ac --- /dev/null +++ b/spec/models/card_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Card, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/list_spec.rb b/spec/models/list_spec.rb new file mode 100644 index 00000000..47d98f6e --- /dev/null +++ b/spec/models/list_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe List, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/member_spec.rb b/spec/models/member_spec.rb new file mode 100644 index 00000000..de08dabb --- /dev/null +++ b/spec/models/member_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Member, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 00000000..47a31bb4 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/fixtures/.keep b/test/fixtures/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 00000000..e69de29b diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 00000000..92e39b2d --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 00000000..e69de29b diff --git a/vendor/assets/javascripts/.keep b/vendor/assets/javascripts/.keep new file mode 100644 index 00000000..e69de29b diff --git a/vendor/assets/javascripts/angular-modal-service.js b/vendor/assets/javascripts/angular-modal-service.js new file mode 100644 index 00000000..26e8b3c0 --- /dev/null +++ b/vendor/assets/javascripts/angular-modal-service.js @@ -0,0 +1,219 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports) { + + 'use strict'; + + // angularModalService.js + // + // Service for showing modal dialogs. + + /***** JSLint Config *****/ + /*global angular */ + (function () { + + 'use strict'; + + var module = angular.module('angularModalService', []); + + module.factory('ModalService', ['$animate', '$document', '$compile', '$controller', '$http', '$rootScope', '$q', '$templateRequest', '$timeout', function ($animate, $document, $compile, $controller, $http, $rootScope, $q, $templateRequest, $timeout) { + + function ModalService() { + + var self = this; + + // Returns a promise which gets the template, either + // from the template parameter or via a request to the + // template url parameter. + var getTemplate = function getTemplate(template, templateUrl) { + var deferred = $q.defer(); + if (template) { + deferred.resolve(template); + } else if (templateUrl) { + $templateRequest(templateUrl, true).then(function (template) { + deferred.resolve(template); + }, function (error) { + deferred.reject(error); + }); + } else { + deferred.reject("No template or templateUrl has been specified."); + } + return deferred.promise; + }; + + // Adds an element to the DOM as the last child of its container + // like append, but uses $animate to handle animations. Returns a + // promise that is resolved once all animation is complete. + var appendChild = function appendChild(parent, child) { + var children = parent.children(); + if (children.length > 0) { + return $animate.enter(child, parent, children[children.length - 1]); + } + return $animate.enter(child, parent); + }; + + self.showModal = function (options) { + + // Get the body of the document, we'll add the modal to this. + var body = angular.element($document[0].body); + + // Create a deferred we'll resolve when the modal is ready. + var deferred = $q.defer(); + + // Validate the input parameters. + var controllerName = options.controller; + if (!controllerName) { + deferred.reject("No controller has been specified."); + return deferred.promise; + } + + // Get the actual html of the template. + getTemplate(options.template, options.templateUrl).then(function (template) { + + // Create a new scope for the modal. + var modalScope = (options.scope || $rootScope).$new(); + var rootScopeOnClose = $rootScope.$on('$locationChangeSuccess', cleanUpClose); + + // Create the inputs object to the controller - this will include + // the scope, as well as all inputs provided. + // We will also create a deferred that is resolved with a provided + // close function. The controller can then call 'close(result)'. + // The controller can also provide a delay for closing - this is + // helpful if there are closing animations which must finish first. + var closeDeferred = $q.defer(); + var closedDeferred = $q.defer(); + var inputs = { + $scope: modalScope, + close: function close(result, delay) { + if (delay === undefined || delay === null) delay = 0; + $timeout(function () { + + cleanUpClose(result); + }, delay); + } + }; + + // If we have provided any inputs, pass them to the controller. + if (options.inputs) angular.extend(inputs, options.inputs); + + // Compile then link the template element, building the actual element. + // Set the $element on the inputs so that it can be injected if required. + var linkFn = $compile(template); + var modalElement = linkFn(modalScope); + inputs.$element = modalElement; + + // Create the controller, explicitly specifying the scope to use. + var controllerObjBefore = modalScope[options.controllerAs]; + var modalController = $controller(options.controller, inputs, false, options.controllerAs); + + if (options.controllerAs && controllerObjBefore) { + angular.extend(modalController, controllerObjBefore); + } + + // Finally, append the modal to the dom. + if (options.appendElement) { + // append to custom append element + appendChild(options.appendElement, modalElement); + } else { + // append to body when no custom append element is specified + appendChild(body, modalElement); + } + + // We now have a modal object... + var modal = { + controller: modalController, + scope: modalScope, + element: modalElement, + close: closeDeferred.promise, + closed: closedDeferred.promise + }; + + // ...which is passed to the caller via the promise. + deferred.resolve(modal); + + function cleanUpClose(result) { + + // Resolve the 'close' promise. + closeDeferred.resolve(result); + + // Let angular remove the element and wait for animations to finish. + $animate.leave(modalElement).then(function () { + // Resolve the 'closed' promise. + closedDeferred.resolve(result); + + // We can now clean up the scope + modalScope.$destroy(); + + // Unless we null out all of these objects we seem to suffer + // from memory leaks, if anyone can explain why then I'd + // be very interested to know. + inputs.close = null; + deferred = null; + closeDeferred = null; + modal = null; + inputs = null; + modalElement = null; + modalScope = null; + }); + + // remove event watcher + rootScopeOnClose && rootScopeOnClose(); + } + }).then(null, function (error) { + // 'catch' doesn't work in IE8. + deferred.reject(error); + }); + + return deferred.promise; + }; + } + + return new ModalService(); + }]); + })(); + +/***/ } +/******/ ]); +//# sourceMappingURL=angular-modal-service.js.map \ No newline at end of file diff --git a/vendor/assets/javascripts/angular-modal-service.js.map b/vendor/assets/javascripts/angular-modal-service.js.map new file mode 100644 index 00000000..a8baa5a0 --- /dev/null +++ b/vendor/assets/javascripts/angular-modal-service.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/bootstrap b2938a098e2d498408cb","webpack:///./src/angular-modal-service.js"],"names":[],"mappings":";AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;AChCC,cAAW;;AAEV;;AAEA,OAAI,SAAS,QAAQ,MAAR,CAAe,qBAAf,EAAsC,EAAtC,CAAb;;AAEA,UAAO,OAAP,CAAe,cAAf,EAA+B,CAAC,UAAD,EAAa,WAAb,EAA0B,UAA1B,EAAsC,aAAtC,EAAqD,OAArD,EAA8D,YAA9D,EAA4E,IAA5E,EAAkF,kBAAlF,EAAsG,UAAtG,EAC7B,UAAS,QAAT,EAAmB,SAAnB,EAA8B,QAA9B,EAAwC,WAAxC,EAAqD,KAArD,EAA4D,UAA5D,EAAwE,EAAxE,EAA4E,gBAA5E,EAA8F,QAA9F,EAAwG;;AAExG,cAAS,YAAT,GAAwB;;AAEtB,WAAI,OAAO,IAAX;;;;;AAKA,WAAI,cAAc,SAAd,WAAc,CAAS,QAAT,EAAmB,WAAnB,EAAgC;AAChD,aAAI,WAAW,GAAG,KAAH,EAAf;AACA,aAAI,QAAJ,EAAc;AACZ,oBAAS,OAAT,CAAiB,QAAjB;AACD,UAFD,MAEO,IAAI,WAAJ,EAAiB;AACtB,4BAAiB,WAAjB,EAA8B,IAA9B,EACG,IADH,CACQ,UAAS,QAAT,EAAmB;AACvB,sBAAS,OAAT,CAAiB,QAAjB;AACD,YAHH,EAGK,UAAS,KAAT,EAAgB;AACjB,sBAAS,MAAT,CAAgB,KAAhB;AACD,YALH;AAMD,UAPM,MAOA;AACL,oBAAS,MAAT,CAAgB,gDAAhB;AACD;AACD,gBAAO,SAAS,OAAhB;AACD,QAfD;;;;;AAoBA,WAAI,cAAc,SAAd,WAAc,CAAS,MAAT,EAAiB,KAAjB,EAAwB;AACxC,aAAI,WAAW,OAAO,QAAP,EAAf;AACA,aAAI,SAAS,MAAT,GAAkB,CAAtB,EAAyB;AACvB,kBAAO,SAAS,KAAT,CAAe,KAAf,EAAsB,MAAtB,EAA8B,SAAS,SAAS,MAAT,GAAkB,CAA3B,CAA9B,CAAP;AACD;AACD,gBAAO,SAAS,KAAT,CAAe,KAAf,EAAsB,MAAtB,CAAP;AACD,QAND;;AAQA,YAAK,SAAL,GAAiB,UAAS,OAAT,EAAkB;;;AAGjC,aAAI,OAAO,QAAQ,OAAR,CAAgB,UAAU,CAAV,EAAa,IAA7B,CAAX;;;AAGA,aAAI,WAAW,GAAG,KAAH,EAAf;;;AAGA,aAAI,iBAAiB,QAAQ,UAA7B;AACA,aAAI,CAAC,cAAL,EAAqB;AACnB,oBAAS,MAAT,CAAgB,mCAAhB;AACA,kBAAO,SAAS,OAAhB;AACD;;;AAGD,qBAAY,QAAQ,QAApB,EAA8B,QAAQ,WAAtC,EACG,IADH,CACQ,UAAS,QAAT,EAAmB;;;AAGvB,eAAI,aAAa,CAAC,QAAQ,KAAR,IAAiB,UAAlB,EAA8B,IAA9B,EAAjB;AACA,eAAI,mBAAmB,WAAW,GAAX,CAAe,wBAAf,EAAyC,YAAzC,CAAvB;;;;;;;;AAQA,eAAI,gBAAgB,GAAG,KAAH,EAApB;AACA,eAAI,iBAAiB,GAAG,KAAH,EAArB;AACA,eAAI,SAAS;AACX,qBAAQ,UADG;AAEX,oBAAO,eAAS,MAAT,EAAiB,KAAjB,EAAwB;AAC7B,mBAAI,UAAU,SAAV,IAAuB,UAAU,IAArC,EAA2C,QAAQ,CAAR;AAC3C,wBAAS,YAAW;;AAElB,8BAAa,MAAb;AAED,gBAJD,EAIG,KAJH;AAKD;AATU,YAAb;;;AAaA,eAAI,QAAQ,MAAZ,EAAoB,QAAQ,MAAR,CAAe,MAAf,EAAuB,QAAQ,MAA/B;;;;AAIpB,eAAI,SAAS,SAAS,QAAT,CAAb;AACA,eAAI,eAAe,OAAO,UAAP,CAAnB;AACA,kBAAO,QAAP,GAAkB,YAAlB;;;AAGA,eAAI,sBAAsB,WAAW,QAAQ,YAAnB,CAA1B;AACA,eAAI,kBAAkB,YAAY,QAAQ,UAApB,EAAgC,MAAhC,EAAwC,KAAxC,EAA+C,QAAQ,YAAvD,CAAtB;;AAEA,eAAI,QAAQ,YAAR,IAAwB,mBAA5B,EAAiD;AAC/C,qBAAQ,MAAR,CAAe,eAAf,EAAgC,mBAAhC;AACD;;;AAGD,eAAI,QAAQ,aAAZ,EAA2B;;AAEzB,yBAAY,QAAQ,aAApB,EAAmC,YAAnC;AACD,YAHD,MAGO;;AAEL,yBAAY,IAAZ,EAAkB,YAAlB;AACD;;;AAGD,eAAI,QAAQ;AACV,yBAAY,eADF;AAEV,oBAAO,UAFG;AAGV,sBAAS,YAHC;AAIV,oBAAO,cAAc,OAJX;AAKV,qBAAQ,eAAe;AALb,YAAZ;;;AASA,oBAAS,OAAT,CAAiB,KAAjB;;AAEA,oBAAS,YAAT,CAAsB,MAAtB,EAA8B;;;AAG5B,2BAAc,OAAd,CAAsB,MAAtB;;;AAGA,sBAAS,KAAT,CAAe,YAAf,EACS,IADT,CACc,YAAY;;AAEhB,8BAAe,OAAf,CAAuB,MAAvB;;;AAGA,0BAAW,QAAX;;;;;AAKA,sBAAO,KAAP,GAAe,IAAf;AACA,0BAAW,IAAX;AACA,+BAAgB,IAAhB;AACA,uBAAQ,IAAR;AACA,wBAAS,IAAT;AACA,8BAAe,IAAf;AACA,4BAAa,IAAb;AACD,cAlBT;;;AAqBA,iCAAoB,kBAApB;AACD;AAEF,UA/FH,EAgGG,IAhGH,CAgGQ,IAhGR,EAgGc,UAAS,KAAT,EAAgB;;AAC1B,oBAAS,MAAT,CAAgB,KAAhB;AACD,UAlGH;;AAoGA,gBAAO,SAAS,OAAhB;AACD,QArHD;AAuHD;;AAED,YAAO,IAAI,YAAJ,EAAP;AACD,IAhK8B,CAA/B;AAkKD,EAxKA,GAAD,C","file":"angular-modal-service.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap b2938a098e2d498408cb\n **/","// angularModalService.js\n//\n// Service for showing modal dialogs.\n\n/***** JSLint Config *****/\n/*global angular */\n(function() {\n\n 'use strict';\n\n var module = angular.module('angularModalService', []);\n\n module.factory('ModalService', ['$animate', '$document', '$compile', '$controller', '$http', '$rootScope', '$q', '$templateRequest', '$timeout',\n function($animate, $document, $compile, $controller, $http, $rootScope, $q, $templateRequest, $timeout) {\n\n function ModalService() {\n\n var self = this;\n\n // Returns a promise which gets the template, either\n // from the template parameter or via a request to the\n // template url parameter.\n var getTemplate = function(template, templateUrl) {\n var deferred = $q.defer();\n if (template) {\n deferred.resolve(template);\n } else if (templateUrl) {\n $templateRequest(templateUrl, true)\n .then(function(template) {\n deferred.resolve(template);\n }, function(error) {\n deferred.reject(error);\n });\n } else {\n deferred.reject(\"No template or templateUrl has been specified.\");\n }\n return deferred.promise;\n };\n\n // Adds an element to the DOM as the last child of its container\n // like append, but uses $animate to handle animations. Returns a\n // promise that is resolved once all animation is complete.\n var appendChild = function(parent, child) {\n var children = parent.children();\n if (children.length > 0) {\n return $animate.enter(child, parent, children[children.length - 1]);\n }\n return $animate.enter(child, parent);\n };\n\n self.showModal = function(options) {\n\n // Get the body of the document, we'll add the modal to this.\n var body = angular.element($document[0].body);\n\n // Create a deferred we'll resolve when the modal is ready.\n var deferred = $q.defer();\n\n // Validate the input parameters.\n var controllerName = options.controller;\n if (!controllerName) {\n deferred.reject(\"No controller has been specified.\");\n return deferred.promise;\n }\n\n // Get the actual html of the template.\n getTemplate(options.template, options.templateUrl)\n .then(function(template) {\n\n // Create a new scope for the modal.\n var modalScope = (options.scope || $rootScope).$new();\n var rootScopeOnClose = $rootScope.$on('$locationChangeSuccess', cleanUpClose);\n\n // Create the inputs object to the controller - this will include\n // the scope, as well as all inputs provided.\n // We will also create a deferred that is resolved with a provided\n // close function. The controller can then call 'close(result)'.\n // The controller can also provide a delay for closing - this is\n // helpful if there are closing animations which must finish first.\n var closeDeferred = $q.defer();\n var closedDeferred = $q.defer();\n var inputs = {\n $scope: modalScope,\n close: function(result, delay) {\n if (delay === undefined || delay === null) delay = 0;\n $timeout(function() {\n\n cleanUpClose(result);\n\n }, delay);\n }\n };\n\n // If we have provided any inputs, pass them to the controller.\n if (options.inputs) angular.extend(inputs, options.inputs);\n\n // Compile then link the template element, building the actual element.\n // Set the $element on the inputs so that it can be injected if required.\n var linkFn = $compile(template);\n var modalElement = linkFn(modalScope);\n inputs.$element = modalElement;\n\n // Create the controller, explicitly specifying the scope to use.\n var controllerObjBefore = modalScope[options.controllerAs];\n var modalController = $controller(options.controller, inputs, false, options.controllerAs);\n\n if (options.controllerAs && controllerObjBefore) {\n angular.extend(modalController, controllerObjBefore);\n }\n\n // Finally, append the modal to the dom.\n if (options.appendElement) {\n // append to custom append element\n appendChild(options.appendElement, modalElement);\n } else {\n // append to body when no custom append element is specified\n appendChild(body, modalElement);\n }\n\n // We now have a modal object...\n var modal = {\n controller: modalController,\n scope: modalScope,\n element: modalElement,\n close: closeDeferred.promise,\n closed: closedDeferred.promise\n };\n\n // ...which is passed to the caller via the promise.\n deferred.resolve(modal);\n\n function cleanUpClose(result) {\n\n // Resolve the 'close' promise.\n closeDeferred.resolve(result);\n\n // Let angular remove the element and wait for animations to finish.\n $animate.leave(modalElement)\n .then(function () {\n // Resolve the 'closed' promise.\n closedDeferred.resolve(result);\n\n // We can now clean up the scope\n modalScope.$destroy();\n\n // Unless we null out all of these objects we seem to suffer\n // from memory leaks, if anyone can explain why then I'd\n // be very interested to know.\n inputs.close = null;\n deferred = null;\n closeDeferred = null;\n modal = null;\n inputs = null;\n modalElement = null;\n modalScope = null;\n });\n\n // remove event watcher\n rootScopeOnClose && rootScopeOnClose();\n }\n\n })\n .then(null, function(error) { // 'catch' doesn't work in IE8.\n deferred.reject(error);\n });\n\n return deferred.promise;\n };\n\n }\n\n return new ModalService();\n }]);\n\n}());\n\n\n\n/** WEBPACK FOOTER **\n ** ./src/angular-modal-service.js\n **/"],"sourceRoot":""} diff --git a/vendor/assets/javascripts/angular-ui-router.js b/vendor/assets/javascripts/angular-ui-router.js new file mode 100644 index 00000000..b6a3d5f8 --- /dev/null +++ b/vendor/assets/javascripts/angular-ui-router.js @@ -0,0 +1,4684 @@ +/** + * State-based routing for AngularJS + * @version v0.4.2 + * @link http://angular-ui.github.com/ + * @license MIT License, http://www.opensource.org/licenses/MIT + */ + +/* commonjs package manager support (eg componentjs) */ +if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ + module.exports = 'ui.router'; +} + +(function (window, angular, undefined) { +/*jshint globalstrict:true*/ +/*global angular:false*/ +'use strict'; + +var isDefined = angular.isDefined, + isFunction = angular.isFunction, + isString = angular.isString, + isObject = angular.isObject, + isArray = angular.isArray, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy, + toJson = angular.toJson; + +function inherit(parent, extra) { + return extend(new (extend(function() {}, { prototype: parent }))(), extra); +} + +function merge(dst) { + forEach(arguments, function(obj) { + if (obj !== dst) { + forEach(obj, function(value, key) { + if (!dst.hasOwnProperty(key)) dst[key] = value; + }); + } + }); + return dst; +} + +/** + * Finds the common ancestor path between two states. + * + * @param {Object} first The first state. + * @param {Object} second The second state. + * @return {Array} Returns an array of state names in descending order, not including the root. + */ +function ancestors(first, second) { + var path = []; + + for (var n in first.path) { + if (first.path[n] !== second.path[n]) break; + path.push(first.path[n]); + } + return path; +} + +/** + * IE8-safe wrapper for `Object.keys()`. + * + * @param {Object} object A JavaScript object. + * @return {Array} Returns the keys of the object as an array. + */ +function objectKeys(object) { + if (Object.keys) { + return Object.keys(object); + } + var result = []; + + forEach(object, function(val, key) { + result.push(key); + }); + return result; +} + +/** + * IE8-safe wrapper for `Array.prototype.indexOf()`. + * + * @param {Array} array A JavaScript array. + * @param {*} value A value to search the array for. + * @return {Number} Returns the array index value of `value`, or `-1` if not present. + */ +function indexOf(array, value) { + if (Array.prototype.indexOf) { + return array.indexOf(value, Number(arguments[2]) || 0); + } + var len = array.length >>> 0, from = Number(arguments[2]) || 0; + from = (from < 0) ? Math.ceil(from) : Math.floor(from); + + if (from < 0) from += len; + + for (; from < len; from++) { + if (from in array && array[from] === value) return from; + } + return -1; +} + +/** + * Merges a set of parameters with all parameters inherited between the common parents of the + * current state and a given destination state. + * + * @param {Object} currentParams The value of the current state parameters ($stateParams). + * @param {Object} newParams The set of parameters which will be composited with inherited params. + * @param {Object} $current Internal definition of object representing the current state. + * @param {Object} $to Internal definition of object representing state to transition to. + */ +function inheritParams(currentParams, newParams, $current, $to) { + var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; + + for (var i in parents) { + if (!parents[i] || !parents[i].params) continue; + parentParams = objectKeys(parents[i].params); + if (!parentParams.length) continue; + + for (var j in parentParams) { + if (indexOf(inheritList, parentParams[j]) >= 0) continue; + inheritList.push(parentParams[j]); + inherited[parentParams[j]] = currentParams[parentParams[j]]; + } + } + return extend({}, inherited, newParams); +} + +/** + * Performs a non-strict comparison of the subset of two objects, defined by a list of keys. + * + * @param {Object} a The first object. + * @param {Object} b The second object. + * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, + * it defaults to the list of keys in `a`. + * @return {Boolean} Returns `true` if the keys match, otherwise `false`. + */ +function equalForKeys(a, b, keys) { + if (!keys) { + keys = []; + for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility + } + + for (var i=0; i + * + * + * + * + * + * + * + * + * + * + * + * + */ +angular.module('ui.router', ['ui.router.state']); + +angular.module('ui.router.compat', ['ui.router']); + +/** + * @ngdoc object + * @name ui.router.util.$resolve + * + * @requires $q + * @requires $injector + * + * @description + * Manages resolution of (acyclic) graphs of promises. + */ +$Resolve.$inject = ['$q', '$injector']; +function $Resolve( $q, $injector) { + + var VISIT_IN_PROGRESS = 1, + VISIT_DONE = 2, + NOTHING = {}, + NO_DEPENDENCIES = [], + NO_LOCALS = NOTHING, + NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING }); + + + /** + * @ngdoc function + * @name ui.router.util.$resolve#study + * @methodOf ui.router.util.$resolve + * + * @description + * Studies a set of invocables that are likely to be used multiple times. + *
+   * $resolve.study(invocables)(locals, parent, self)
+   * 
+ * is equivalent to + *
+   * $resolve.resolve(invocables, locals, parent, self)
+   * 
+ * but the former is more efficient (in fact `resolve` just calls `study` + * internally). + * + * @param {object} invocables Invocable objects + * @return {function} a function to pass in locals, parent and self + */ + this.study = function (invocables) { + if (!isObject(invocables)) throw new Error("'invocables' must be an object"); + var invocableKeys = objectKeys(invocables || {}); + + // Perform a topological sort of invocables to build an ordered plan + var plan = [], cycle = [], visited = {}; + function visit(value, key) { + if (visited[key] === VISIT_DONE) return; + + cycle.push(key); + if (visited[key] === VISIT_IN_PROGRESS) { + cycle.splice(0, indexOf(cycle, key)); + throw new Error("Cyclic dependency: " + cycle.join(" -> ")); + } + visited[key] = VISIT_IN_PROGRESS; + + if (isString(value)) { + plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES); + } else { + var params = $injector.annotate(value); + forEach(params, function (param) { + if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); + }); + plan.push(key, value, params); + } + + cycle.pop(); + visited[key] = VISIT_DONE; + } + forEach(invocables, visit); + invocables = cycle = visited = null; // plan is all that's required + + function isResolve(value) { + return isObject(value) && value.then && value.$$promises; + } + + return function (locals, parent, self) { + if (isResolve(locals) && self === undefined) { + self = parent; parent = locals; locals = null; + } + if (!locals) locals = NO_LOCALS; + else if (!isObject(locals)) { + throw new Error("'locals' must be an object"); + } + if (!parent) parent = NO_PARENT; + else if (!isResolve(parent)) { + throw new Error("'parent' must be a promise returned by $resolve.resolve()"); + } + + // To complete the overall resolution, we have to wait for the parent + // promise and for the promise for each invokable in our plan. + var resolution = $q.defer(), + result = silenceUncaughtInPromise(resolution.promise), + promises = result.$$promises = {}, + values = extend({}, locals), + wait = 1 + plan.length/3, + merged = false; + + silenceUncaughtInPromise(result); + + function done() { + // Merge parent values we haven't got yet and publish our own $$values + if (!--wait) { + if (!merged) merge(values, parent.$$values); + result.$$values = values; + result.$$promises = result.$$promises || true; // keep for isResolve() + delete result.$$inheritedValues; + resolution.resolve(values); + } + } + + function fail(reason) { + result.$$failure = reason; + resolution.reject(reason); + } + + // Short-circuit if parent has already failed + if (isDefined(parent.$$failure)) { + fail(parent.$$failure); + return result; + } + + if (parent.$$inheritedValues) { + merge(values, omit(parent.$$inheritedValues, invocableKeys)); + } + + // Merge parent values if the parent has already resolved, or merge + // parent promises and wait if the parent resolve is still in progress. + extend(promises, parent.$$promises); + if (parent.$$values) { + merged = merge(values, omit(parent.$$values, invocableKeys)); + result.$$inheritedValues = omit(parent.$$values, invocableKeys); + done(); + } else { + if (parent.$$inheritedValues) { + result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys); + } + parent.then(done, fail); + } + + // Process each invocable in the plan, but ignore any where a local of the same name exists. + for (var i=0, ii=plan.length; i + * Impact on loading templates for more details about this mechanism. + * + * @param {boolean} value + */ + this.shouldUnsafelyUseHttp = function(value) { + shouldUnsafelyUseHttp = !!value; + }; + + /** + * @ngdoc object + * @name ui.router.util.$templateFactory + * + * @requires $http + * @requires $templateCache + * @requires $injector + * + * @description + * Service. Manages loading of templates. + */ + this.$get = ['$http', '$templateCache', '$injector', function($http, $templateCache, $injector){ + return new TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp);}]; +} + + +/** + * @ngdoc object + * @name ui.router.util.$templateFactory + * + * @requires $http + * @requires $templateCache + * @requires $injector + * + * @description + * Service. Manages loading of templates. + */ +function TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp) { + + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromConfig + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template from a configuration object. + * + * @param {object} config Configuration object for which to load a template. + * The following properties are search in the specified order, and the first one + * that is defined is used to create the template: + * + * @param {string|object} config.template html string template or function to + * load via {@link ui.router.util.$templateFactory#fromString fromString}. + * @param {string|object} config.templateUrl url to load or a function returning + * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}. + * @param {Function} config.templateProvider function to invoke via + * {@link ui.router.util.$templateFactory#fromProvider fromProvider}. + * @param {object} params Parameters to pass to the template function. + * @param {object} locals Locals to pass to `invoke` if the template is loaded + * via a `templateProvider`. Defaults to `{ params: params }`. + * + * @return {string|object} The template html as a string, or a promise for + * that string,or `null` if no template is configured. + */ + this.fromConfig = function (config, params, locals) { + return ( + isDefined(config.template) ? this.fromString(config.template, params) : + isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) : + isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) : + null + ); + }; + + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromString + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template from a string or a function returning a string. + * + * @param {string|object} template html template as a string or function that + * returns an html template as a string. + * @param {object} params Parameters to pass to the template function. + * + * @return {string|object} The template html as a string, or a promise for that + * string. + */ + this.fromString = function (template, params) { + return isFunction(template) ? template(params) : template; + }; + + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromUrl + * @methodOf ui.router.util.$templateFactory + * + * @description + * Loads a template from the a URL via `$http` and `$templateCache`. + * + * @param {string|Function} url url of the template to load, or a function + * that returns a url. + * @param {Object} params Parameters to pass to the url function. + * @return {string|Promise.} The template html as a string, or a promise + * for that string. + */ + this.fromUrl = function (url, params) { + if (isFunction(url)) url = url(params); + if (url == null) return null; + else { + if(!shouldUnsafelyUseHttp) { + return $injector.get('$templateRequest')(url); + } else { + return $http + .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }}) + .then(function(response) { return response.data; }); + } + } + }; + + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromProvider + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template by invoking an injectable provider function. + * + * @param {Function} provider Function to invoke via `$injector.invoke` + * @param {Object} params Parameters for the template. + * @param {Object} locals Locals to pass to `invoke`. Defaults to + * `{ params: params }`. + * @return {string|Promise.} The template html as a string, or a promise + * for that string. + */ + this.fromProvider = function (provider, params, locals) { + return $injector.invoke(provider, null, locals || { params: params }); + }; +} + +angular.module('ui.router.util').provider('$templateFactory', TemplateFactoryProvider); + +var $$UMFP; // reference to $UrlMatcherFactoryProvider + +/** + * @ngdoc object + * @name ui.router.util.type:UrlMatcher + * + * @description + * Matches URLs against patterns and extracts named parameters from the path or the search + * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list + * of search parameters. Multiple search parameter names are separated by '&'. Search parameters + * do not influence whether or not a URL is matched, but their values are passed through into + * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. + * + * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace + * syntax, which optionally allows a regular expression for the parameter to be specified: + * + * * `':'` name - colon placeholder + * * `'*'` name - catch-all placeholder + * * `'{' name '}'` - curly placeholder + * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the + * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. + * + * Parameter names may contain only word characters (latin letters, digits, and underscore) and + * must be unique within the pattern (across both path and search parameters). For colon + * placeholders or curly placeholders without an explicit regexp, a path parameter matches any + * number of characters other than '/'. For catch-all placeholders the path parameter matches + * any number of characters. + * + * Examples: + * + * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for + * trailing slashes, and patterns have to match the entire path, not just a prefix. + * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or + * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. + * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. + * * `'/user/{id:[^/]*}'` - Same as the previous example. + * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id + * parameter consists of 1 to 8 hex digits. + * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the + * path into the parameter 'path'. + * * `'/files/*path'` - ditto. + * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined + * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start + * + * @param {string} pattern The pattern to compile into a matcher. + * @param {Object} config A configuration object hash: + * @param {Object=} parentMatcher Used to concatenate the pattern/config onto + * an existing UrlMatcher + * + * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`. + * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`. + * + * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any + * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns + * non-null) will start with this prefix. + * + * @property {string} source The pattern that was passed into the constructor + * + * @property {string} sourcePath The path portion of the source property + * + * @property {string} sourceSearch The search portion of the source property + * + * @property {string} regex The constructed regex that will be used to match against the url when + * it is time to determine which url will match. + * + * @returns {Object} New `UrlMatcher` object + */ +function UrlMatcher(pattern, config, parentMatcher) { + config = extend({ params: {} }, isObject(config) ? config : {}); + + // Find all placeholders and create a compiled pattern, using either classic or curly syntax: + // '*' name + // ':' name + // '{' name '}' + // '{' name ':' regexp '}' + // The regular expression is somewhat complicated due to the need to allow curly braces + // inside the regular expression. The placeholder regexp breaks down as follows: + // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) + // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case + // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either + // [^{}\\]+ - anything other than curly braces or backslash + // \\. - a backslash escape + // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms + var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + compiled = '^', last = 0, m, + segments = this.segments = [], + parentParams = parentMatcher ? parentMatcher.params : {}, + params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(), + paramNames = []; + + function addParameter(id, type, config, location) { + paramNames.push(id); + if (parentParams[id]) return parentParams[id]; + if (!/^\w+([-.]+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); + if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); + params[id] = new $$UMFP.Param(id, type, config, location); + return params[id]; + } + + function quoteRegExp(string, pattern, squash, optional) { + var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); + if (!pattern) return result; + switch(squash) { + case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break; + case true: + result = result.replace(/\/$/, ''); + surroundPattern = ['(?:\/(', ')|\/)?']; + break; + default: surroundPattern = ['(' + squash + "|", ')?']; break; + } + return result + surroundPattern[0] + pattern + surroundPattern[1]; + } + + this.source = pattern; + + // Split into static segments separated by path parameter placeholders. + // The number of segments is always 1 more than the number of parameters. + function matchDetails(m, isSearch) { + var id, regexp, segment, type, cfg, arrayMode; + id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null + cfg = config.params[id]; + segment = pattern.substring(last, m.index); + regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null); + + if (regexp) { + type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) }); + } + + return { + id: id, regexp: regexp, segment: segment, type: type, cfg: cfg + }; + } + + var p, param, segment; + while ((m = placeholder.exec(pattern))) { + p = matchDetails(m, false); + if (p.segment.indexOf('?') >= 0) break; // we're into the search part + + param = addParameter(p.id, p.type, p.cfg, "path"); + compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional); + segments.push(p.segment); + last = placeholder.lastIndex; + } + segment = pattern.substring(last); + + // Find any search parameter names and remove them from the last segment + var i = segment.indexOf('?'); + + if (i >= 0) { + var search = this.sourceSearch = segment.substring(i); + segment = segment.substring(0, i); + this.sourcePath = pattern.substring(0, last + i); + + if (search.length > 0) { + last = 0; + while ((m = searchPlaceholder.exec(search))) { + p = matchDetails(m, true); + param = addParameter(p.id, p.type, p.cfg, "search"); + last = placeholder.lastIndex; + // check if ?& + } + } + } else { + this.sourcePath = pattern; + this.sourceSearch = ''; + } + + compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$'; + segments.push(segment); + + this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined); + this.prefix = segments[0]; + this.$$paramNames = paramNames; +} + +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#concat + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Returns a new matcher for a pattern constructed by appending the path part and adding the + * search parameters of the specified pattern to this pattern. The current pattern is not + * modified. This can be understood as creating a pattern for URLs that are relative to (or + * suffixes of) the current pattern. + * + * @example + * The following two matchers are equivalent: + *
+ * new UrlMatcher('/user/{id}?q').concat('/details?date');
+ * new UrlMatcher('/user/{id}/details?q&date');
+ * 
+ * + * @param {string} pattern The pattern to append. + * @param {Object} config An object hash of the configuration for the matcher. + * @returns {UrlMatcher} A matcher for the concatenated pattern. + */ +UrlMatcher.prototype.concat = function (pattern, config) { + // Because order of search parameters is irrelevant, we can add our own search + // parameters to the end of the new pattern. Parse the new pattern by itself + // and then join the bits together, but it's much easier to do this on a string level. + var defaultConfig = { + caseInsensitive: $$UMFP.caseInsensitive(), + strict: $$UMFP.strictMode(), + squash: $$UMFP.defaultSquashPolicy() + }; + return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this); +}; + +UrlMatcher.prototype.toString = function () { + return this.source; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#exec + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Tests the specified path against this matcher, and returns an object containing the captured + * parameter values, or null if the path does not match. The returned object contains the values + * of any search parameters that are mentioned in the pattern, but their value may be null if + * they are not present in `searchParams`. This means that search parameters are always treated + * as optional. + * + * @example + *
+ * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
+ *   x: '1', q: 'hello'
+ * });
+ * // returns { id: 'bob', q: 'hello', r: null }
+ * 
+ * + * @param {string} path The URL path to match, e.g. `$location.path()`. + * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. + * @returns {Object} The captured parameter values. + */ +UrlMatcher.prototype.exec = function (path, searchParams) { + var m = this.regexp.exec(path); + if (!m) return null; + searchParams = searchParams || {}; + + var paramNames = this.parameters(), nTotal = paramNames.length, + nPath = this.segments.length - 1, + values = {}, i, j, cfg, paramName; + + if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); + + function decodePathArray(string) { + function reverseString(str) { return str.split("").reverse().join(""); } + function unquoteDashes(str) { return str.replace(/\\-/g, "-"); } + + var split = reverseString(string).split(/-(?!\\)/); + var allReversed = map(split, reverseString); + return map(allReversed, unquoteDashes).reverse(); + } + + var param, paramVal; + for (i = 0; i < nPath; i++) { + paramName = paramNames[i]; + param = this.params[paramName]; + paramVal = m[i+1]; + // if the param value matches a pre-replace pair, replace the value before decoding. + for (j = 0; j < param.replace.length; j++) { + if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; + } + if (paramVal && param.array === true) paramVal = decodePathArray(paramVal); + if (isDefined(paramVal)) paramVal = param.type.decode(paramVal); + values[paramName] = param.value(paramVal); + } + for (/**/; i < nTotal; i++) { + paramName = paramNames[i]; + values[paramName] = this.params[paramName].value(searchParams[paramName]); + param = this.params[paramName]; + paramVal = searchParams[paramName]; + for (j = 0; j < param.replace.length; j++) { + if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; + } + if (isDefined(paramVal)) paramVal = param.type.decode(paramVal); + values[paramName] = param.value(paramVal); + } + + return values; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#parameters + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Returns the names of all path and search parameters of this pattern in an unspecified order. + * + * @returns {Array.} An array of parameter names. Must be treated as read-only. If the + * pattern has no parameters, an empty array is returned. + */ +UrlMatcher.prototype.parameters = function (param) { + if (!isDefined(param)) return this.$$paramNames; + return this.params[param] || null; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#validates + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Checks an object hash of parameters to validate their correctness according to the parameter + * types of this `UrlMatcher`. + * + * @param {Object} params The object hash of parameters to validate. + * @returns {boolean} Returns `true` if `params` validates, otherwise `false`. + */ +UrlMatcher.prototype.validates = function (params) { + return this.params.$$validates(params); +}; + +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#format + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Creates a URL that matches this pattern by substituting the specified values + * for the path and search parameters. Null values for path parameters are + * treated as empty strings. + * + * @example + *
+ * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
+ * // returns '/user/bob?q=yes'
+ * 
+ * + * @param {Object} values the values to substitute for the parameters in this pattern. + * @returns {string} the formatted URL (path and optionally search part). + */ +UrlMatcher.prototype.format = function (values) { + values = values || {}; + var segments = this.segments, params = this.parameters(), paramset = this.params; + if (!this.validates(values)) return null; + + var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0]; + + function encodeDashes(str) { // Replace dashes with encoded "\-" + return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); }); + } + + for (i = 0; i < nTotal; i++) { + var isPathParam = i < nPath; + var name = params[i], param = paramset[name], value = param.value(values[name]); + var isDefaultValue = param.isOptional && param.type.equals(param.value(), value); + var squash = isDefaultValue ? param.squash : false; + var encoded = param.type.encode(value); + + if (isPathParam) { + var nextSegment = segments[i + 1]; + var isFinalPathParam = i + 1 === nPath; + + if (squash === false) { + if (encoded != null) { + if (isArray(encoded)) { + result += map(encoded, encodeDashes).join("-"); + } else { + result += encodeURIComponent(encoded); + } + } + result += nextSegment; + } else if (squash === true) { + var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/; + result += nextSegment.match(capture)[1]; + } else if (isString(squash)) { + result += squash + nextSegment; + } + + if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1); + } else { + if (encoded == null || (isDefaultValue && squash !== false)) continue; + if (!isArray(encoded)) encoded = [ encoded ]; + if (encoded.length === 0) continue; + encoded = map(encoded, encodeURIComponent).join('&' + name + '='); + result += (search ? '&' : '?') + (name + '=' + encoded); + search = true; + } + } + + return result; +}; + +/** + * @ngdoc object + * @name ui.router.util.type:Type + * + * @description + * Implements an interface to define custom parameter types that can be decoded from and encoded to + * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`} + * objects when matching or formatting URLs, or comparing or validating parameter values. + * + * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more + * information on registering custom types. + * + * @param {Object} config A configuration object which contains the custom type definition. The object's + * properties will override the default methods and/or pattern in `Type`'s public interface. + * @example + *
+ * {
+ *   decode: function(val) { return parseInt(val, 10); },
+ *   encode: function(val) { return val && val.toString(); },
+ *   equals: function(a, b) { return this.is(a) && a === b; },
+ *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
+ *   pattern: /\d+/
+ * }
+ * 
+ * + * @property {RegExp} pattern The regular expression pattern used to match values of this type when + * coming from a substring of a URL. + * + * @returns {Object} Returns a new `Type` object. + */ +function Type(config) { + extend(this, config); +} + +/** + * @ngdoc function + * @name ui.router.util.type:Type#is + * @methodOf ui.router.util.type:Type + * + * @description + * Detects whether a value is of a particular type. Accepts a native (decoded) value + * and determines whether it matches the current `Type` object. + * + * @param {*} val The value to check. + * @param {string} key Optional. If the type check is happening in the context of a specific + * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the + * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects. + * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`. + */ +Type.prototype.is = function(val, key) { + return true; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:Type#encode + * @methodOf ui.router.util.type:Type + * + * @description + * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the + * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it + * only needs to be a representation of `val` that has been coerced to a string. + * + * @param {*} val The value to encode. + * @param {string} key The name of the parameter in which `val` is stored. Can be used for + * meta-programming of `Type` objects. + * @returns {string} Returns a string representation of `val` that can be encoded in a URL. + */ +Type.prototype.encode = function(val, key) { + return val; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:Type#decode + * @methodOf ui.router.util.type:Type + * + * @description + * Converts a parameter value (from URL string or transition param) to a custom/native value. + * + * @param {string} val The URL parameter value to decode. + * @param {string} key The name of the parameter in which `val` is stored. Can be used for + * meta-programming of `Type` objects. + * @returns {*} Returns a custom representation of the URL parameter value. + */ +Type.prototype.decode = function(val, key) { + return val; +}; + +/** + * @ngdoc function + * @name ui.router.util.type:Type#equals + * @methodOf ui.router.util.type:Type + * + * @description + * Determines whether two decoded values are equivalent. + * + * @param {*} a A value to compare against. + * @param {*} b A value to compare against. + * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`. + */ +Type.prototype.equals = function(a, b) { + return a == b; +}; + +Type.prototype.$subPattern = function() { + var sub = this.pattern.toString(); + return sub.substr(1, sub.length - 2); +}; + +Type.prototype.pattern = /.*/; + +Type.prototype.toString = function() { return "{Type:" + this.name + "}"; }; + +/** Given an encoded string, or a decoded object, returns a decoded object */ +Type.prototype.$normalize = function(val) { + return this.is(val) ? val : this.decode(val); +}; + +/* + * Wraps an existing custom Type as an array of Type, depending on 'mode'. + * e.g.: + * - urlmatcher pattern "/path?{queryParam[]:int}" + * - url: "/path?queryParam=1&queryParam=2 + * - $stateParams.queryParam will be [1, 2] + * if `mode` is "auto", then + * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 + * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2] + */ +Type.prototype.$asArray = function(mode, isSearch) { + if (!mode) return this; + if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only"); + + function ArrayType(type, mode) { + function bindTo(type, callbackName) { + return function() { + return type[callbackName].apply(type, arguments); + }; + } + + // Wrap non-array value as array + function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); } + // Unwrap array value for "auto" mode. Return undefined for empty array. + function arrayUnwrap(val) { + switch(val.length) { + case 0: return undefined; + case 1: return mode === "auto" ? val[0] : val; + default: return val; + } + } + function falsey(val) { return !val; } + + // Wraps type (.is/.encode/.decode) functions to operate on each value of an array + function arrayHandler(callback, allTruthyMode) { + return function handleArray(val) { + if (isArray(val) && val.length === 0) return val; + val = arrayWrap(val); + var result = map(val, callback); + if (allTruthyMode === true) + return filter(result, falsey).length === 0; + return arrayUnwrap(result); + }; + } + + // Wraps type (.equals) functions to operate on each value of an array + function arrayEqualsHandler(callback) { + return function handleArray(val1, val2) { + var left = arrayWrap(val1), right = arrayWrap(val2); + if (left.length !== right.length) return false; + for (var i = 0; i < left.length; i++) { + if (!callback(left[i], right[i])) return false; + } + return true; + }; + } + + this.encode = arrayHandler(bindTo(type, 'encode')); + this.decode = arrayHandler(bindTo(type, 'decode')); + this.is = arrayHandler(bindTo(type, 'is'), true); + this.equals = arrayEqualsHandler(bindTo(type, 'equals')); + this.pattern = type.pattern; + this.$normalize = arrayHandler(bindTo(type, '$normalize')); + this.name = type.name; + this.$arrayMode = mode; + } + + return new ArrayType(this, mode); +}; + + + +/** + * @ngdoc object + * @name ui.router.util.$urlMatcherFactory + * + * @description + * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory + * is also available to providers under the name `$urlMatcherFactoryProvider`. + */ +function $UrlMatcherFactory() { + $$UMFP = this; + + var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false; + + // Use tildes to pre-encode slashes. + // If the slashes are simply URLEncoded, the browser can choose to pre-decode them, + // and bidirectional encoding/decoding fails. + // Tilde was chosen because it's not a RFC 3986 section 2.2 Reserved Character + function valToString(val) { return val != null ? val.toString().replace(/(~|\/)/g, function (m) { return {'~':'~~', '/':'~2F'}[m]; }) : val; } + function valFromString(val) { return val != null ? val.toString().replace(/(~~|~2F)/g, function (m) { return {'~~':'~', '~2F':'/'}[m]; }) : val; } + + var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = { + "string": { + encode: valToString, + decode: valFromString, + // TODO: in 1.0, make string .is() return false if value is undefined/null by default. + // In 0.2.x, string params are optional by default for backwards compat + is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; }, + pattern: /[^/]*/ + }, + "int": { + encode: valToString, + decode: function(val) { return parseInt(val, 10); }, + is: function(val) { return val !== undefined && val !== null && this.decode(val.toString()) === val; }, + pattern: /\d+/ + }, + "bool": { + encode: function(val) { return val ? 1 : 0; }, + decode: function(val) { return parseInt(val, 10) !== 0; }, + is: function(val) { return val === true || val === false; }, + pattern: /0|1/ + }, + "date": { + encode: function (val) { + if (!this.is(val)) + return undefined; + return [ val.getFullYear(), + ('0' + (val.getMonth() + 1)).slice(-2), + ('0' + val.getDate()).slice(-2) + ].join("-"); + }, + decode: function (val) { + if (this.is(val)) return val; + var match = this.capture.exec(val); + return match ? new Date(match[1], match[2] - 1, match[3]) : undefined; + }, + is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); }, + equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); }, + pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, + capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/ + }, + "json": { + encode: angular.toJson, + decode: angular.fromJson, + is: angular.isObject, + equals: angular.equals, + pattern: /[^/]*/ + }, + "any": { // does not encode/decode + encode: angular.identity, + decode: angular.identity, + equals: angular.equals, + pattern: /.*/ + } + }; + + function getDefaultConfig() { + return { + strict: isStrictMode, + caseInsensitive: isCaseInsensitive + }; + } + + function isInjectable(value) { + return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1]))); + } + + /** + * [Internal] Get the default value of a parameter, which may be an injectable function. + */ + $UrlMatcherFactory.$$getDefaultValue = function(config) { + if (!isInjectable(config.value)) return config.value; + if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); + return injector.invoke(config.value); + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#caseInsensitive + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Defines whether URL matching should be case sensitive (the default behavior), or not. + * + * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`; + * @returns {boolean} the current value of caseInsensitive + */ + this.caseInsensitive = function(value) { + if (isDefined(value)) + isCaseInsensitive = value; + return isCaseInsensitive; + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#strictMode + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Defines whether URLs should match trailing slashes, or not (the default behavior). + * + * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`. + * @returns {boolean} the current value of strictMode + */ + this.strictMode = function(value) { + if (isDefined(value)) + isStrictMode = value; + return isStrictMode; + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Sets the default behavior when generating or matching URLs with default parameter values. + * + * @param {string} value A string that defines the default parameter URL squashing behavior. + * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL + * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the + * parameter is surrounded by slashes, squash (remove) one slash from the URL + * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) + * the parameter value from the URL and replace it with this string. + */ + this.defaultSquashPolicy = function(value) { + if (!isDefined(value)) return defaultSquashPolicy; + if (value !== true && value !== false && !isString(value)) + throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string"); + defaultSquashPolicy = value; + return value; + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#compile + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern. + * + * @param {string} pattern The URL pattern. + * @param {Object} config The config object hash. + * @returns {UrlMatcher} The UrlMatcher. + */ + this.compile = function (pattern, config) { + return new UrlMatcher(pattern, extend(getDefaultConfig(), config)); + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#isMatcher + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Returns true if the specified object is a `UrlMatcher`, or false otherwise. + * + * @param {Object} object The object to perform the type check against. + * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by + * implementing all the same methods. + */ + this.isMatcher = function (o) { + if (!isObject(o)) return false; + var result = true; + + forEach(UrlMatcher.prototype, function(val, name) { + if (isFunction(val)) { + result = result && (isDefined(o[name]) && isFunction(o[name])); + } + }); + return result; + }; + + /** + * @ngdoc function + * @name ui.router.util.$urlMatcherFactory#type + * @methodOf ui.router.util.$urlMatcherFactory + * + * @description + * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to + * generate URLs with typed parameters. + * + * @param {string} name The type name. + * @param {Object|Function} definition The type definition. See + * {@link ui.router.util.type:Type `Type`} for information on the values accepted. + * @param {Object|Function} definitionFn (optional) A function that is injected before the app + * runtime starts. The result of this function is merged into the existing `definition`. + * See {@link ui.router.util.type:Type `Type`} for information on the values accepted. + * + * @returns {Object} Returns `$urlMatcherFactoryProvider`. + * + * @example + * This is a simple example of a custom type that encodes and decodes items from an + * array, using the array index as the URL-encoded value: + * + *
+   * var list = ['John', 'Paul', 'George', 'Ringo'];
+   *
+   * $urlMatcherFactoryProvider.type('listItem', {
+   *   encode: function(item) {
+   *     // Represent the list item in the URL using its corresponding index
+   *     return list.indexOf(item);
+   *   },
+   *   decode: function(item) {
+   *     // Look up the list item by index
+   *     return list[parseInt(item, 10)];
+   *   },
+   *   is: function(item) {
+   *     // Ensure the item is valid by checking to see that it appears
+   *     // in the list
+   *     return list.indexOf(item) > -1;
+   *   }
+   * });
+   *
+   * $stateProvider.state('list', {
+   *   url: "/list/{item:listItem}",
+   *   controller: function($scope, $stateParams) {
+   *     console.log($stateParams.item);
+   *   }
+   * });
+   *
+   * // ...
+   *
+   * // Changes URL to '/list/3', logs "Ringo" to the console
+   * $state.go('list', { item: "Ringo" });
+   * 
+ * + * This is a more complex example of a type that relies on dependency injection to + * interact with services, and uses the parameter name from the URL to infer how to + * handle encoding and decoding parameter values: + * + *
+   * // Defines a custom type that gets a value from a service,
+   * // where each service gets different types of values from
+   * // a backend API:
+   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
+   *
+   *   // Matches up services to URL parameter names
+   *   var services = {
+   *     user: Users,
+   *     post: Posts
+   *   };
+   *
+   *   return {
+   *     encode: function(object) {
+   *       // Represent the object in the URL using its unique ID
+   *       return object.id;
+   *     },
+   *     decode: function(value, key) {
+   *       // Look up the object by ID, using the parameter
+   *       // name (key) to call the correct service
+   *       return services[key].findById(value);
+   *     },
+   *     is: function(object, key) {
+   *       // Check that object is a valid dbObject
+   *       return angular.isObject(object) && object.id && services[key];
+   *     }
+   *     equals: function(a, b) {
+   *       // Check the equality of decoded objects by comparing
+   *       // their unique IDs
+   *       return a.id === b.id;
+   *     }
+   *   };
+   * });
+   *
+   * // In a config() block, you can then attach URLs with
+   * // type-annotated parameters:
+   * $stateProvider.state('users', {
+   *   url: "/users",
+   *   // ...
+   * }).state('users.item', {
+   *   url: "/{user:dbObject}",
+   *   controller: function($scope, $stateParams) {
+   *     // $stateParams.user will now be an object returned from
+   *     // the Users service
+   *   },
+   *   // ...
+   * });
+   * 
+ */ + this.type = function (name, definition, definitionFn) { + if (!isDefined(definition)) return $types[name]; + if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined."); + + $types[name] = new Type(extend({ name: name }, definition)); + if (definitionFn) { + typeQueue.push({ name: name, def: definitionFn }); + if (!enqueue) flushTypeQueue(); + } + return this; + }; + + // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s + function flushTypeQueue() { + while(typeQueue.length) { + var type = typeQueue.shift(); + if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime."); + angular.extend($types[type.name], injector.invoke(type.def)); + } + } + + // Register default types. Store them in the prototype of $types. + forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); }); + $types = inherit($types, {}); + + /* No need to document $get, since it returns this */ + this.$get = ['$injector', function ($injector) { + injector = $injector; + enqueue = false; + flushTypeQueue(); + + forEach(defaultTypes, function(type, name) { + if (!$types[name]) $types[name] = new Type(type); + }); + return this; + }]; + + this.Param = function Param(id, type, config, location) { + var self = this; + config = unwrapShorthand(config); + type = getType(config, type, location); + var arrayMode = getArrayMode(); + type = arrayMode ? type.$asArray(arrayMode, location === "search") : type; + if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined) + config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to "" + var isOptional = config.value !== undefined; + var squash = getSquashPolicy(config, isOptional); + var replace = getReplace(config, arrayMode, isOptional, squash); + + function unwrapShorthand(config) { + var keys = isObject(config) ? objectKeys(config) : []; + var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 && + indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1; + if (isShorthand) config = { value: config }; + config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; }; + return config; + } + + function getType(config, urlType, location) { + if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations."); + if (urlType) return urlType; + if (!config.type) return (location === "config" ? $types.any : $types.string); + + if (angular.isString(config.type)) + return $types[config.type]; + if (config.type instanceof Type) + return config.type; + return new Type(config.type); + } + + // array config: param name (param[]) overrides default settings. explicit config overrides param name. + function getArrayMode() { + var arrayDefaults = { array: (location === "search" ? "auto" : false) }; + var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; + return extend(arrayDefaults, arrayParamNomenclature, config).array; + } + + /** + * returns false, true, or the squash value to indicate the "default parameter url squash policy". + */ + function getSquashPolicy(config, isOptional) { + var squash = config.squash; + if (!isOptional || squash === false) return false; + if (!isDefined(squash) || squash == null) return defaultSquashPolicy; + if (squash === true || isString(squash)) return squash; + throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); + } + + function getReplace(config, arrayMode, isOptional, squash) { + var replace, configuredKeys, defaultPolicy = [ + { from: "", to: (isOptional || arrayMode ? undefined : "") }, + { from: null, to: (isOptional || arrayMode ? undefined : "") } + ]; + replace = isArray(config.replace) ? config.replace : []; + if (isString(squash)) + replace.push({ from: squash, to: undefined }); + configuredKeys = map(replace, function(item) { return item.from; } ); + return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace); + } + + /** + * [Internal] Get the default value of a parameter, which may be an injectable function. + */ + function $$getDefaultValue() { + if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); + var defaultValue = injector.invoke(config.$$fn); + if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue)) + throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")"); + return defaultValue; + } + + /** + * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the + * default value, which may be the result of an injectable function. + */ + function $value(value) { + function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; } + function $replace(value) { + var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; }); + return replacement.length ? replacement[0] : value; + } + value = $replace(value); + return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value); + } + + function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; } + + extend(this, { + id: id, + type: type, + location: location, + array: arrayMode, + squash: squash, + replace: replace, + isOptional: isOptional, + value: $value, + dynamic: undefined, + config: config, + toString: toString + }); + }; + + function ParamSet(params) { + extend(this, params || {}); + } + + ParamSet.prototype = { + $$new: function() { + return inherit(this, extend(new ParamSet(), { $$parent: this})); + }, + $$keys: function () { + var keys = [], chain = [], parent = this, + ignore = objectKeys(ParamSet.prototype); + while (parent) { chain.push(parent); parent = parent.$$parent; } + chain.reverse(); + forEach(chain, function(paramset) { + forEach(objectKeys(paramset), function(key) { + if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key); + }); + }); + return keys; + }, + $$values: function(paramValues) { + var values = {}, self = this; + forEach(self.$$keys(), function(key) { + values[key] = self[key].value(paramValues && paramValues[key]); + }); + return values; + }, + $$equals: function(paramValues1, paramValues2) { + var equal = true, self = this; + forEach(self.$$keys(), function(key) { + var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key]; + if (!self[key].type.equals(left, right)) equal = false; + }); + return equal; + }, + $$validates: function $$validate(paramValues) { + var keys = this.$$keys(), i, param, rawVal, normalized, encoded; + for (i = 0; i < keys.length; i++) { + param = this[keys[i]]; + rawVal = paramValues[keys[i]]; + if ((rawVal === undefined || rawVal === null) && param.isOptional) + break; // There was no parameter value, but the param is optional + normalized = param.type.$normalize(rawVal); + if (!param.type.is(normalized)) + return false; // The value was not of the correct Type, and could not be decoded to the correct Type + encoded = param.type.encode(normalized); + if (angular.isString(encoded) && !param.type.pattern.exec(encoded)) + return false; // The value was of the correct type, but when encoded, did not match the Type's regexp + } + return true; + }, + $$parent: undefined + }; + + this.ParamSet = ParamSet; +} + +// Register as a provider so it's available to other providers +angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory); +angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]); + +/** + * @ngdoc object + * @name ui.router.router.$urlRouterProvider + * + * @requires ui.router.util.$urlMatcherFactoryProvider + * @requires $locationProvider + * + * @description + * `$urlRouterProvider` has the responsibility of watching `$location`. + * When `$location` changes it runs through a list of rules one by one until a + * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify + * a url in a state configuration. All urls are compiled into a UrlMatcher object. + * + * There are several methods on `$urlRouterProvider` that make it useful to use directly + * in your module config. + */ +$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider']; +function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) { + var rules = [], otherwise = null, interceptDeferred = false, listener; + + // Returns a string that is a prefix of all strings matching the RegExp + function regExpPrefix(re) { + var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); + return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; + } + + // Interpolates matched values into a String.replace()-style pattern + function interpolate(pattern, match) { + return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { + return match[what === '$' ? 0 : Number(what)]; + }); + } + + /** + * @ngdoc function + * @name ui.router.router.$urlRouterProvider#rule + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Defines rules that are used by `$urlRouterProvider` to find matches for + * specific URLs. + * + * @example + *
+   * var app = angular.module('app', ['ui.router.router']);
+   *
+   * app.config(function ($urlRouterProvider) {
+   *   // Here's an example of how you might allow case insensitive urls
+   *   $urlRouterProvider.rule(function ($injector, $location) {
+   *     var path = $location.path(),
+   *         normalized = path.toLowerCase();
+   *
+   *     if (path !== normalized) {
+   *       return normalized;
+   *     }
+   *   });
+   * });
+   * 
+ * + * @param {function} rule Handler function that takes `$injector` and `$location` + * services as arguments. You can use them to return a valid path as a string. + * + * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance + */ + this.rule = function (rule) { + if (!isFunction(rule)) throw new Error("'rule' must be a function"); + rules.push(rule); + return this; + }; + + /** + * @ngdoc object + * @name ui.router.router.$urlRouterProvider#otherwise + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Defines a path that is used when an invalid route is requested. + * + * @example + *
+   * var app = angular.module('app', ['ui.router.router']);
+   *
+   * app.config(function ($urlRouterProvider) {
+   *   // if the path doesn't match any of the urls you configured
+   *   // otherwise will take care of routing the user to the
+   *   // specified url
+   *   $urlRouterProvider.otherwise('/index');
+   *
+   *   // Example of using function rule as param
+   *   $urlRouterProvider.otherwise(function ($injector, $location) {
+   *     return '/a/valid/url';
+   *   });
+   * });
+   * 
+ * + * @param {string|function} rule The url path you want to redirect to or a function + * rule that returns the url path. The function version is passed two params: + * `$injector` and `$location` services, and must return a url string. + * + * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance + */ + this.otherwise = function (rule) { + if (isString(rule)) { + var redirect = rule; + rule = function () { return redirect; }; + } + else if (!isFunction(rule)) throw new Error("'rule' must be a function"); + otherwise = rule; + return this; + }; + + + function handleIfMatch($injector, handler, match) { + if (!match) return false; + var result = $injector.invoke(handler, handler, { $match: match }); + return isDefined(result) ? result : true; + } + + /** + * @ngdoc function + * @name ui.router.router.$urlRouterProvider#when + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Registers a handler for a given url matching. + * + * If the handler is a string, it is + * treated as a redirect, and is interpolated according to the syntax of match + * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). + * + * If the handler is a function, it is injectable. It gets invoked if `$location` + * matches. You have the option of inject the match object as `$match`. + * + * The handler can return + * + * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` + * will continue trying to find another one that matches. + * - **string** which is treated as a redirect and passed to `$location.url()` + * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. + * + * @example + *
+   * var app = angular.module('app', ['ui.router.router']);
+   *
+   * app.config(function ($urlRouterProvider) {
+   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {
+   *     if ($state.$current.navigable !== state ||
+   *         !equalForKeys($match, $stateParams) {
+   *      $state.transitionTo(state, $match, false);
+   *     }
+   *   });
+   * });
+   * 
+ * + * @param {string|object} what The incoming path that you want to redirect. + * @param {string|function} handler The path you want to redirect your user to. + */ + this.when = function (what, handler) { + var redirect, handlerIsString = isString(handler); + if (isString(what)) what = $urlMatcherFactory.compile(what); + + if (!handlerIsString && !isFunction(handler) && !isArray(handler)) + throw new Error("invalid 'handler' in when()"); + + var strategies = { + matcher: function (what, handler) { + if (handlerIsString) { + redirect = $urlMatcherFactory.compile(handler); + handler = ['$match', function ($match) { return redirect.format($match); }]; + } + return extend(function ($injector, $location) { + return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); + }, { + prefix: isString(what.prefix) ? what.prefix : '' + }); + }, + regex: function (what, handler) { + if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); + + if (handlerIsString) { + redirect = handler; + handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; + } + return extend(function ($injector, $location) { + return handleIfMatch($injector, handler, what.exec($location.path())); + }, { + prefix: regExpPrefix(what) + }); + } + }; + + var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; + + for (var n in check) { + if (check[n]) return this.rule(strategies[n](what, handler)); + } + + throw new Error("invalid 'what' in when()"); + }; + + /** + * @ngdoc function + * @name ui.router.router.$urlRouterProvider#deferIntercept + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Disables (or enables) deferring location change interception. + * + * If you wish to customize the behavior of syncing the URL (for example, if you wish to + * defer a transition but maintain the current URL), call this method at configuration time. + * Then, at run time, call `$urlRouter.listen()` after you have configured your own + * `$locationChangeSuccess` event handler. + * + * @example + *
+   * var app = angular.module('app', ['ui.router.router']);
+   *
+   * app.config(function ($urlRouterProvider) {
+   *
+   *   // Prevent $urlRouter from automatically intercepting URL changes;
+   *   // this allows you to configure custom behavior in between
+   *   // location changes and route synchronization:
+   *   $urlRouterProvider.deferIntercept();
+   *
+   * }).run(function ($rootScope, $urlRouter, UserService) {
+   *
+   *   $rootScope.$on('$locationChangeSuccess', function(e) {
+   *     // UserService is an example service for managing user state
+   *     if (UserService.isLoggedIn()) return;
+   *
+   *     // Prevent $urlRouter's default handler from firing
+   *     e.preventDefault();
+   *
+   *     UserService.handleLogin().then(function() {
+   *       // Once the user has logged in, sync the current URL
+   *       // to the router:
+   *       $urlRouter.sync();
+   *     });
+   *   });
+   *
+   *   // Configures $urlRouter's listener *after* your custom listener
+   *   $urlRouter.listen();
+   * });
+   * 
+ * + * @param {boolean} defer Indicates whether to defer location change interception. Passing + no parameter is equivalent to `true`. + */ + this.deferIntercept = function (defer) { + if (defer === undefined) defer = true; + interceptDeferred = defer; + }; + + /** + * @ngdoc object + * @name ui.router.router.$urlRouter + * + * @requires $location + * @requires $rootScope + * @requires $injector + * @requires $browser + * + * @description + * + */ + this.$get = $get; + $get.$inject = ['$location', '$rootScope', '$injector', '$browser', '$sniffer']; + function $get( $location, $rootScope, $injector, $browser, $sniffer) { + + var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl; + + function appendBasePath(url, isHtml5, absolute) { + if (baseHref === '/') return url; + if (isHtml5) return baseHref.slice(0, -1) + url; + if (absolute) return baseHref.slice(1) + url; + return url; + } + + // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree + function update(evt) { + if (evt && evt.defaultPrevented) return; + var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl; + lastPushedUrl = undefined; + // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573 + //if (ignoreUpdate) return true; + + function check(rule) { + var handled = rule($injector, $location); + + if (!handled) return false; + if (isString(handled)) $location.replace().url(handled); + return true; + } + var n = rules.length, i; + + for (i = 0; i < n; i++) { + if (check(rules[i])) return; + } + // always check otherwise last to allow dynamic updates to the set of rules + if (otherwise) check(otherwise); + } + + function listen() { + listener = listener || $rootScope.$on('$locationChangeSuccess', update); + return listener; + } + + if (!interceptDeferred) listen(); + + return { + /** + * @ngdoc function + * @name ui.router.router.$urlRouter#sync + * @methodOf ui.router.router.$urlRouter + * + * @description + * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. + * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, + * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed + * with the transition by calling `$urlRouter.sync()`. + * + * @example + *
+       * angular.module('app', ['ui.router'])
+       *   .run(function($rootScope, $urlRouter) {
+       *     $rootScope.$on('$locationChangeSuccess', function(evt) {
+       *       // Halt state change from even starting
+       *       evt.preventDefault();
+       *       // Perform custom logic
+       *       var meetsRequirement = ...
+       *       // Continue with the update and state transition if logic allows
+       *       if (meetsRequirement) $urlRouter.sync();
+       *     });
+       * });
+       * 
+ */ + sync: function() { + update(); + }, + + listen: function() { + return listen(); + }, + + update: function(read) { + if (read) { + location = $location.url(); + return; + } + if ($location.url() === location) return; + + $location.url(location); + $location.replace(); + }, + + push: function(urlMatcher, params, options) { + var url = urlMatcher.format(params || {}); + + // Handle the special hash param, if needed + if (url !== null && params && params['#']) { + url += '#' + params['#']; + } + + $location.url(url); + lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined; + if (options && options.replace) $location.replace(); + }, + + /** + * @ngdoc function + * @name ui.router.router.$urlRouter#href + * @methodOf ui.router.router.$urlRouter + * + * @description + * A URL generation method that returns the compiled URL for a given + * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. + * + * @example + *
+       * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
+       *   person: "bob"
+       * });
+       * // $bob == "/about/bob";
+       * 
+ * + * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. + * @param {object=} params An object of parameter values to fill the matcher's required parameters. + * @param {object=} options Options object. The options are: + * + * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". + * + * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` + */ + href: function(urlMatcher, params, options) { + if (!urlMatcher.validates(params)) return null; + + var isHtml5 = $locationProvider.html5Mode(); + if (angular.isObject(isHtml5)) { + isHtml5 = isHtml5.enabled; + } + + isHtml5 = isHtml5 && $sniffer.history; + + var url = urlMatcher.format(params); + options = options || {}; + + if (!isHtml5 && url !== null) { + url = "#" + $locationProvider.hashPrefix() + url; + } + + // Handle special hash param, if needed + if (url !== null && params && params['#']) { + url += '#' + params['#']; + } + + url = appendBasePath(url, isHtml5, options.absolute); + + if (!options.absolute || !url) { + return url; + } + + var slash = (!isHtml5 && url ? '/' : ''), port = $location.port(); + port = (port === 80 || port === 443 ? '' : ':' + port); + + return [$location.protocol(), '://', $location.host(), port, slash, url].join(''); + } + }; + } +} + +angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); + +/** + * @ngdoc object + * @name ui.router.state.$stateProvider + * + * @requires ui.router.router.$urlRouterProvider + * @requires ui.router.util.$urlMatcherFactoryProvider + * + * @description + * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely + * on state. + * + * A state corresponds to a "place" in the application in terms of the overall UI and + * navigation. A state describes (via the controller / template / view properties) what + * the UI looks like and does at that place. + * + * States often have things in common, and the primary way of factoring out these + * commonalities in this model is via the state hierarchy, i.e. parent/child states aka + * nested states. + * + * The `$stateProvider` provides interfaces to declare these states for your app. + */ +$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider']; +function $StateProvider( $urlRouterProvider, $urlMatcherFactory) { + + var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; + + // Builds state properties from definition passed to registerState() + var stateBuilder = { + + // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. + // state.children = []; + // if (parent) parent.children.push(state); + parent: function(state) { + if (isDefined(state.parent) && state.parent) return findState(state.parent); + // regex matches any valid composite state name + // would match "contact.list" but not "contacts" + var compositeName = /^(.+)\.[^.]+$/.exec(state.name); + return compositeName ? findState(compositeName[1]) : root; + }, + + // inherit 'data' from parent and override by own values (if any) + data: function(state) { + if (state.parent && state.parent.data) { + state.data = state.self.data = inherit(state.parent.data, state.data); + } + return state.data; + }, + + // Build a URLMatcher if necessary, either via a relative or absolute URL + url: function(state) { + var url = state.url, config = { params: state.params || {} }; + + if (isString(url)) { + if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); + return (state.parent.navigable || root).url.concat(url, config); + } + + if (!url || $urlMatcherFactory.isMatcher(url)) return url; + throw new Error("Invalid url '" + url + "' in state '" + state + "'"); + }, + + // Keep track of the closest ancestor state that has a URL (i.e. is navigable) + navigable: function(state) { + return state.url ? state : (state.parent ? state.parent.navigable : null); + }, + + // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params + ownParams: function(state) { + var params = state.url && state.url.params || new $$UMFP.ParamSet(); + forEach(state.params || {}, function(config, id) { + if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); + }); + return params; + }, + + // Derive parameters for this state and ensure they're a super-set of parent's parameters + params: function(state) { + var ownParams = pick(state.ownParams, state.ownParams.$$keys()); + return state.parent && state.parent.params ? extend(state.parent.params.$$new(), ownParams) : new $$UMFP.ParamSet(); + }, + + // If there is no explicit multi-view configuration, make one up so we don't have + // to handle both cases in the view directive later. Note that having an explicit + // 'views' property will mean the default unnamed view properties are ignored. This + // is also a good time to resolve view names to absolute names, so everything is a + // straight lookup at link time. + views: function(state) { + var views = {}; + + forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { + if (name.indexOf('@') < 0) name += '@' + state.parent.name; + view.resolveAs = view.resolveAs || state.resolveAs || '$resolve'; + views[name] = view; + }); + return views; + }, + + // Keep a full path from the root down to this state as this is needed for state activation. + path: function(state) { + return state.parent ? state.parent.path.concat(state) : []; // exclude root from path + }, + + // Speed up $state.contains() as it's used a lot + includes: function(state) { + var includes = state.parent ? extend({}, state.parent.includes) : {}; + includes[state.name] = true; + return includes; + }, + + $delegates: {} + }; + + function isRelative(stateName) { + return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; + } + + function findState(stateOrName, base) { + if (!stateOrName) return undefined; + + var isStr = isString(stateOrName), + name = isStr ? stateOrName : stateOrName.name, + path = isRelative(name); + + if (path) { + if (!base) throw new Error("No reference point given for path '" + name + "'"); + base = findState(base); + + var rel = name.split("."), i = 0, pathLength = rel.length, current = base; + + for (; i < pathLength; i++) { + if (rel[i] === "" && i === 0) { + current = base; + continue; + } + if (rel[i] === "^") { + if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); + current = current.parent; + continue; + } + break; + } + rel = rel.slice(i).join("."); + name = current.name + (current.name && rel ? "." : "") + rel; + } + var state = states[name]; + + if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { + return state; + } + return undefined; + } + + function queueState(parentName, state) { + if (!queue[parentName]) { + queue[parentName] = []; + } + queue[parentName].push(state); + } + + function flushQueuedChildren(parentName) { + var queued = queue[parentName] || []; + while(queued.length) { + registerState(queued.shift()); + } + } + + function registerState(state) { + // Wrap a new object around the state so we can store our private details easily. + state = inherit(state, { + self: state, + resolve: state.resolve || {}, + toString: function() { return this.name; } + }); + + var name = state.name; + if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); + if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined"); + + // Get parent name + var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) + : (isString(state.parent)) ? state.parent + : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name + : ''; + + // If parent is not registered yet, add state to queue and register later + if (parentName && !states[parentName]) { + return queueState(parentName, state.self); + } + + for (var key in stateBuilder) { + if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); + } + states[name] = state; + + // Register the state in the global state list and with $urlRouter if necessary. + if (!state[abstractKey] && state.url) { + $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { + if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { + $state.transitionTo(state, $match, { inherit: true, location: false }); + } + }]); + } + + // Register any queued children + flushQueuedChildren(name); + + return state; + } + + // Checks text to see if it looks like a glob. + function isGlob (text) { + return text.indexOf('*') > -1; + } + + // Returns true if glob matches current $state name. + function doesStateMatchGlob (glob) { + var globSegments = glob.split('.'), + segments = $state.$current.name.split('.'); + + //match single stars + for (var i = 0, l = globSegments.length; i < l; i++) { + if (globSegments[i] === '*') { + segments[i] = '*'; + } + } + + //match greedy starts + if (globSegments[0] === '**') { + segments = segments.slice(indexOf(segments, globSegments[1])); + segments.unshift('**'); + } + //match greedy ends + if (globSegments[globSegments.length - 1] === '**') { + segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); + segments.push('**'); + } + + if (globSegments.length != segments.length) { + return false; + } + + return segments.join('') === globSegments.join(''); + } + + + // Implicit root state that is always active + root = registerState({ + name: '', + url: '^', + views: null, + 'abstract': true + }); + root.navigable = null; + + + /** + * @ngdoc function + * @name ui.router.state.$stateProvider#decorator + * @methodOf ui.router.state.$stateProvider + * + * @description + * Allows you to extend (carefully) or override (at your own peril) the + * `stateBuilder` object used internally by `$stateProvider`. This can be used + * to add custom functionality to ui-router, for example inferring templateUrl + * based on the state name. + * + * When passing only a name, it returns the current (original or decorated) builder + * function that matches `name`. + * + * The builder functions that can be decorated are listed below. Though not all + * necessarily have a good use case for decoration, that is up to you to decide. + * + * In addition, users can attach custom decorators, which will generate new + * properties within the state's internal definition. There is currently no clear + * use-case for this beyond accessing internal states (i.e. $state.$current), + * however, expect this to become increasingly relevant as we introduce additional + * meta-programming features. + * + * **Warning**: Decorators should not be interdependent because the order of + * execution of the builder functions in non-deterministic. Builder functions + * should only be dependent on the state definition object and super function. + * + * + * Existing builder functions and current return values: + * + * - **parent** `{object}` - returns the parent state object. + * - **data** `{object}` - returns state data, including any inherited data that is not + * overridden by own values (if any). + * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher} + * or `null`. + * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is + * navigable). + * - **params** `{object}` - returns an array of state params that are ensured to + * be a super-set of parent's params. + * - **views** `{object}` - returns a views object where each key is an absolute view + * name (i.e. "viewName@stateName") and each value is the config object + * (template, controller) for the view. Even when you don't use the views object + * explicitly on a state config, one is still created for you internally. + * So by decorating this builder function you have access to decorating template + * and controller properties. + * - **ownParams** `{object}` - returns an array of params that belong to the state, + * not including any params defined by ancestor states. + * - **path** `{string}` - returns the full path from the root down to this state. + * Needed for state activation. + * - **includes** `{object}` - returns an object that includes every state that + * would pass a `$state.includes()` test. + * + * @example + *
+   * // Override the internal 'views' builder with a function that takes the state
+   * // definition, and a reference to the internal function being overridden:
+   * $stateProvider.decorator('views', function (state, parent) {
+   *   var result = {},
+   *       views = parent(state);
+   *
+   *   angular.forEach(views, function (config, name) {
+   *     var autoName = (state.name + '.' + name).replace('.', '/');
+   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
+   *     result[name] = config;
+   *   });
+   *   return result;
+   * });
+   *
+   * $stateProvider.state('home', {
+   *   views: {
+   *     'contact.list': { controller: 'ListController' },
+   *     'contact.item': { controller: 'ItemController' }
+   *   }
+   * });
+   *
+   * // ...
+   *
+   * $state.go('home');
+   * // Auto-populates list and item views with /partials/home/contact/list.html,
+   * // and /partials/home/contact/item.html, respectively.
+   * 
+ * + * @param {string} name The name of the builder function to decorate. + * @param {object} func A function that is responsible for decorating the original + * builder function. The function receives two parameters: + * + * - `{object}` - state - The state config object. + * - `{object}` - super - The original builder function. + * + * @return {object} $stateProvider - $stateProvider instance + */ + this.decorator = decorator; + function decorator(name, func) { + /*jshint validthis: true */ + if (isString(name) && !isDefined(func)) { + return stateBuilder[name]; + } + if (!isFunction(func) || !isString(name)) { + return this; + } + if (stateBuilder[name] && !stateBuilder.$delegates[name]) { + stateBuilder.$delegates[name] = stateBuilder[name]; + } + stateBuilder[name] = func; + return this; + } + + /** + * @ngdoc function + * @name ui.router.state.$stateProvider#state + * @methodOf ui.router.state.$stateProvider + * + * @description + * Registers a state configuration under a given state name. The stateConfig object + * has the following acceptable properties. + * + * @param {string} name A unique state name, e.g. "home", "about", "contacts". + * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". + * @param {object} stateConfig State configuration object. + * @param {string|function=} stateConfig.template + * + * html template as a string or a function that returns + * an html template as a string which should be used by the uiView directives. This property + * takes precedence over templateUrl. + * + * If `template` is a function, it will be called with the following parameters: + * + * - {array.<object>} - state parameters extracted from the current $location.path() by + * applying the current state + * + *
template:
+   *   "

inline template definition

" + + * "
"
+ *
template: function(params) {
+   *       return "

generated template

"; }
+ * + * + * @param {string|function=} stateConfig.templateUrl + * + * + * path or function that returns a path to an html + * template that should be used by uiView. + * + * If `templateUrl` is a function, it will be called with the following parameters: + * + * - {array.<object>} - state parameters extracted from the current $location.path() by + * applying the current state + * + *
templateUrl: "home.html"
+ *
templateUrl: function(params) {
+   *     return myTemplates[params.pageId]; }
+ * + * @param {function=} stateConfig.templateProvider + * + * Provider function that returns HTML content string. + *
 templateProvider:
+   *       function(MyTemplateService, params) {
+   *         return MyTemplateService.getTemplate(params.pageId);
+   *       }
+ * + * @param {string|function=} stateConfig.controller + * + * + * Controller fn that should be associated with newly + * related scope or the name of a registered controller if passed as a string. + * Optionally, the ControllerAs may be declared here. + *
controller: "MyRegisteredController"
+ *
controller:
+   *     "MyRegisteredController as fooCtrl"}
+ *
controller: function($scope, MyService) {
+   *     $scope.data = MyService.getData(); }
+ * + * @param {function=} stateConfig.controllerProvider + * + * + * Injectable provider function that returns the actual controller or string. + *
controllerProvider:
+   *   function(MyResolveData) {
+   *     if (MyResolveData.foo)
+   *       return "FooCtrl"
+   *     else if (MyResolveData.bar)
+   *       return "BarCtrl";
+   *     else return function($scope) {
+   *       $scope.baz = "Qux";
+   *     }
+   *   }
+ * + * @param {string=} stateConfig.controllerAs + * + * + * A controller alias name. If present the controller will be + * published to scope under the controllerAs name. + *
controllerAs: "myCtrl"
+ * + * @param {string|object=} stateConfig.parent + * + * Optionally specifies the parent state of this state. + * + *
parent: 'parentState'
+ *
parent: parentState // JS variable
+ * + * @param {object=} stateConfig.resolve + * + * + * An optional map<string, function> of dependencies which + * should be injected into the controller. If any of these dependencies are promises, + * the router will wait for them all to be resolved before the controller is instantiated. + * If all the promises are resolved successfully, the $stateChangeSuccess event is fired + * and the values of the resolved promises are injected into any controllers that reference them. + * If any of the promises are rejected the $stateChangeError event is fired. + * + * The map object is: + * + * - key - {string}: name of dependency to be injected into controller + * - factory - {string|function}: If string then it is alias for service. Otherwise if function, + * it is injected and return value it treated as dependency. If result is a promise, it is + * resolved before its value is injected into controller. + * + *
resolve: {
+   *     myResolve1:
+   *       function($http, $stateParams) {
+   *         return $http.get("/api/foos/"+stateParams.fooID);
+   *       }
+   *     }
+ * + * @param {string=} stateConfig.url + * + * + * A url fragment with optional parameters. When a state is navigated or + * transitioned to, the `$stateParams` service will be populated with any + * parameters that were passed. + * + * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for + * more details on acceptable patterns ) + * + * examples: + *
url: "/home"
+   * url: "/users/:userid"
+   * url: "/books/{bookid:[a-zA-Z_-]}"
+   * url: "/books/{categoryid:int}"
+   * url: "/books/{publishername:string}/{categoryid:int}"
+   * url: "/messages?before&after"
+   * url: "/messages?{before:date}&{after:date}"
+   * url: "/messages/:mailboxid?{before:date}&{after:date}"
+   * 
+ * + * @param {object=} stateConfig.views + * + * an optional map<string, object> which defined multiple views, or targets views + * manually/explicitly. + * + * Examples: + * + * Targets three named `ui-view`s in the parent state's template + *
views: {
+   *     header: {
+   *       controller: "headerCtrl",
+   *       templateUrl: "header.html"
+   *     }, body: {
+   *       controller: "bodyCtrl",
+   *       templateUrl: "body.html"
+   *     }, footer: {
+   *       controller: "footCtrl",
+   *       templateUrl: "footer.html"
+   *     }
+   *   }
+ * + * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template. + *
views: {
+   *     'header@top': {
+   *       controller: "msgHeaderCtrl",
+   *       templateUrl: "msgHeader.html"
+   *     }, 'body': {
+   *       controller: "messagesCtrl",
+   *       templateUrl: "messages.html"
+   *     }
+   *   }
+ * + * @param {boolean=} [stateConfig.abstract=false] + * + * An abstract state will never be directly activated, + * but can provide inherited properties to its common children states. + *
abstract: true
+ * + * @param {function=} stateConfig.onEnter + * + * + * Callback function for when a state is entered. Good way + * to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, + * because it won't be automatically annotated by your build tools. + * + *
onEnter: function(MyService, $stateParams) {
+   *     MyService.foo($stateParams.myParam);
+   * }
+ * + * @param {function=} stateConfig.onExit + * + * + * Callback function for when a state is exited. Good way to + * trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, + * because it won't be automatically annotated by your build tools. + * + *
onExit: function(MyService, $stateParams) {
+   *     MyService.cleanup($stateParams.myParam);
+   * }
+ * + * @param {boolean=} [stateConfig.reloadOnSearch=true] + * + * + * If `false`, will not retrigger the same state + * just because a search/query parameter has changed (via $location.search() or $location.hash()). + * Useful for when you'd like to modify $location.search() without triggering a reload. + *
reloadOnSearch: false
+ * + * @param {object=} stateConfig.data + * + * + * Arbitrary data object, useful for custom configuration. The parent state's `data` is + * prototypally inherited. In other words, adding a data property to a state adds it to + * the entire subtree via prototypal inheritance. + * + *
data: {
+   *     requiredRole: 'foo'
+   * } 
+ * + * @param {object=} stateConfig.params + * + * + * A map which optionally configures parameters declared in the `url`, or + * defines additional non-url parameters. For each parameter being + * configured, add a configuration object keyed to the name of the parameter. + * + * Each parameter configuration object may contain the following properties: + * + * - ** value ** - {object|function=}: specifies the default value for this + * parameter. This implicitly sets this parameter as optional. + * + * When UI-Router routes to a state and no value is + * specified for this parameter in the URL or transition, the + * default value will be used instead. If `value` is a function, + * it will be injected and invoked, and the return value used. + * + * *Note*: `undefined` is treated as "no default value" while `null` + * is treated as "the default value is `null`". + * + * *Shorthand*: If you only need to configure the default value of the + * parameter, you may use a shorthand syntax. In the **`params`** + * map, instead mapping the param name to a full parameter configuration + * object, simply set map it to the default parameter value, e.g.: + * + *
// define a parameter's default value
+   * params: {
+   *     param1: { value: "defaultValue" }
+   * }
+   * // shorthand default values
+   * params: {
+   *     param1: "defaultValue",
+   *     param2: "param2Default"
+   * }
+ * + * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be + * treated as an array of values. If you specified a Type, the value will be + * treated as an array of the specified Type. Note: query parameter values + * default to a special `"auto"` mode. + * + * For query parameters in `"auto"` mode, if multiple values for a single parameter + * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values + * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if + * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single + * value (e.g.: `{ foo: '1' }`). + * + *
params: {
+   *     param1: { array: true }
+   * }
+ * + * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when + * the current parameter value is the same as the default value. If `squash` is not set, it uses the + * configured default squash policy. + * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`}) + * + * There are three squash settings: + * + * - false: The parameter's default value is not squashed. It is encoded and included in the URL + * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed + * by slashes in the state's `url` declaration, then one of those slashes are omitted. + * This can allow for cleaner looking URLs. + * - `""`: The parameter's default value is replaced with an arbitrary placeholder of your choice. + * + *
params: {
+   *     param1: {
+   *       value: "defaultId",
+   *       squash: true
+   * } }
+   * // squash "defaultValue" to "~"
+   * params: {
+   *     param1: {
+   *       value: "defaultValue",
+   *       squash: "~"
+   * } }
+   * 
+ * + * + * @example + *
+   * // Some state name examples
+   *
+   * // stateName can be a single top-level name (must be unique).
+   * $stateProvider.state("home", {});
+   *
+   * // Or it can be a nested state name. This state is a child of the
+   * // above "home" state.
+   * $stateProvider.state("home.newest", {});
+   *
+   * // Nest states as deeply as needed.
+   * $stateProvider.state("home.newest.abc.xyz.inception", {});
+   *
+   * // state() returns $stateProvider, so you can chain state declarations.
+   * $stateProvider
+   *   .state("home", {})
+   *   .state("about", {})
+   *   .state("contacts", {});
+   * 
+ * + */ + this.state = state; + function state(name, definition) { + /*jshint validthis: true */ + if (isObject(name)) definition = name; + else definition.name = name; + registerState(definition); + return this; + } + + /** + * @ngdoc object + * @name ui.router.state.$state + * + * @requires $rootScope + * @requires $q + * @requires ui.router.state.$view + * @requires $injector + * @requires ui.router.util.$resolve + * @requires ui.router.state.$stateParams + * @requires ui.router.router.$urlRouter + * + * @property {object} params A param object, e.g. {sectionId: section.id)}, that + * you'd like to test against the current active state. + * @property {object} current A reference to the state's config object. However + * you passed it in. Useful for accessing custom data. + * @property {object} transition Currently pending transition. A promise that'll + * resolve or reject. + * + * @description + * `$state` service is responsible for representing states as well as transitioning + * between them. It also provides interfaces to ask for current state or even states + * you're coming from. + */ + this.$get = $get; + $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory']; + function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) { + + var TransitionSupersededError = new Error('transition superseded'); + + var TransitionSuperseded = silenceUncaughtInPromise($q.reject(TransitionSupersededError)); + var TransitionPrevented = silenceUncaughtInPromise($q.reject(new Error('transition prevented'))); + var TransitionAborted = silenceUncaughtInPromise($q.reject(new Error('transition aborted'))); + var TransitionFailed = silenceUncaughtInPromise($q.reject(new Error('transition failed'))); + + // Handles the case where a state which is the target of a transition is not found, and the user + // can optionally retry or defer the transition + function handleRedirect(redirect, state, params, options) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateNotFound + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when a requested state **cannot be found** using the provided state name during transition. + * The event is broadcast allowing any handlers a single chance to deal with the error (usually by + * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, + * you can see its three properties in the example. You can use `event.preventDefault()` to abort the + * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. + * + * @param {Object} event Event object. + * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. + * @param {State} fromState Current state object. + * @param {Object} fromParams Current state params. + * + * @example + * + *
+       * // somewhere, assume lazy.state has not been defined
+       * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
+       *
+       * // somewhere else
+       * $scope.$on('$stateNotFound',
+       * function(event, unfoundState, fromState, fromParams){
+       *     console.log(unfoundState.to); // "lazy.state"
+       *     console.log(unfoundState.toParams); // {a:1, b:2}
+       *     console.log(unfoundState.options); // {inherit:false} + default options
+       * })
+       * 
+ */ + var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); + + if (evt.defaultPrevented) { + $urlRouter.update(); + return TransitionAborted; + } + + if (!evt.retry) { + return null; + } + + // Allow the handler to return a promise to defer state lookup retry + if (options.$retry) { + $urlRouter.update(); + return TransitionFailed; + } + var retryTransition = $state.transition = $q.when(evt.retry); + + retryTransition.then(function() { + if (retryTransition !== $state.transition) { + $rootScope.$broadcast('$stateChangeCancel', redirect.to, redirect.toParams, state, params); + return TransitionSuperseded; + } + redirect.options.$retry = true; + return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); + }, function() { + return TransitionAborted; + }); + $urlRouter.update(); + + return retryTransition; + } + + root.locals = { resolve: null, globals: { $stateParams: {} } }; + + $state = { + params: {}, + current: root.self, + $current: root, + transition: null + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#reload + * @methodOf ui.router.state.$state + * + * @description + * A method that force reloads the current state. All resolves are re-resolved, + * controllers reinstantiated, and events re-fired. + * + * @example + *
+     * var app angular.module('app', ['ui.router']);
+     *
+     * app.controller('ctrl', function ($scope, $state) {
+     *   $scope.reload = function(){
+     *     $state.reload();
+     *   }
+     * });
+     * 
+ * + * `reload()` is just an alias for: + *
+     * $state.transitionTo($state.current, $stateParams, {
+     *   reload: true, inherit: false, notify: true
+     * });
+     * 
+ * + * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved. + * @example + *
+     * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
+     * //and current state is 'contacts.detail.item'
+     * var app angular.module('app', ['ui.router']);
+     *
+     * app.controller('ctrl', function ($scope, $state) {
+     *   $scope.reload = function(){
+     *     //will reload 'contact.detail' and 'contact.detail.item' states
+     *     $state.reload('contact.detail');
+     *   }
+     * });
+     * 
+ * + * `reload()` is just an alias for: + *
+     * $state.transitionTo($state.current, $stateParams, {
+     *   reload: true, inherit: false, notify: true
+     * });
+     * 
+ + * @returns {promise} A promise representing the state of the new transition. See + * {@link ui.router.state.$state#methods_go $state.go}. + */ + $state.reload = function reload(state) { + return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true}); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#go + * @methodOf ui.router.state.$state + * + * @description + * Convenience method for transitioning to a new state. `$state.go` calls + * `$state.transitionTo` internally but automatically sets options to + * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. + * This allows you to easily use an absolute or relative to path and specify + * only the parameters you'd like to update (while letting unspecified parameters + * inherit from the currently active ancestor states). + * + * @example + *
+     * var app = angular.module('app', ['ui.router']);
+     *
+     * app.controller('ctrl', function ($scope, $state) {
+     *   $scope.changeState = function () {
+     *     $state.go('contact.detail');
+     *   };
+     * });
+     * 
+ * + * + * @param {string} to Absolute state name or relative state path. Some examples: + * + * - `$state.go('contact.detail')` - will go to the `contact.detail` state + * - `$state.go('^')` - will go to a parent state + * - `$state.go('^.sibling')` - will go to a sibling state + * - `$state.go('.child.grandchild')` - will go to grandchild state + * + * @param {object=} params A map of the parameters that will be sent to the state, + * will populate $stateParams. Any parameters that are not specified will be inherited from currently + * defined parameters. Only parameters specified in the state definition can be overridden, new + * parameters will be ignored. This allows, for example, going to a sibling state that shares parameters + * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. + * transitioning to a sibling will get you the parameters for all parents, transitioning to a child + * will get you all current parameters, etc. + * @param {object=} options Options object. The options are: + * + * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` + * will not. If string, must be `"replace"`, which will update url and also replace last history record. + * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. + * - **`reload`** (v0.2.5) - {boolean=false|string|object}, If `true` will force transition even if no state or params + * have changed. It will reload the resolves and views of the current state and parent states. + * If `reload` is a string (or state object), the state object is fetched (by name, or object reference); and \ + * the transition reloads the resolves and views for that matched state, and all its children states. + * + * @returns {promise} A promise representing the state of the new transition. + * + * Possible success values: + * + * - $state.current + * + *
Possible rejection values: + * + * - 'transition superseded' - when a newer transition has been started after this one + * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener + * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or + * when a `$stateNotFound` `event.retry` promise errors. + * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. + * - *resolve error* - when an error has occurred with a `resolve` + * + */ + $state.go = function go(to, params, options) { + return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#transitionTo + * @methodOf ui.router.state.$state + * + * @description + * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} + * uses `transitionTo` internally. `$state.go` is recommended in most situations. + * + * @example + *
+     * var app = angular.module('app', ['ui.router']);
+     *
+     * app.controller('ctrl', function ($scope, $state) {
+     *   $scope.changeState = function () {
+     *     $state.transitionTo('contact.detail');
+     *   };
+     * });
+     * 
+ * + * @param {string} to State name. + * @param {object=} toParams A map of the parameters that will be sent to the state, + * will populate $stateParams. + * @param {object=} options Options object. The options are: + * + * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` + * will not. If string, must be `"replace"`, which will update url and also replace last history record. + * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. + * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params + * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd + * use this when you want to force a reload when *everything* is the same, including search params. + * if String, then will reload the state with the name given in reload, and any children. + * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children. + * + * @returns {promise} A promise representing the state of the new transition. See + * {@link ui.router.state.$state#methods_go $state.go}. + */ + $state.transitionTo = function transitionTo(to, toParams, options) { + toParams = toParams || {}; + options = extend({ + location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false + }, options || {}); + + var from = $state.$current, fromParams = $state.params, fromPath = from.path; + var evt, toState = findState(to, options.relative); + + // Store the hash param for later (since it will be stripped out by various methods) + var hash = toParams['#']; + + if (!isDefined(toState)) { + var redirect = { to: to, toParams: toParams, options: options }; + var redirectResult = handleRedirect(redirect, from.self, fromParams, options); + + if (redirectResult) { + return redirectResult; + } + + // Always retry once if the $stateNotFound was not prevented + // (handles either redirect changed or state lazy-definition) + to = redirect.to; + toParams = redirect.toParams; + options = redirect.options; + toState = findState(to, options.relative); + + if (!isDefined(toState)) { + if (!options.relative) throw new Error("No such state '" + to + "'"); + throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); + } + } + if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); + if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); + if (!toState.params.$$validates(toParams)) return TransitionFailed; + + toParams = toState.params.$$values(toParams); + to = toState; + + var toPath = to.path; + + // Starting from the root of the path, keep all levels that haven't changed + var keep = 0, state = toPath[keep], locals = root.locals, toLocals = []; + + if (!options.reload) { + while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) { + locals = toLocals[keep] = state.locals; + keep++; + state = toPath[keep]; + } + } else if (isString(options.reload) || isObject(options.reload)) { + if (isObject(options.reload) && !options.reload.name) { + throw new Error('Invalid reload state object'); + } + + var reloadState = options.reload === true ? fromPath[0] : findState(options.reload); + if (options.reload && !reloadState) { + throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'"); + } + + while (state && state === fromPath[keep] && state !== reloadState) { + locals = toLocals[keep] = state.locals; + keep++; + state = toPath[keep]; + } + } + + // If we're going to the same state and all locals are kept, we've got nothing to do. + // But clear 'transition', as we still want to cancel any other pending transitions. + // TODO: We may not want to bump 'transition' if we're called from a location change + // that we've initiated ourselves, because we might accidentally abort a legitimate + // transition initiated from code? + if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) { + if (hash) toParams['#'] = hash; + $state.params = toParams; + copy($state.params, $stateParams); + copy(filterByKeys(to.params.$$keys(), $stateParams), to.locals.globals.$stateParams); + if (options.location && to.navigable && to.navigable.url) { + $urlRouter.push(to.navigable.url, toParams, { + $$avoidResync: true, replace: options.location === 'replace' + }); + $urlRouter.update(true); + } + $state.transition = null; + return $q.when($state.current); + } + + // Filter parameters before we pass them to event handlers etc. + toParams = filterByKeys(to.params.$$keys(), toParams || {}); + + // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart + if (hash) toParams['#'] = hash; + + // Broadcast start event and cancel the transition if requested + if (options.notify) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeStart + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when the state transition **begins**. You can use `event.preventDefault()` + * to prevent the transition from happening and then the transition promise will be + * rejected with a `'transition prevented'` value. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + * + * @example + * + *
+         * $rootScope.$on('$stateChangeStart',
+         * function(event, toState, toParams, fromState, fromParams){
+         *     event.preventDefault();
+         *     // transitionTo() promise will be rejected with
+         *     // a 'transition prevented' error
+         * })
+         * 
+ */ + if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams, options).defaultPrevented) { + $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); + //Don't update and resync url if there's been a new transition started. see issue #2238, #600 + if ($state.transition == null) $urlRouter.update(); + return TransitionPrevented; + } + } + + // Resolve locals for the remaining states, but don't update any global state just + // yet -- if anything fails to resolve the current state needs to remain untouched. + // We also set up an inheritance chain for the locals here. This allows the view directive + // to quickly look up the correct definition for each view in the current state. Even + // though we create the locals object itself outside resolveState(), it is initially + // empty and gets filled asynchronously. We need to keep track of the promise for the + // (fully resolved) current locals, and pass this down the chain. + var resolved = $q.when(locals); + + for (var l = keep; l < toPath.length; l++, state = toPath[l]) { + locals = toLocals[l] = inherit(locals); + resolved = resolveState(state, toParams, state === to, resolved, locals, options); + } + + // Once everything is resolved, we are ready to perform the actual transition + // and return a promise for the new state. We also keep track of what the + // current promise is, so that we can detect overlapping transitions and + // keep only the outcome of the last transition. + var transition = $state.transition = resolved.then(function () { + var l, entering, exiting; + + if ($state.transition !== transition) { + $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); + return TransitionSuperseded; + } + + // Exit 'from' states not kept + for (l = fromPath.length - 1; l >= keep; l--) { + exiting = fromPath[l]; + if (exiting.self.onExit) { + $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); + } + exiting.locals = null; + } + + // Enter 'to' states not kept + for (l = keep; l < toPath.length; l++) { + entering = toPath[l]; + entering.locals = toLocals[l]; + if (entering.self.onEnter) { + $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals); + } + } + + // Run it again, to catch any transitions in callbacks + if ($state.transition !== transition) { + $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); + return TransitionSuperseded; + } + + // Update globals in $state + $state.$current = to; + $state.current = to.self; + $state.params = toParams; + copy($state.params, $stateParams); + $state.transition = null; + + if (options.location && to.navigable) { + $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, { + $$avoidResync: true, replace: options.location === 'replace' + }); + } + + if (options.notify) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeSuccess + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired once the state transition is **complete**. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + */ + $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams); + } + $urlRouter.update(true); + + return $state.current; + }).then(null, function (error) { + // propagate TransitionSuperseded error without emitting $stateChangeCancel + // as it was already emitted in the success handler above + if (error === TransitionSupersededError) return TransitionSuperseded; + + if ($state.transition !== transition) { + $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); + return TransitionSuperseded; + } + + $state.transition = null; + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeError + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when an **error occurs** during transition. It's important to note that if you + * have any errors in your resolve functions (javascript errors, non-existent services, etc) + * they will not throw traditionally. You must listen for this $stateChangeError event to + * catch **ALL** errors. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + * @param {Error} error The resolve error object. + */ + evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error); + + if (!evt.defaultPrevented) { + $urlRouter.update(); + } + + return $q.reject(error); + }); + + silenceUncaughtInPromise(transition); + return transition; + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#is + * @methodOf ui.router.state.$state + * + * @description + * Similar to {@link ui.router.state.$state#methods_includes $state.includes}, + * but only checks for the full state name. If params is supplied then it will be + * tested for strict equality against the current active params object, so all params + * must match with none missing and no extras. + * + * @example + *
+     * $state.$current.name = 'contacts.details.item';
+     *
+     * // absolute name
+     * $state.is('contact.details.item'); // returns true
+     * $state.is(contactDetailItemStateObject); // returns true
+     *
+     * // relative name (. and ^), typically from a template
+     * // E.g. from the 'contacts.details' template
+     * 
Item
+ *
+ * + * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check. + * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like + * to test against the current active state. + * @param {object=} options An options object. The options are: + * + * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will + * test relative to `options.relative` state (or name). + * + * @returns {boolean} Returns true if it is the state. + */ + $state.is = function is(stateOrName, params, options) { + options = extend({ relative: $state.$current }, options || {}); + var state = findState(stateOrName, options.relative); + + if (!isDefined(state)) { return undefined; } + if ($state.$current !== state) { return false; } + + return !params || objectKeys(params).reduce(function(acc, key) { + var paramDef = state.params[key]; + return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]); + }, true); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#includes + * @methodOf ui.router.state.$state + * + * @description + * A method to determine if the current active state is equal to or is the child of the + * state stateName. If any params are passed then they will be tested for a match as well. + * Not all the parameters need to be passed, just the ones you'd like to test for equality. + * + * @example + * Partial and relative names + *
+     * $state.$current.name = 'contacts.details.item';
+     *
+     * // Using partial names
+     * $state.includes("contacts"); // returns true
+     * $state.includes("contacts.details"); // returns true
+     * $state.includes("contacts.details.item"); // returns true
+     * $state.includes("contacts.list"); // returns false
+     * $state.includes("about"); // returns false
+     *
+     * // Using relative names (. and ^), typically from a template
+     * // E.g. from the 'contacts.details' template
+     * 
Item
+ *
+ * + * Basic globbing patterns + *
+     * $state.$current.name = 'contacts.details.item.url';
+     *
+     * $state.includes("*.details.*.*"); // returns true
+     * $state.includes("*.details.**"); // returns true
+     * $state.includes("**.item.**"); // returns true
+     * $state.includes("*.details.item.url"); // returns true
+     * $state.includes("*.details.*.url"); // returns true
+     * $state.includes("*.details.*"); // returns false
+     * $state.includes("item.**"); // returns false
+     * 
+ * + * @param {string} stateOrName A partial name, relative name, or glob pattern + * to be searched for within the current state name. + * @param {object=} params A param object, e.g. `{sectionId: section.id}`, + * that you'd like to test against the current active state. + * @param {object=} options An options object. The options are: + * + * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set, + * .includes will test relative to `options.relative` state (or name). + * + * @returns {boolean} Returns true if it does include the state + */ + $state.includes = function includes(stateOrName, params, options) { + options = extend({ relative: $state.$current }, options || {}); + if (isString(stateOrName) && isGlob(stateOrName)) { + if (!doesStateMatchGlob(stateOrName)) { + return false; + } + stateOrName = $state.$current.name; + } + + var state = findState(stateOrName, options.relative); + if (!isDefined(state)) { return undefined; } + if (!isDefined($state.$current.includes[state.name])) { return false; } + if (!params) { return true; } + + var keys = objectKeys(params); + for (var i = 0; i < keys.length; i++) { + var key = keys[i], paramDef = state.params[key]; + if (paramDef && !paramDef.type.equals($stateParams[key], params[key])) { + return false; + } + } + + return objectKeys(params).reduce(function(acc, key) { + var paramDef = state.params[key]; + return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]); + }, true); + }; + + + /** + * @ngdoc function + * @name ui.router.state.$state#href + * @methodOf ui.router.state.$state + * + * @description + * A url generation method that returns the compiled url for the given state populated with the given params. + * + * @example + *
+     * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
+     * 
+ * + * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. + * @param {object=} params An object of parameter values to fill the state's required parameters. + * @param {object=} options Options object. The options are: + * + * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the + * first parameter, then the constructed href url will be built from the first navigable ancestor (aka + * ancestor with a valid url). + * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". + * + * @returns {string} compiled state url + */ + $state.href = function href(stateOrName, params, options) { + options = extend({ + lossy: true, + inherit: true, + absolute: false, + relative: $state.$current + }, options || {}); + + var state = findState(stateOrName, options.relative); + + if (!isDefined(state)) return null; + if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state); + + var nav = (state && options.lossy) ? state.navigable : state; + + if (!nav || nav.url === undefined || nav.url === null) { + return null; + } + return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), { + absolute: options.absolute + }); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#get + * @methodOf ui.router.state.$state + * + * @description + * Returns the state configuration object for any specific state or all states. + * + * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for + * the requested state. If not provided, returns an array of ALL state configs. + * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context. + * @returns {Object|Array} State configuration object or array of all objects. + */ + $state.get = function (stateOrName, context) { + if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; }); + var state = findState(stateOrName, context || $state.$current); + return (state && state.self) ? state.self : null; + }; + + function resolveState(state, params, paramsAreFiltered, inherited, dst, options) { + // Make a restricted $stateParams with only the parameters that apply to this state if + // necessary. In addition to being available to the controller and onEnter/onExit callbacks, + // we also need $stateParams to be available for any $injector calls we make during the + // dependency resolution process. + var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params); + var locals = { $stateParams: $stateParams }; + + // Resolve 'global' dependencies for the state, i.e. those not specific to a view. + // We're also including $stateParams in this; that way the parameters are restricted + // to the set that should be visible to the state, and are independent of when we update + // the global $state and $stateParams values. + dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); + var promises = [dst.resolve.then(function (globals) { + dst.globals = globals; + })]; + if (inherited) promises.push(inherited); + + function resolveViews() { + var viewsPromises = []; + + // Resolve template and dependencies for all views. + forEach(state.views, function (view, name) { + var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); + injectables.$template = [ function () { + return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || ''; + }]; + + viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) { + // References to the controller (only instantiated at link time) + if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { + var injectLocals = angular.extend({}, injectables, dst.globals); + result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); + } else { + result.$$controller = view.controller; + } + // Provide access to the state itself for internal use + result.$$state = state; + result.$$controllerAs = view.controllerAs; + result.$$resolveAs = view.resolveAs; + dst[name] = result; + })); + }); + + return $q.all(viewsPromises).then(function(){ + return dst.globals; + }); + } + + // Wait for all the promises and then return the activation object + return $q.all(promises).then(resolveViews).then(function (values) { + return dst; + }); + } + + return $state; + } + + function shouldSkipReload(to, toParams, from, fromParams, locals, options) { + // Return true if there are no differences in non-search (path/object) params, false if there are differences + function nonSearchParamsEqual(fromAndToState, fromParams, toParams) { + // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params. + function notSearchParam(key) { + return fromAndToState.params[key].location != "search"; + } + var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam); + var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys)); + var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams); + return nonQueryParamSet.$$equals(fromParams, toParams); + } + + // If reload was not explicitly requested + // and we're transitioning to the same state we're already in + // and the locals didn't change + // or they changed in a way that doesn't merit reloading + // (reloadOnParams:false, or reloadOnSearch.false and only search params changed) + // Then return true. + if (!options.reload && to === from && + (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) { + return true; + } + } +} + +angular.module('ui.router.state') + .factory('$stateParams', function () { return {}; }) + .constant("$state.runtime", { autoinject: true }) + .provider('$state', $StateProvider) + // Inject $state to initialize when entering runtime. #2574 + .run(['$injector', function ($injector) { + // Allow tests (stateSpec.js) to turn this off by defining this constant + if ($injector.get("$state.runtime").autoinject) { + $injector.get('$state'); + } + }]); + + +$ViewProvider.$inject = []; +function $ViewProvider() { + + this.$get = $get; + /** + * @ngdoc object + * @name ui.router.state.$view + * + * @requires ui.router.util.$templateFactory + * @requires $rootScope + * + * @description + * + */ + $get.$inject = ['$rootScope', '$templateFactory']; + function $get( $rootScope, $templateFactory) { + return { + // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... }) + /** + * @ngdoc function + * @name ui.router.state.$view#load + * @methodOf ui.router.state.$view + * + * @description + * + * @param {string} name name + * @param {object} options option object. + */ + load: function load(name, options) { + var result, defaults = { + template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {} + }; + options = extend(defaults, options); + + if (options.view) { + result = $templateFactory.fromConfig(options.view, options.params, options.locals); + } + return result; + } + }; + } +} + +angular.module('ui.router.state').provider('$view', $ViewProvider); + +/** + * @ngdoc object + * @name ui.router.state.$uiViewScrollProvider + * + * @description + * Provider that returns the {@link ui.router.state.$uiViewScroll} service function. + */ +function $ViewScrollProvider() { + + var useAnchorScroll = false; + + /** + * @ngdoc function + * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll + * @methodOf ui.router.state.$uiViewScrollProvider + * + * @description + * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for + * scrolling based on the url anchor. + */ + this.useAnchorScroll = function () { + useAnchorScroll = true; + }; + + /** + * @ngdoc object + * @name ui.router.state.$uiViewScroll + * + * @requires $anchorScroll + * @requires $timeout + * + * @description + * When called with a jqLite element, it scrolls the element into view (after a + * `$timeout` so the DOM has time to refresh). + * + * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor, + * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}. + */ + this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { + if (useAnchorScroll) { + return $anchorScroll; + } + + return function ($element) { + return $timeout(function () { + $element[0].scrollIntoView(); + }, 0, false); + }; + }]; +} + +angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); + +/** + * @ngdoc directive + * @name ui.router.state.directive:ui-view + * + * @requires ui.router.state.$state + * @requires $compile + * @requires $controller + * @requires $injector + * @requires ui.router.state.$uiViewScroll + * @requires $document + * + * @restrict ECA + * + * @description + * The ui-view directive tells $state where to place your templates. + * + * @param {string=} name A view name. The name should be unique amongst the other views in the + * same state. You can have views of the same name that live in different states. + * + * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window + * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll + * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you + * scroll ui-view elements into view when they are populated during a state activation. + * + * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) + * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.* + * + * @param {string=} onload Expression to evaluate whenever the view updates. + * + * @example + * A view can be unnamed or named. + *
+ * 
+ * 
+ * + * + *
+ *
+ * + * You can only have one unnamed view within any template (or root html). If you are only using a + * single view and it is unnamed then you can populate it like so: + *
+ * 
+ * $stateProvider.state("home", { + * template: "

HELLO!

" + * }) + *
+ * + * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#methods_state `views`} + * config property, by name, in this case an empty name: + *
+ * $stateProvider.state("home", {
+ *   views: {
+ *     "": {
+ *       template: "

HELLO!

" + * } + * } + * }) + *
+ * + * But typically you'll only use the views property if you name your view or have more than one view + * in the same template. There's not really a compelling reason to name a view if its the only one, + * but you could if you wanted, like so: + *
+ * 
+ *
+ *
+ * $stateProvider.state("home", {
+ *   views: {
+ *     "main": {
+ *       template: "

HELLO!

" + * } + * } + * }) + *
+ * + * Really though, you'll use views to set up multiple views: + *
+ * 
+ *
+ *
+ *
+ * + *
+ * $stateProvider.state("home", {
+ *   views: {
+ *     "": {
+ *       template: "

HELLO!

" + * }, + * "chart": { + * template: "" + * }, + * "data": { + * template: "" + * } + * } + * }) + *
+ * + * Examples for `autoscroll`: + * + *
+ * 
+ * 
+ *
+ * 
+ * 
+ * 
+ * 
+ * 
+ * + * Resolve data: + * + * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this + * can be customized using [[ViewDeclaration.resolveAs]]). This can be then accessed from the template. + * + * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the + * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which + * depends on `$resolve` data. + * + * Example usage of $resolve in a view template + *
+ * $stateProvider.state('home', {
+ *   template: '',
+ *   resolve: {
+ *     user: function(UserService) { return UserService.fetchUser(); }
+ *   }
+ * });
+ * 
+ */ +$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate', '$q']; +function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate, $q) { + + function getService() { + return ($injector.has) ? function(service) { + return $injector.has(service) ? $injector.get(service) : null; + } : function(service) { + try { + return $injector.get(service); + } catch (e) { + return null; + } + }; + } + + var service = getService(), + $animator = service('$animator'), + $animate = service('$animate'); + + // Returns a set of DOM manipulation functions based on which Angular version + // it should use + function getRenderer(attrs, scope) { + var statics = function() { + return { + enter: function (element, target, cb) { target.after(element); cb(); }, + leave: function (element, cb) { element.remove(); cb(); } + }; + }; + + if ($animate) { + return { + enter: function(element, target, cb) { + if (angular.version.minor > 2) { + $animate.enter(element, null, target).then(cb); + } else { + $animate.enter(element, null, target, cb); + } + }, + leave: function(element, cb) { + if (angular.version.minor > 2) { + $animate.leave(element).then(cb); + } else { + $animate.leave(element, cb); + } + } + }; + } + + if ($animator) { + var animate = $animator && $animator(scope, attrs); + + return { + enter: function(element, target, cb) {animate.enter(element, null, target); cb(); }, + leave: function(element, cb) { animate.leave(element); cb(); } + }; + } + + return statics(); + } + + var directive = { + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + compile: function (tElement, tAttrs, $transclude) { + return function (scope, $element, attrs) { + var previousEl, currentEl, currentScope, latestLocals, + onloadExp = attrs.onload || '', + autoScrollExp = attrs.autoscroll, + renderer = getRenderer(attrs, scope), + inherited = $element.inheritedData('$uiView'); + + scope.$on('$stateChangeSuccess', function() { + updateView(false); + }); + + updateView(true); + + function cleanupLastView() { + if (previousEl) { + previousEl.remove(); + previousEl = null; + } + + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + + if (currentEl) { + var $uiViewData = currentEl.data('$uiViewAnim'); + renderer.leave(currentEl, function() { + $uiViewData.$$animLeave.resolve(); + previousEl = null; + }); + + previousEl = currentEl; + currentEl = null; + } + } + + function updateView(firstTime) { + var newScope, + name = getUiViewName(scope, attrs, $element, $interpolate), + previousLocals = name && $state.$current && $state.$current.locals[name]; + + if (!firstTime && previousLocals === latestLocals) return; // nothing to do + newScope = scope.$new(); + latestLocals = $state.$current.locals[name]; + + /** + * @ngdoc event + * @name ui.router.state.directive:ui-view#$viewContentLoading + * @eventOf ui.router.state.directive:ui-view + * @eventType emits on ui-view directive scope + * @description + * + * Fired once the view **begins loading**, *before* the DOM is rendered. + * + * @param {Object} event Event object. + * @param {string} viewName Name of the view. + */ + newScope.$emit('$viewContentLoading', name); + + var clone = $transclude(newScope, function(clone) { + var animEnter = $q.defer(), animLeave = $q.defer(); + var viewAnimData = { + $animEnter: animEnter.promise, + $animLeave: animLeave.promise, + $$animLeave: animLeave + }; + + clone.data('$uiViewAnim', viewAnimData); + renderer.enter(clone, $element, function onUiViewEnter() { + animEnter.resolve(); + if(currentScope) { + currentScope.$emit('$viewContentAnimationEnded'); + } + + if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { + $uiViewScroll(clone); + } + }); + cleanupLastView(); + }); + + currentEl = clone; + currentScope = newScope; + /** + * @ngdoc event + * @name ui.router.state.directive:ui-view#$viewContentLoaded + * @eventOf ui.router.state.directive:ui-view + * @eventType emits on ui-view directive scope + * @description + * Fired once the view is **loaded**, *after* the DOM is rendered. + * + * @param {Object} event Event object. + * @param {string} viewName Name of the view. + */ + currentScope.$emit('$viewContentLoaded', name); + currentScope.$eval(onloadExp); + } + }; + } + }; + + return directive; +} + +$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate']; +function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) { + return { + restrict: 'ECA', + priority: -400, + compile: function (tElement) { + var initial = tElement.html(); + if (tElement.empty) { + tElement.empty(); + } else { + // ng 1.0.0 doesn't have empty(), which cleans up data and handlers + tElement[0].innerHTML = null; + } + + return function (scope, $element, attrs) { + var current = $state.$current, + name = getUiViewName(scope, attrs, $element, $interpolate), + locals = current && current.locals[name]; + + if (! locals) { + $element.html(initial); + $compile($element.contents())(scope); + return; + } + + $element.data('$uiView', { name: name, state: locals.$$state }); + $element.html(locals.$template ? locals.$template : initial); + + var resolveData = angular.extend({}, locals); + scope[locals.$$resolveAs] = resolveData; + + var link = $compile($element.contents()); + + if (locals.$$controller) { + locals.$scope = scope; + locals.$element = $element; + var controller = $controller(locals.$$controller, locals); + if (locals.$$controllerAs) { + scope[locals.$$controllerAs] = controller; + scope[locals.$$controllerAs][locals.$$resolveAs] = resolveData; + } + if (isFunction(controller.$onInit)) controller.$onInit(); + $element.data('$ngControllerController', controller); + $element.children().data('$ngControllerController', controller); + } + + link(scope); + }; + } + }; +} + +/** + * Shared ui-view code for both directives: + * Given scope, element, and its attributes, return the view's name + */ +function getUiViewName(scope, attrs, element, $interpolate) { + var name = $interpolate(attrs.uiView || attrs.name || '')(scope); + var uiViewCreatedBy = element.inheritedData('$uiView'); + return name.indexOf('@') >= 0 ? name : (name + '@' + (uiViewCreatedBy ? uiViewCreatedBy.state.name : '')); +} + +angular.module('ui.router.state').directive('uiView', $ViewDirective); +angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill); + +function parseStateRef(ref, current) { + var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed; + if (preparsed) ref = current + '(' + preparsed[1] + ')'; + parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/); + if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); + return { state: parsed[1], paramExpr: parsed[3] || null }; +} + +function stateContext(el) { + var stateData = el.parent().inheritedData('$uiView'); + + if (stateData && stateData.state && stateData.state.name) { + return stateData.state; + } +} + +function getTypeInfo(el) { + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. + var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]'; + var isForm = el[0].nodeName === "FORM"; + + return { + attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'), + isAnchor: el.prop("tagName").toUpperCase() === "A", + clickable: !isForm + }; +} + +function clickHook(el, $state, $timeout, type, current) { + return function(e) { + var button = e.which || e.button, target = current(); + + if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) { + // HACK: This is to allow ng-clicks to be processed before the transition is initiated: + var transition = $timeout(function() { + $state.go(target.state, target.params, target.options); + }); + e.preventDefault(); + + // if the state has no URL, ignore one preventDefault from the directive. + var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1: 0; + + e.preventDefault = function() { + if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition); + }; + } + }; +} + +function defaultOpts(el, $state) { + return { relative: stateContext(el) || $state.$current, inherit: true }; +} + +/** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref + * + * @requires ui.router.state.$state + * @requires $timeout + * + * @restrict A + * + * @description + * A directive that binds a link (`` tag) to a state. If the state has an associated + * URL, the directive will automatically generate & update the `href` attribute via + * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking + * the link will trigger a state transition with optional parameters. + * + * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be + * handled natively by the browser. + * + * You can also use relative state paths within ui-sref, just like the relative + * paths passed to `$state.go()`. You just need to be aware that the path is relative + * to the state that the link lives in, in other words the state that loaded the + * template containing the link. + * + * You can specify options to pass to {@link ui.router.state.$state#methods_go $state.go()} + * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`, + * and `reload`. + * + * @example + * Here's an example of how you'd use ui-sref and how it would compile. If you have the + * following template: + *
+ * Home | About | Next page
+ *
+ * 
+ * 
+ * + * Then the compiled html would be (assuming Html5Mode is off and current state is contacts): + *
+ * Home | About | Next page
+ *
+ * 
    + *
  • + * Joe + *
  • + *
  • + * Alice + *
  • + *
  • + * Bob + *
  • + *
+ * + * Home + *
+ * + * @param {string} ui-sref 'stateName' can be any valid absolute or relative state + * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()} + */ +$StateRefDirective.$inject = ['$state', '$timeout']; +function $StateRefDirective($state, $timeout) { + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(scope, element, attrs, uiSrefActive) { + var ref = parseStateRef(attrs.uiSref, $state.current.name); + var def = { state: ref.state, href: null, params: null }; + var type = getTypeInfo(element); + var active = uiSrefActive[1] || uiSrefActive[0]; + var unlinkInfoFn = null; + var hookFn; + + def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {}); + + var update = function(val) { + if (val) def.params = angular.copy(val); + def.href = $state.href(ref.state, def.params, def.options); + + if (unlinkInfoFn) unlinkInfoFn(); + if (active) unlinkInfoFn = active.$$addStateInfo(ref.state, def.params); + if (def.href !== null) attrs.$set(type.attr, def.href); + }; + + if (ref.paramExpr) { + scope.$watch(ref.paramExpr, function(val) { if (val !== def.params) update(val); }, true); + def.params = angular.copy(scope.$eval(ref.paramExpr)); + } + update(); + + if (!type.clickable) return; + hookFn = clickHook(element, $state, $timeout, type, function() { return def; }); + element[element.on ? 'on' : 'bind']("click", hookFn); + scope.$on('$destroy', function() { + element[element.off ? 'off' : 'unbind']("click", hookFn); + }); + } + }; +} + +/** + * @ngdoc directive + * @name ui.router.state.directive:ui-state + * + * @requires ui.router.state.uiSref + * + * @restrict A + * + * @description + * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition, + * params and override options. + * + * @param {string} ui-state 'stateName' can be any valid absolute or relative state + * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#methods_href $state.href()} + * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()} + */ +$StateRefDynamicDirective.$inject = ['$state', '$timeout']; +function $StateRefDynamicDirective($state, $timeout) { + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(scope, element, attrs, uiSrefActive) { + var type = getTypeInfo(element); + var active = uiSrefActive[1] || uiSrefActive[0]; + var group = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null]; + var watch = '[' + group.map(function(val) { return val || 'null'; }).join(', ') + ']'; + var def = { state: null, params: null, options: null, href: null }; + var unlinkInfoFn = null; + var hookFn; + + function runStateRefLink (group) { + def.state = group[0]; def.params = group[1]; def.options = group[2]; + def.href = $state.href(def.state, def.params, def.options); + + if (unlinkInfoFn) unlinkInfoFn(); + if (active) unlinkInfoFn = active.$$addStateInfo(def.state, def.params); + if (def.href) attrs.$set(type.attr, def.href); + } + + scope.$watch(watch, runStateRefLink, true); + runStateRefLink(scope.$eval(watch)); + + if (!type.clickable) return; + hookFn = clickHook(element, $state, $timeout, type, function() { return def; }); + element[element.on ? 'on' : 'bind']("click", hookFn); + scope.$on('$destroy', function() { + element[element.off ? 'off' : 'unbind']("click", hookFn); + }); + } + }; +} + + +/** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref-active + * + * @requires ui.router.state.$state + * @requires ui.router.state.$stateParams + * @requires $interpolate + * + * @restrict A + * + * @description + * A directive working alongside ui-sref to add classes to an element when the + * related ui-sref directive's state is active, and removing them when it is inactive. + * The primary use-case is to simplify the special appearance of navigation menus + * relying on `ui-sref`, by having the "active" state's menu button appear different, + * distinguishing it from the inactive menu items. + * + * ui-sref-active can live on the same element as ui-sref or on a parent element. The first + * ui-sref-active found at the same level or above the ui-sref will be used. + * + * Will activate when the ui-sref's target state or any child state is active. If you + * need to activate only when the ui-sref target state is active and *not* any of + * it's children, then you will use + * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq} + * + * @example + * Given the following template: + *
+ * 
+ * 
+ * + * + * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins", + * the resulting HTML will appear as (note the 'active' class): + *
+ * 
+ * 
+ * + * The class name is interpolated **once** during the directives link time (any further changes to the + * interpolated value are ignored). + * + * Multiple classes may be specified in a space-separated format: + *
+ * 
    + *
  • + * link + *
  • + *
+ *
+ * + * It is also possible to pass ui-sref-active an expression that evaluates + * to an object hash, whose keys represent active class names and whose + * values represent the respective state names/globs. + * ui-sref-active will match if the current active state **includes** any of + * the specified state names/globs, even the abstract ones. + * + * @Example + * Given the following template, with "admin" being an abstract state: + *
+ * 
+ * Roles + *
+ *
+ * + * When the current state is "admin.roles" the "active" class will be applied + * to both the
and elements. It is important to note that the state + * names/globs passed to ui-sref-active shadow the state provided by ui-sref. + */ + +/** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref-active-eq + * + * @requires ui.router.state.$state + * @requires ui.router.state.$stateParams + * @requires $interpolate + * + * @restrict A + * + * @description + * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate + * when the exact target state used in the `ui-sref` is active; no child states. + * + */ +$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate']; +function $StateRefActiveDirective($state, $stateParams, $interpolate) { + return { + restrict: "A", + controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) { + var states = [], activeClasses = {}, activeEqClass, uiSrefActive; + + // There probably isn't much point in $observing this + // uiSrefActive and uiSrefActiveEq share the same directive object with some + // slight difference in logic routing + activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope); + + try { + uiSrefActive = $scope.$eval($attrs.uiSrefActive); + } catch (e) { + // Do nothing. uiSrefActive is not a valid expression. + // Fall back to using $interpolate below + } + uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope); + if (isObject(uiSrefActive)) { + forEach(uiSrefActive, function(stateOrName, activeClass) { + if (isString(stateOrName)) { + var ref = parseStateRef(stateOrName, $state.current.name); + addState(ref.state, $scope.$eval(ref.paramExpr), activeClass); + } + }); + } + + // Allow uiSref to communicate with uiSrefActive[Equals] + this.$$addStateInfo = function (newState, newParams) { + // we already got an explicit state provided by ui-sref-active, so we + // shadow the one that comes from ui-sref + if (isObject(uiSrefActive) && states.length > 0) { + return; + } + var deregister = addState(newState, newParams, uiSrefActive); + update(); + return deregister; + }; + + $scope.$on('$stateChangeSuccess', update); + + function addState(stateName, stateParams, activeClass) { + var state = $state.get(stateName, stateContext($element)); + var stateHash = createStateHash(stateName, stateParams); + + var stateInfo = { + state: state || { name: stateName }, + params: stateParams, + hash: stateHash + }; + + states.push(stateInfo); + activeClasses[stateHash] = activeClass; + + return function removeState() { + var idx = states.indexOf(stateInfo); + if (idx !== -1) states.splice(idx, 1); + }; + } + + /** + * @param {string} state + * @param {Object|string} [params] + * @return {string} + */ + function createStateHash(state, params) { + if (!isString(state)) { + throw new Error('state should be a string'); + } + if (isObject(params)) { + return state + toJson(params); + } + params = $scope.$eval(params); + if (isObject(params)) { + return state + toJson(params); + } + return state; + } + + // Update route state + function update() { + for (var i = 0; i < states.length; i++) { + if (anyMatch(states[i].state, states[i].params)) { + addClass($element, activeClasses[states[i].hash]); + } else { + removeClass($element, activeClasses[states[i].hash]); + } + + if (exactMatch(states[i].state, states[i].params)) { + addClass($element, activeEqClass); + } else { + removeClass($element, activeEqClass); + } + } + } + + function addClass(el, className) { $timeout(function () { el.addClass(className); }); } + function removeClass(el, className) { el.removeClass(className); } + function anyMatch(state, params) { return $state.includes(state.name, params); } + function exactMatch(state, params) { return $state.is(state.name, params); } + + update(); + }] + }; +} + +angular.module('ui.router.state') + .directive('uiSref', $StateRefDirective) + .directive('uiSrefActive', $StateRefActiveDirective) + .directive('uiSrefActiveEq', $StateRefActiveDirective) + .directive('uiState', $StateRefDynamicDirective); + +/** + * @ngdoc filter + * @name ui.router.state.filter:isState + * + * @requires ui.router.state.$state + * + * @description + * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}. + */ +$IsStateFilter.$inject = ['$state']; +function $IsStateFilter($state) { + var isFilter = function (state, params) { + return $state.is(state, params); + }; + isFilter.$stateful = true; + return isFilter; +} + +/** + * @ngdoc filter + * @name ui.router.state.filter:includedByState + * + * @requires ui.router.state.$state + * + * @description + * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}. + */ +$IncludedByStateFilter.$inject = ['$state']; +function $IncludedByStateFilter($state) { + var includesFilter = function (state, params, options) { + return $state.includes(state, params, options); + }; + includesFilter.$stateful = true; + return includesFilter; +} + +angular.module('ui.router.state') + .filter('isState', $IsStateFilter) + .filter('includedByState', $IncludedByStateFilter); +})(window, window.angular); \ No newline at end of file diff --git a/vendor/assets/javascripts/angular-ui-router.min.js b/vendor/assets/javascripts/angular-ui-router.min.js new file mode 100644 index 00000000..8c06f0cd --- /dev/null +++ b/vendor/assets/javascripts/angular-ui-router.min.js @@ -0,0 +1,8 @@ +/** + * State-based routing for AngularJS + * @version v0.4.2 + * @link http://angular-ui.github.com/ + * @license MIT License, http://www.opensource.org/licenses/MIT + */ +"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="ui.router"),function(a,b,c){"use strict";function d(a,b){return T(new(T(function(){},{prototype:a})),b)}function e(a){return S(arguments,function(b){b!==a&&S(b,function(b,c){a.hasOwnProperty(c)||(a[c]=b)})}),a}function f(a,b){var c=[];for(var d in a.path){if(a.path[d]!==b.path[d])break;c.push(a.path[d])}return c}function g(a){if(Object.keys)return Object.keys(a);var b=[];return S(a,function(a,c){b.push(c)}),b}function h(a,b){if(Array.prototype.indexOf)return a.indexOf(b,Number(arguments[2])||0);var c=a.length>>>0,d=Number(arguments[2])||0;for(d=d<0?Math.ceil(d):Math.floor(d),d<0&&(d+=c);d=0||(k.push(e[m]),j[e[m]]=a[e[m]]);return T({},j,b)}function j(a,b,c){if(!c){c=[];for(var d in a)c.push(d)}for(var e=0;e "));if(t[c]=d,P(a))r.push(c,[function(){return b.get(a)}],j);else{var e=b.annotate(a);S(e,function(a){a!==c&&i.hasOwnProperty(a)&&n(i[a],a)}),r.push(c,a,e)}s.pop(),t[c]=f}}function o(a){return Q(a)&&a.then&&a.$$promises}if(!Q(i))throw new Error("'invocables' must be an object");var q=g(i||{}),r=[],s=[],t={};return S(i,n),i=s=t=null,function(d,f,g){function h(){--v||(w||e(u,f.$$values),s.$$values=u,s.$$promises=s.$$promises||!0,delete s.$$inheritedValues,n.resolve(u))}function i(a){s.$$failure=a,n.reject(a)}function j(c,e,f){function j(a){l.reject(a),i(a)}function k(){if(!N(s.$$failure))try{l.resolve(b.invoke(e,g,u)),l.promise.then(function(a){u[c]=a,h()},j)}catch(a){j(a)}}var l=a.defer(),m=0;S(f,function(a){t.hasOwnProperty(a)&&!d.hasOwnProperty(a)&&(m++,t[a].then(function(b){u[a]=b,--m||k()},j))}),m||k(),t[c]=p(l.promise)}if(o(d)&&g===c&&(g=f,f=d,d=null),d){if(!Q(d))throw new Error("'locals' must be an object")}else d=k;if(f){if(!o(f))throw new Error("'parent' must be a promise returned by $resolve.resolve()")}else f=l;var n=a.defer(),s=p(n.promise),t=s.$$promises={},u=T({},d),v=1+r.length/3,w=!1;if(p(s),N(f.$$failure))return i(f.$$failure),s;f.$$inheritedValues&&e(u,m(f.$$inheritedValues,q)),T(t,f.$$promises),f.$$values?(w=e(u,m(f.$$values,q)),s.$$inheritedValues=m(f.$$values,q),h()):(f.$$inheritedValues&&(s.$$inheritedValues=m(f.$$inheritedValues,q)),f.then(h,i));for(var x=0,y=r.length;x=0));)s=f(r.id,r.type,r.cfg,"path"),l+=g(r.segment,s.type.pattern.source,s.squash,s.isOptional),n.push(r.segment),m=j.lastIndex;t=a.substring(m);var u=t.indexOf("?");if(u>=0){var v=this.sourceSearch=t.substring(u);if(t=t.substring(0,u),this.sourcePath=a.substring(0,m+u),v.length>0)for(m=0;i=k.exec(v);)r=h(i,!0),s=f(r.id,r.type,r.cfg,"search"),m=j.lastIndex}else this.sourcePath=a,this.sourceSearch="";l+=g(t)+(b.strict===!1?"/?":"")+"$",n.push(t),this.regexp=new RegExp(l,b.caseInsensitive?"i":c),this.prefix=n[0],this.$$paramNames=q}function u(a){T(this,a)}function v(){function a(a){return null!=a?a.toString().replace(/(~|\/)/g,function(a){return{"~":"~~","/":"~2F"}[a]}):a}function e(a){return null!=a?a.toString().replace(/(~~|~2F)/g,function(a){return{"~~":"~","~2F":"/"}[a]}):a}function f(){return{strict:p,caseInsensitive:m}}function i(a){return O(a)||R(a)&&O(a[a.length-1])}function j(){for(;w.length;){var a=w.shift();if(a.pattern)throw new Error("You cannot override a type's .pattern at runtime.");b.extend(r[a.name],l.invoke(a.def))}}function k(a){T(this,a||{})}W=this;var l,m=!1,p=!0,q=!1,r={},s=!0,w=[],x={string:{encode:a,decode:e,is:function(a){return null==a||!N(a)||"string"==typeof a},pattern:/[^\/]*/},int:{encode:a,decode:function(a){return parseInt(a,10)},is:function(a){return a!==c&&null!==a&&this.decode(a.toString())===a},pattern:/\d+/},bool:{encode:function(a){return a?1:0},decode:function(a){return 0!==parseInt(a,10)},is:function(a){return a===!0||a===!1},pattern:/0|1/},date:{encode:function(a){return this.is(a)?[a.getFullYear(),("0"+(a.getMonth()+1)).slice(-2),("0"+a.getDate()).slice(-2)].join("-"):c},decode:function(a){if(this.is(a))return a;var b=this.capture.exec(a);return b?new Date(b[1],b[2]-1,b[3]):c},is:function(a){return a instanceof Date&&!isNaN(a.valueOf())},equals:function(a,b){return this.is(a)&&this.is(b)&&a.toISOString()===b.toISOString()},pattern:/[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,capture:/([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/},json:{encode:b.toJson,decode:b.fromJson,is:b.isObject,equals:b.equals,pattern:/[^\/]*/},any:{encode:b.identity,decode:b.identity,equals:b.equals,pattern:/.*/}};v.$$getDefaultValue=function(a){if(!i(a.value))return a.value;if(!l)throw new Error("Injectable functions cannot be called at configuration time");return l.invoke(a.value)},this.caseInsensitive=function(a){return N(a)&&(m=a),m},this.strictMode=function(a){return N(a)&&(p=a),p},this.defaultSquashPolicy=function(a){if(!N(a))return q;if(a!==!0&&a!==!1&&!P(a))throw new Error("Invalid squash policy: "+a+". Valid policies: false, true, arbitrary-string");return q=a,a},this.compile=function(a,b){return new t(a,T(f(),b))},this.isMatcher=function(a){if(!Q(a))return!1;var b=!0;return S(t.prototype,function(c,d){O(c)&&(b=b&&N(a[d])&&O(a[d]))}),b},this.type=function(a,b,c){if(!N(b))return r[a];if(r.hasOwnProperty(a))throw new Error("A type named '"+a+"' has already been defined.");return r[a]=new u(T({name:a},b)),c&&(w.push({name:a,def:c}),s||j()),this},S(x,function(a,b){r[b]=new u(T({name:b},a))}),r=d(r,{}),this.$get=["$injector",function(a){return l=a,s=!1,j(),S(x,function(a,b){r[b]||(r[b]=new u(a))}),this}],this.Param=function(a,d,e,f){function j(a){var b=Q(a)?g(a):[],c=h(b,"value")===-1&&h(b,"type")===-1&&h(b,"squash")===-1&&h(b,"array")===-1;return c&&(a={value:a}),a.$$fn=i(a.value)?a.value:function(){return a.value},a}function k(c,d,e){if(c.type&&d)throw new Error("Param '"+a+"' has two type configurations.");return d?d:c.type?b.isString(c.type)?r[c.type]:c.type instanceof u?c.type:new u(c.type):"config"===e?r.any:r.string}function m(){var b={array:"search"===f&&"auto"},c=a.match(/\[\]$/)?{array:!0}:{};return T(b,c,e).array}function p(a,b){var c=a.squash;if(!b||c===!1)return!1;if(!N(c)||null==c)return q;if(c===!0||P(c))return c;throw new Error("Invalid squash policy: '"+c+"'. Valid policies: false, true, or arbitrary string")}function s(a,b,d,e){var f,g,i=[{from:"",to:d||b?c:""},{from:null,to:d||b?c:""}];return f=R(a.replace)?a.replace:[],P(e)&&f.push({from:e,to:c}),g=o(f,function(a){return a.from}),n(i,function(a){return h(g,a.from)===-1}).concat(f)}function t(){if(!l)throw new Error("Injectable functions cannot be called at configuration time");var a=l.invoke(e.$$fn);if(null!==a&&a!==c&&!x.type.is(a))throw new Error("Default value ("+a+") for parameter '"+x.id+"' is not an instance of Type ("+x.type.name+")");return a}function v(a){function b(a){return function(b){return b.from===a}}function c(a){var c=o(n(x.replace,b(a)),function(a){return a.to});return c.length?c[0]:a}return a=c(a),N(a)?x.type.$normalize(a):t()}function w(){return"{Param:"+a+" "+d+" squash: '"+A+"' optional: "+z+"}"}var x=this;e=j(e),d=k(e,d,f);var y=m();d=y?d.$asArray(y,"search"===f):d,"string"!==d.name||y||"path"!==f||e.value!==c||(e.value="");var z=e.value!==c,A=p(e,z),B=s(e,y,z,A);T(this,{id:a,type:d,location:f,array:y,squash:A,replace:B,isOptional:z,value:v,dynamic:c,config:e,toString:w})},k.prototype={$$new:function(){return d(this,T(new k,{$$parent:this}))},$$keys:function(){for(var a=[],b=[],c=this,d=g(k.prototype);c;)b.push(c),c=c.$$parent;return b.reverse(),S(b,function(b){S(g(b),function(b){h(a,b)===-1&&h(d,b)===-1&&a.push(b)})}),a},$$values:function(a){var b={},c=this;return S(c.$$keys(),function(d){b[d]=c[d].value(a&&a[d])}),b},$$equals:function(a,b){var c=!0,d=this;return S(d.$$keys(),function(e){var f=a&&a[e],g=b&&b[e];d[e].type.equals(f,g)||(c=!1)}),c},$$validates:function(a){var d,e,f,g,h,i=this.$$keys();for(d=0;d=0)throw new Error("State must have a valid name");if(A.hasOwnProperty(c))throw new Error("State '"+c+"' is already defined");var e=c.indexOf(".")!==-1?c.substring(0,c.lastIndexOf(".")):P(b.parent)?b.parent:Q(b.parent)&&P(b.parent.name)?b.parent.name:"";if(e&&!A[e])return n(e,b.self);for(var f in D)O(D[f])&&(b[f]=D[f](b,D.$delegates[f]));return A[c]=b,!b[C]&&b.url&&a.when(b.url,["$match","$stateParams",function(a,c){z.$current.navigable==b&&j(a,c)||z.transitionTo(b,a,{inherit:!0,location:!1})}]),q(c),b}function s(a){return a.indexOf("*")>-1}function t(a){for(var b=a.split("."),c=z.$current.name.split("."),d=0,e=b.length;d=G;d--)g=q[d],g.self.onExit&&h.invoke(g.self.onExit,g.self,g.locals.globals),g.locals=null;for(d=G;d2?k.enter(a,null,c).then(d):k.enter(a,null,c,d)},leave:function(a,c){b.version.minor>2?k.leave(a).then(c):k.leave(a,c)}};if(j){var e=j&&j(c,a);return{enter:function(a,b,c){e.enter(a,null,b),c()},leave:function(a,b){e.leave(a),b()}}}return d()}var i=g(),j=i("$animator"),k=i("$animate"),l={restrict:"ECA",terminal:!0,priority:400,transclude:"element",compile:function(c,g,i){return function(c,g,j){function k(){if(m&&(m.remove(),m=null),o&&(o.$destroy(),o=null),n){var a=n.data("$uiViewAnim");s.leave(n,function(){a.$$animLeave.resolve(),m=null}),m=n,n=null}}function l(h){var l,m=C(c,j,g,e),t=m&&a.$current&&a.$current.locals[m];if(h||t!==p){l=c.$new(),p=a.$current.locals[m],l.$emit("$viewContentLoading",m);var u=i(l,function(a){var e=f.defer(),h=f.defer(),i={$animEnter:e.promise,$animLeave:h.promise,$$animLeave:h};a.data("$uiViewAnim",i),s.enter(a,g,function(){e.resolve(),o&&o.$emit("$viewContentAnimationEnded"),(b.isDefined(r)&&!r||c.$eval(r))&&d(a)}),k()});n=u,o=l,o.$emit("$viewContentLoaded",m),o.$eval(q)}}var m,n,o,p,q=j.onload||"",r=j.autoscroll,s=h(j,c);g.inheritedData("$uiView");c.$on("$stateChangeSuccess",function(){l(!1)}),l(!0)}}};return l}function B(a,c,d,e){return{restrict:"ECA",priority:-400,compile:function(f){var g=f.html();return f.empty?f.empty():f[0].innerHTML=null,function(f,h,i){var j=d.$current,k=C(f,i,h,e),l=j&&j.locals[k];if(!l)return h.html(g),void a(h.contents())(f);h.data("$uiView",{name:k,state:l.$$state}),h.html(l.$template?l.$template:g);var m=b.extend({},l);f[l.$$resolveAs]=m;var n=a(h.contents());if(l.$$controller){l.$scope=f,l.$element=h;var o=c(l.$$controller,l);l.$$controllerAs&&(f[l.$$controllerAs]=o,f[l.$$controllerAs][l.$$resolveAs]=m),O(o.$onInit)&&o.$onInit(),h.data("$ngControllerController",o),h.children().data("$ngControllerController",o)}n(f)}}}}function C(a,b,c,d){var e=d(b.uiView||b.name||"")(a),f=c.inheritedData("$uiView");return e.indexOf("@")>=0?e:e+"@"+(f?f.state.name:"")}function D(a,b){var c,d=a.match(/^\s*({[^}]*})\s*$/);if(d&&(a=b+"("+d[1]+")"),c=a.replace(/\n/g," ").match(/^([^(]+?)\s*(\((.*)\))?$/),!c||4!==c.length)throw new Error("Invalid state ref '"+a+"'");return{state:c[1],paramExpr:c[3]||null}}function E(a){var b=a.parent().inheritedData("$uiView");if(b&&b.state&&b.state.name)return b.state}function F(a){var b="[object SVGAnimatedString]"===Object.prototype.toString.call(a.prop("href")),c="FORM"===a[0].nodeName;return{attr:c?"action":b?"xlink:href":"href",isAnchor:"A"===a.prop("tagName").toUpperCase(),clickable:!c}}function G(a,b,c,d,e){return function(f){var g=f.which||f.button,h=e();if(!(g>1||f.ctrlKey||f.metaKey||f.shiftKey||a.attr("target"))){var i=c(function(){b.go(h.state,h.params,h.options)});f.preventDefault();var j=d.isAnchor&&!h.href?1:0;f.preventDefault=function(){j--<=0&&c.cancel(i)}}}}function H(a,b){return{relative:E(a)||b.$current,inherit:!0}}function I(a,c){return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(d,e,f,g){var h,i=D(f.uiSref,a.current.name),j={state:i.state,href:null,params:null},k=F(e),l=g[1]||g[0],m=null;j.options=T(H(e,a),f.uiSrefOpts?d.$eval(f.uiSrefOpts):{});var n=function(c){c&&(j.params=b.copy(c)),j.href=a.href(i.state,j.params,j.options),m&&m(),l&&(m=l.$$addStateInfo(i.state,j.params)),null!==j.href&&f.$set(k.attr,j.href)};i.paramExpr&&(d.$watch(i.paramExpr,function(a){a!==j.params&&n(a)},!0),j.params=b.copy(d.$eval(i.paramExpr))),n(),k.clickable&&(h=G(e,a,c,k,function(){return j}),e[e.on?"on":"bind"]("click",h),d.$on("$destroy",function(){e[e.off?"off":"unbind"]("click",h)}))}}}function J(a,b){return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(c,d,e,f){function g(b){m.state=b[0],m.params=b[1],m.options=b[2],m.href=a.href(m.state,m.params,m.options),n&&n(),j&&(n=j.$$addStateInfo(m.state,m.params)),m.href&&e.$set(i.attr,m.href)}var h,i=F(d),j=f[1]||f[0],k=[e.uiState,e.uiStateParams||null,e.uiStateOpts||null],l="["+k.map(function(a){return a||"null"}).join(", ")+"]",m={state:null,params:null,options:null,href:null},n=null;c.$watch(l,g,!0),g(c.$eval(l)),i.clickable&&(h=G(d,a,b,i,function(){return m}),d[d.on?"on":"bind"]("click",h),c.$on("$destroy",function(){d[d.off?"off":"unbind"]("click",h)}))}}}function K(a,b,c){return{restrict:"A",controller:["$scope","$element","$attrs","$timeout",function(b,d,e,f){function g(b,c,e){var f=a.get(b,E(d)),g=h(b,c),i={state:f||{name:b},params:c,hash:g};return p.push(i),q[g]=e,function(){var a=p.indexOf(i);a!==-1&&p.splice(a,1)}}function h(a,c){if(!P(a))throw new Error("state should be a string");return Q(c)?a+V(c):(c=b.$eval(c),Q(c)?a+V(c):a)}function i(){for(var a=0;a0)){var c=g(a,b,o);return i(),c}},b.$on("$stateChangeSuccess",i),i()}]}}function L(a){var b=function(b,c){return a.is(b,c)};return b.$stateful=!0,b}function M(a){var b=function(b,c,d){return a.includes(b,c,d)};return b.$stateful=!0,b}var N=b.isDefined,O=b.isFunction,P=b.isString,Q=b.isObject,R=b.isArray,S=b.forEach,T=b.extend,U=b.copy,V=b.toJson;b.module("ui.router.util",["ng"]),b.module("ui.router.router",["ui.router.util"]),b.module("ui.router.state",["ui.router.router","ui.router.util"]),b.module("ui.router",["ui.router.state"]),b.module("ui.router.compat",["ui.router"]),q.$inject=["$q","$injector"],b.module("ui.router.util").service("$resolve",q),b.module("ui.router.util").provider("$templateFactory",r);var W;t.prototype.concat=function(a,b){var c={caseInsensitive:W.caseInsensitive(),strict:W.strictMode(),squash:W.defaultSquashPolicy()};return new t(this.sourcePath+a+this.sourceSearch,T(c,b),this)},t.prototype.toString=function(){return this.source},t.prototype.exec=function(a,b){function c(a){function b(a){return a.split("").reverse().join("")}function c(a){return a.replace(/\\-/g,"-")}var d=b(a).split(/-(?!\\)/),e=o(d,b);return o(e,c).reverse()}var d=this.regexp.exec(a);if(!d)return null;b=b||{};var e,f,g,h=this.parameters(),i=h.length,j=this.segments.length-1,k={};if(j!==d.length-1)throw new Error("Unbalanced capture group in route '"+this.source+"'");var l,m;for(e=0;e3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/vendor/assets/javascripts/ngAnimate.js b/vendor/assets/javascripts/ngAnimate.js new file mode 100644 index 00000000..64cbe3df --- /dev/null +++ b/vendor/assets/javascripts/ngAnimate.js @@ -0,0 +1,116 @@ +var app = angular.module('app', ['ngAnimate']); + +// myApp.animation('', function() { +// return { +// addClass : function(element, className, done) { +// if(className == 'ng-hide') { +// jQuery(element).animate({ +// opacity:0 +// }, done); +// } +// else { +// done(); +// } +// }, +// removeClass : function(element, className, done) { +// if(className == 'ng-hide') { +// element.css('opacity',0); + +// /* remove it early so you can animate on it since +// it is not possible using element.css() to set +// a style using !important */ +// element.removeClass('ng-hide'); +// jQuery(element).animate({ +// opacity:1 +// }, done); +// } +// else { +// done(); +// } +// } +// }; +// }); + + +function AppController ($scope, $rootScope, $http, $timeout) { + + // grid(0), list (1) + $scope.layoutMode = 0; + $scope.list = []; + $scope.currentAnimation; + $scope.isShow = true; + $scope.animations = ["toggle", + "spin-toggle", + "scale-fade", + "scale-fade-in", + "bouncy-scale-in", + "flip-in", + "slide-left", + "slide-right", + "slide-top", + "slide-down", + "bouncy-slide-left", + "bouncy-slide-right", + "bouncy-slide-top", + "bouncy-slide-down", + "rotate-in"]; + + $scope.addItem = function (animation) { + $scope.animation = animation; + for (var i = 0; i < 6; i++) { + $timeout(function () { + $scope.list.push({ title : "item" }); + }, 100 * i); + }; + } + + $scope.removeItem = function (item) { + var index = $scope.list.indexOf(item); + $scope.list.remove(index); + } + + $scope.cleanList = function () { + for (var i = 0; i < $scope.list.length; i++) { + $timeout(function () { + $scope.list.pop(); + }, 100 * i); + }; + } + + // Play all animation, it will auto clean item list. + $scope.autoPlayAnimation = function (index) { + var animation = $scope.animations[index]; + if (animation) { + $scope.currentAnimation = animation; + $scope.addItem(animation); + $timeout(function () { + $scope.cleanList(); + }, 1000); + $timeout(function () { + $scope.autoPlayAnimation(++index); + }, 2000); + } + else { + $scope.currentAnimation = undefined; + } + } + + $scope.switchGridMode = function () { + $scope.layoutMode = 0; + } + + $scope.switchListMode = function () { + $scope.layoutMode = 1; + } + + $scope.toggle = function () { + $scope.isShow = !$scope.isShow; + } +} + + +Array.prototype.remove = function(from, to) { + var rest = this.slice((to || from) + 1 || this.length); + this.length = from < 0 ? this.length + from : from; + return this.push.apply(this, rest); +}; \ No newline at end of file diff --git a/vendor/assets/javascripts/restangular.js b/vendor/assets/javascripts/restangular.js new file mode 100644 index 00000000..dd2e369e --- /dev/null +++ b/vendor/assets/javascripts/restangular.js @@ -0,0 +1,1355 @@ +/** + * Restful Resources service for AngularJS apps + * @version v1.5.2 - 2016-02-08 * @link https://github.com/mgonto/restangular + * @author Martin Gontovnikas + * @license MIT License, http://www.opensource.org/licenses/MIT + */(function() { + +var restangular = angular.module('restangular', []); + +restangular.provider('Restangular', function() { + // Configuration + var Configurer = {}; + Configurer.init = function(object, config) { + object.configuration = config; + + /** + * Those are HTTP safe methods for which there is no need to pass any data with the request. + */ + var safeMethods= ['get', 'head', 'options', 'trace', 'getlist']; + config.isSafe = function(operation) { + return _.includes(safeMethods, operation.toLowerCase()); + }; + + var absolutePattern = /^https?:\/\//i; + config.isAbsoluteUrl = function(string) { + return _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ? + string && absolutePattern.test(string) : + config.absoluteUrl; + }; + + config.absoluteUrl = _.isUndefined(config.absoluteUrl) ? true : config.absoluteUrl; + object.setSelfLinkAbsoluteUrl = function(value) { + config.absoluteUrl = value; + }; + /** + * This is the BaseURL to be used with Restangular + */ + config.baseUrl = _.isUndefined(config.baseUrl) ? '' : config.baseUrl; + object.setBaseUrl = function(newBaseUrl) { + config.baseUrl = /\/$/.test(newBaseUrl) ? + newBaseUrl.substring(0, newBaseUrl.length-1) : + newBaseUrl; + return this; + }; + + /** + * Sets the extra fields to keep from the parents + */ + config.extraFields = config.extraFields || []; + object.setExtraFields = function(newExtraFields) { + config.extraFields = newExtraFields; + return this; + }; + + /** + * Some default $http parameter to be used in EVERY call + **/ + config.defaultHttpFields = config.defaultHttpFields || {}; + object.setDefaultHttpFields = function(values) { + config.defaultHttpFields = values; + return this; + }; + + config.withHttpValues = function(httpLocalConfig, obj) { + return _.defaults(obj, httpLocalConfig, config.defaultHttpFields); + }; + + config.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds; + object.setEncodeIds = function(encode) { + config.encodeIds = encode; + }; + + config.defaultRequestParams = config.defaultRequestParams || { + get: {}, + post: {}, + put: {}, + remove: {}, + common: {} + }; + + object.setDefaultRequestParams = function(param1, param2) { + var methods = [], + params = param2 || param1; + if (!_.isUndefined(param2)) { + if (_.isArray(param1)) { + methods = param1; + } else { + methods.push(param1); + } + } else { + methods.push('common'); + } + + _.each(methods, function (method) { + config.defaultRequestParams[method] = params; + }); + return this; + }; + + object.requestParams = config.defaultRequestParams; + + config.defaultHeaders = config.defaultHeaders || {}; + object.setDefaultHeaders = function(headers) { + config.defaultHeaders = headers; + object.defaultHeaders = config.defaultHeaders; + return this; + }; + + object.defaultHeaders = config.defaultHeaders; + + /** + * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override + **/ + config.methodOverriders = config.methodOverriders || []; + object.setMethodOverriders = function(values) { + var overriders = _.extend([], values); + if (config.isOverridenMethod('delete', overriders)) { + overriders.push('remove'); + } + config.methodOverriders = overriders; + return this; + }; + + config.jsonp = _.isUndefined(config.jsonp) ? false : config.jsonp; + object.setJsonp = function(active) { + config.jsonp = active; + }; + + config.isOverridenMethod = function(method, values) { + var search = values || config.methodOverriders; + return !_.isUndefined(_.find(search, function(one) { + return one.toLowerCase() === method.toLowerCase(); + })); + }; + + /** + * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams + **/ + config.urlCreator = config.urlCreator || 'path'; + object.setUrlCreator = function(name) { + if (!_.has(config.urlCreatorFactory, name)) { + throw new Error('URL Path selected isn\'t valid'); + } + + config.urlCreator = name; + return this; + }; + + /** + * You can set the restangular fields here. The 3 required fields for Restangular are: + * + * id: Id of the element + * route: name of the route of this element + * parentResource: the reference to the parent resource + * + * All of this fields except for id, are handled (and created) by Restangular. By default, + * the field values will be id, route and parentResource respectively + */ + config.restangularFields = config.restangularFields || { + id: 'id', + route: 'route', + parentResource: 'parentResource', + restangularCollection: 'restangularCollection', + cannonicalId: '__cannonicalId', + etag: 'restangularEtag', + selfLink: 'href', + get: 'get', + getList: 'getList', + put: 'put', + post: 'post', + remove: 'remove', + head: 'head', + trace: 'trace', + options: 'options', + patch: 'patch', + getRestangularUrl: 'getRestangularUrl', + getRequestedUrl: 'getRequestedUrl', + putElement: 'putElement', + addRestangularMethod: 'addRestangularMethod', + getParentList: 'getParentList', + clone: 'clone', + ids: 'ids', + httpConfig: '_$httpConfig', + reqParams: 'reqParams', + one: 'one', + all: 'all', + several: 'several', + oneUrl: 'oneUrl', + allUrl: 'allUrl', + customPUT: 'customPUT', + customPOST: 'customPOST', + customDELETE: 'customDELETE', + customGET: 'customGET', + customGETLIST: 'customGETLIST', + customOperation: 'customOperation', + doPUT: 'doPUT', + doPOST: 'doPOST', + doDELETE: 'doDELETE', + doGET: 'doGET', + doGETLIST: 'doGETLIST', + fromServer: 'fromServer', + withConfig: 'withConfig', + withHttpConfig: 'withHttpConfig', + singleOne: 'singleOne', + plain: 'plain', + save: 'save', + restangularized: 'restangularized' + }; + object.setRestangularFields = function(resFields) { + config.restangularFields = + _.extend(config.restangularFields, resFields); + return this; + }; + + config.isRestangularized = function(obj) { + return !!obj[config.restangularFields.restangularized]; + }; + + config.setFieldToElem = function(field, elem, value) { + var properties = field.split('.'); + var idValue = elem; + _.each(_.initial(properties), function(prop) { + idValue[prop] = {}; + idValue = idValue[prop]; + }); + idValue[_.last(properties)] = value; + return this; + }; + + config.getFieldFromElem = function(field, elem) { + var properties = field.split('.'); + var idValue = elem; + _.each(properties, function(prop) { + if (idValue) { + idValue = idValue[prop]; + } + }); + return angular.copy(idValue); + }; + + config.setIdToElem = function(elem, id /*, route */) { + config.setFieldToElem(config.restangularFields.id, elem, id); + return this; + }; + + config.getIdFromElem = function(elem) { + return config.getFieldFromElem(config.restangularFields.id, elem); + }; + + config.isValidId = function(elemId) { + return '' !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId); + }; + + config.setUrlToElem = function(elem, url /*, route */) { + config.setFieldToElem(config.restangularFields.selfLink, elem, url); + return this; + }; + + config.getUrlFromElem = function(elem) { + return config.getFieldFromElem(config.restangularFields.selfLink, elem); + }; + + config.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId; + object.setUseCannonicalId = function(value) { + config.useCannonicalId = value; + return this; + }; + + config.getCannonicalIdFromElem = function(elem) { + var cannonicalId = elem[config.restangularFields.cannonicalId]; + var actualId = config.isValidId(cannonicalId) ? cannonicalId : config.getIdFromElem(elem); + return actualId; + }; + + /** + * Sets the Response parser. This is used in case your response isn't directly the data. + * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}} + * you can extract this data which is the one that needs wrapping + * + * The ResponseExtractor is a function that receives the response and the method executed. + */ + + config.responseInterceptors = config.responseInterceptors || []; + + config.defaultResponseInterceptor = function(data /*, operation, what, url, response, deferred */) { + return data; + }; + + config.responseExtractor = function(data, operation, what, url, response, deferred) { + var interceptors = angular.copy(config.responseInterceptors); + interceptors.push(config.defaultResponseInterceptor); + var theData = data; + _.each(interceptors, function(interceptor) { + theData = interceptor(theData, operation, + what, url, response, deferred); + }); + return theData; + }; + + object.addResponseInterceptor = function(extractor) { + config.responseInterceptors.push(extractor); + return this; + }; + + config.errorInterceptors = config.errorInterceptors || []; + object.addErrorInterceptor = function(interceptor) { + config.errorInterceptors.push(interceptor); + return this; + }; + + object.setResponseInterceptor = object.addResponseInterceptor; + object.setResponseExtractor = object.addResponseInterceptor; + object.setErrorInterceptor = object.addErrorInterceptor; + + /** + * Response interceptor is called just before resolving promises. + */ + + + /** + * Request interceptor is called before sending an object to the server. + */ + config.requestInterceptors = config.requestInterceptors || []; + + config.defaultInterceptor = function(element, operation, path, url, headers, params, httpConfig) { + return { + element: element, + headers: headers, + params: params, + httpConfig: httpConfig + }; + }; + + config.fullRequestInterceptor = function(element, operation, path, url, headers, params, httpConfig) { + var interceptors = angular.copy(config.requestInterceptors); + var defaultRequest = config.defaultInterceptor(element, operation, path, url, headers, params, httpConfig); + return _.reduce(interceptors, function(request, interceptor) { + return _.extend(request, interceptor(request.element, operation, + path, url, request.headers, request.params, request.httpConfig)); + }, defaultRequest); + }; + + object.addRequestInterceptor = function(interceptor) { + config.requestInterceptors.push(function(elem, operation, path, url, headers, params, httpConfig) { + return { + headers: headers, + params: params, + element: interceptor(elem, operation, path, url), + httpConfig: httpConfig + }; + }); + return this; + }; + + object.setRequestInterceptor = object.addRequestInterceptor; + + object.addFullRequestInterceptor = function(interceptor) { + config.requestInterceptors.push(interceptor); + return this; + }; + + object.setFullRequestInterceptor = object.addFullRequestInterceptor; + + config.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function(elem) { + return elem; + }; + object.setOnBeforeElemRestangularized = function(post) { + config.onBeforeElemRestangularized = post; + return this; + }; + + object.setRestangularizePromiseInterceptor = function(interceptor) { + config.restangularizePromiseInterceptor = interceptor; + return this; + }; + + /** + * This method is called after an element has been "Restangularized". + * + * It receives the element, a boolean indicating if it's an element or a collection + * and the name of the model + * + */ + config.onElemRestangularized = config.onElemRestangularized || function(elem) { + return elem; + }; + object.setOnElemRestangularized = function(post) { + config.onElemRestangularized = post; + return this; + }; + + config.shouldSaveParent = config.shouldSaveParent || function() { + return true; + }; + object.setParentless = function(values) { + if (_.isArray(values)) { + config.shouldSaveParent = function(route) { + return !_.includes(values, route); + }; + } else if (_.isBoolean(values)) { + config.shouldSaveParent = function() { + return !values; + }; + } + return this; + }; + + /** + * This lets you set a suffix to every request. + * + * For example, if your api requires that for JSon requests you do /users/123.json, you can set that + * in here. + * + * + * By default, the suffix is null + */ + config.suffix = _.isUndefined(config.suffix) ? null : config.suffix; + object.setRequestSuffix = function(newSuffix) { + config.suffix = newSuffix; + return this; + }; + + /** + * Add element transformers for certain routes. + */ + config.transformers = config.transformers || {}; + object.addElementTransformer = function(type, secondArg, thirdArg) { + var isCollection = null; + var transformer = null; + if (arguments.length === 2) { + transformer = secondArg; + } else { + transformer = thirdArg; + isCollection = secondArg; + } + + var typeTransformers = config.transformers[type]; + if (!typeTransformers) { + typeTransformers = config.transformers[type] = []; + } + + typeTransformers.push(function(coll, elem) { + if (_.isNull(isCollection) || (coll === isCollection)) { + return transformer(elem); + } + return elem; + }); + + return object; + }; + + object.extendCollection = function(route, fn) { + return object.addElementTransformer(route, true, fn); + }; + + object.extendModel = function(route, fn) { + return object.addElementTransformer(route, false, fn); + }; + + config.transformElem = function(elem, isCollection, route, Restangular, force) { + if (!force && !config.transformLocalElements && !elem[config.restangularFields.fromServer]) { + return elem; + } + var typeTransformers = config.transformers[route]; + var changedElem = elem; + if (typeTransformers) { + _.each(typeTransformers, function(transformer) { + changedElem = transformer(isCollection, changedElem); + }); + } + return config.onElemRestangularized(changedElem, isCollection, route, Restangular); + }; + + config.transformLocalElements = _.isUndefined(config.transformLocalElements) ? + false : + config.transformLocalElements; + + object.setTransformOnlyServerElements = function(active) { + config.transformLocalElements = !active; + }; + + config.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse; + object.setFullResponse = function(full) { + config.fullResponse = full; + return this; + }; + + + //Internal values and functions + config.urlCreatorFactory = {}; + + /** + * Base URL Creator. Base prototype for everything related to it + **/ + + var BaseCreator = function() { + }; + + BaseCreator.prototype.setConfig = function(config) { + this.config = config; + return this; + }; + + BaseCreator.prototype.parentsArray = function(current) { + var parents = []; + while(current) { + parents.push(current); + current = current[this.config.restangularFields.parentResource]; + } + return parents.reverse(); + }; + + function RestangularResource(config, $http, url, configurer) { + var resource = {}; + _.each(_.keys(configurer), function(key) { + var value = configurer[key]; + + // Add default parameters + value.params = _.extend({}, value.params, config.defaultRequestParams[value.method.toLowerCase()]); + // We don't want the ? if no params are there + if (_.isEmpty(value.params)) { + delete value.params; + } + + if (config.isSafe(value.method)) { + + resource[key] = function() { + return $http(_.extend(value, { + url: url + })); + }; + + } else { + + resource[key] = function(data) { + return $http(_.extend(value, { + url: url, + data: data + })); + }; + + } + }); + + return resource; + } + + BaseCreator.prototype.resource = function(current, $http, localHttpConfig, callHeaders, callParams, what, etag,operation) { + + var params = _.defaults(callParams || {}, this.config.defaultRequestParams.common); + var headers = _.defaults(callHeaders || {}, this.config.defaultHeaders); + + if (etag) { + if (!config.isSafe(operation)) { + headers['If-Match'] = etag; + } else { + headers['If-None-Match'] = etag; + } + } + + var url = this.base(current); + + if (what) { + var add = ''; + if (!/\/$/.test(url)) { + add += '/'; + } + add += what; + url += add; + } + + if (this.config.suffix && + url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1 && + !this.config.getUrlFromElem(current)) { + url += this.config.suffix; + } + + current[this.config.restangularFields.httpConfig] = undefined; + + return RestangularResource(this.config, $http, url, { + getList: this.config.withHttpValues(localHttpConfig, + {method: 'GET', + params: params, + headers: headers}), + + get: this.config.withHttpValues(localHttpConfig, + {method: 'GET', + params: params, + headers: headers}), + + jsonp: this.config.withHttpValues(localHttpConfig, + {method: 'jsonp', + params: params, + headers: headers}), + + put: this.config.withHttpValues(localHttpConfig, + {method: 'PUT', + params: params, + headers: headers}), + + post: this.config.withHttpValues(localHttpConfig, + {method: 'POST', + params: params, + headers: headers}), + + remove: this.config.withHttpValues(localHttpConfig, + {method: 'DELETE', + params: params, + headers: headers}), + + head: this.config.withHttpValues(localHttpConfig, + {method: 'HEAD', + params: params, + headers: headers}), + + trace: this.config.withHttpValues(localHttpConfig, + {method: 'TRACE', + params: params, + headers: headers}), + + options: this.config.withHttpValues(localHttpConfig, + {method: 'OPTIONS', + params: params, + headers: headers}), + + patch: this.config.withHttpValues(localHttpConfig, + {method: 'PATCH', + params: params, + headers: headers}) + }); + }; + + /** + * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API. + * This means that if you have an Account that then has a set of Buildings, a URL to a building + * would be /accounts/123/buildings/456 + **/ + var Path = function() { + }; + + Path.prototype = new BaseCreator(); + + Path.prototype.normalizeUrl = function (url){ + var parts = /(http[s]?:\/\/)?(.*)?/.exec(url); + parts[2] = parts[2].replace(/[\\\/]+/g, '/'); + return (typeof parts[1] !== 'undefined')? parts[1] + parts[2] : parts[2]; + }; + + Path.prototype.base = function(current) { + var __this = this; + return _.reduce(this.parentsArray(current), function(acum, elem) { + var elemUrl; + var elemSelfLink = __this.config.getUrlFromElem(elem); + if (elemSelfLink) { + if (__this.config.isAbsoluteUrl(elemSelfLink)) { + return elemSelfLink; + } else { + elemUrl = elemSelfLink; + } + } else { + elemUrl = elem[__this.config.restangularFields.route]; + + if (elem[__this.config.restangularFields.restangularCollection]) { + var ids = elem[__this.config.restangularFields.ids]; + if (ids) { + elemUrl += '/' + ids.join(','); + } + } else { + var elemId; + if (__this.config.useCannonicalId) { + elemId = __this.config.getCannonicalIdFromElem(elem); + } else { + elemId = __this.config.getIdFromElem(elem); + } + + if (config.isValidId(elemId) && !elem.singleOne) { + elemUrl += '/' + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId); + } + } + } + acum = acum.replace(/\/$/, '') + '/' + elemUrl; + return __this.normalizeUrl(acum); + + }, this.config.baseUrl); + }; + + + + Path.prototype.fetchUrl = function(current, what) { + var baseUrl = this.base(current); + if (what) { + baseUrl += '/' + what; + } + return baseUrl; + }; + + Path.prototype.fetchRequestedUrl = function(current, what) { + var url = this.fetchUrl(current, what); + var params = current[config.restangularFields.reqParams]; + + // From here on and until the end of fetchRequestedUrl, + // the code has been kindly borrowed from angular.js + // The reason for such code bloating is coherence: + // If the user were to use this for cache management, the + // serialization of parameters would need to be identical + // to the one done by angular for cache keys to match. + function sortedKeys(obj) { + var keys = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys.push(key); + } + } + return keys.sort(); + } + + function forEachSorted(obj, iterator, context) { + var keys = sortedKeys(obj); + for ( var i = 0; i < keys.length; i++) { + iterator.call(context, obj[keys[i]], keys[i]); + } + return keys; + } + + function encodeUriQuery(val, pctEncodeSpaces) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + } + + if (!params) { return url + (this.config.suffix || ''); } + + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || value === undefined) { return; } + if (!angular.isArray(value)) { value = [value]; } + + angular.forEach(value, function(v) { + if (angular.isObject(v)) { + v = angular.toJson(v); + } + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); + }); + }); + + return url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); + }; + + config.urlCreatorFactory.path = Path; + }; + + var globalConfiguration = {}; + + Configurer.init(this, globalConfiguration); + + + + this.$get = ['$http', '$q', function($http, $q) { + + function createServiceForConfiguration(config) { + var service = {}; + + var urlHandler = new config.urlCreatorFactory[config.urlCreator](); + urlHandler.setConfig(config); + + function restangularizeBase(parent, elem, route, reqParams, fromServer) { + elem[config.restangularFields.route] = route; + elem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem); + elem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem); + elem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem); + elem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem); + elem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams; + elem[config.restangularFields.withHttpConfig] = _.bind(withHttpConfig, elem); + elem[config.restangularFields.plain] = _.bind(stripRestangular, elem, elem); + + // Tag element as restangularized + elem[config.restangularFields.restangularized] = true; + + // RequestLess connection + elem[config.restangularFields.one] = _.bind(one, elem, elem); + elem[config.restangularFields.all] = _.bind(all, elem, elem); + elem[config.restangularFields.several] = _.bind(several, elem, elem); + elem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem); + elem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem); + + elem[config.restangularFields.fromServer] = !!fromServer; + + if (parent && config.shouldSaveParent(route)) { + var parentId = config.getIdFromElem(parent); + var parentUrl = config.getUrlFromElem(parent); + + var restangularFieldsForParent = _.union( + _.values( _.pick(config.restangularFields, ['route', 'singleOne', 'parentResource']) ), + config.extraFields + ); + var parentResource = _.pick(parent, restangularFieldsForParent); + + if (config.isValidId(parentId)) { + config.setIdToElem(parentResource, parentId, route); + } + if (config.isValidId(parentUrl)) { + config.setUrlToElem(parentResource, parentUrl, route); + } + + elem[config.restangularFields.parentResource] = parentResource; + } else { + elem[config.restangularFields.parentResource] = null; + } + return elem; + } + + function one(parent, route, id, singleOne) { + var error; + if (_.isNumber(route) || _.isNumber(parent)) { + error = 'You\'re creating a Restangular entity with the number '; + error += 'instead of the route or the parent. For example, you can\'t call .one(12).'; + throw new Error(error); + } + if (_.isUndefined(route)) { + error = 'You\'re creating a Restangular entity either without the path. '; + error += 'For example you can\'t call .one(). Please check if your arguments are valid.'; + throw new Error(error); + } + var elem = {}; + config.setIdToElem(elem, id, route); + config.setFieldToElem(config.restangularFields.singleOne, elem, singleOne); + return restangularizeElem(parent, elem , route, false); + } + + + function all(parent, route) { + return restangularizeCollection(parent, [] , route, false); + } + + function several(parent, route /*, ids */) { + var collection = []; + collection[config.restangularFields.ids] = Array.prototype.splice.call(arguments, 2); + return restangularizeCollection(parent, collection , route, false); + } + + function oneUrl(parent, route, url) { + if (!route) { + throw new Error('Route is mandatory when creating new Restangular objects.'); + } + var elem = {}; + config.setUrlToElem(elem, url, route); + return restangularizeElem(parent, elem , route, false); + } + + + function allUrl(parent, route, url) { + if (!route) { + throw new Error('Route is mandatory when creating new Restangular objects.'); + } + var elem = {}; + config.setUrlToElem(elem, url, route); + return restangularizeCollection(parent, elem , route, false); + } + // Promises + function restangularizePromise(promise, isCollection, valueToFill) { + promise.call = _.bind(promiseCall, promise); + promise.get = _.bind(promiseGet, promise); + promise[config.restangularFields.restangularCollection] = isCollection; + if (isCollection) { + promise.push = _.bind(promiseCall, promise, 'push'); + } + promise.$object = valueToFill; + if (config.restangularizePromiseInterceptor) { + config.restangularizePromiseInterceptor(promise); + } + return promise; + } + + function promiseCall(method) { + var deferred = $q.defer(); + var callArgs = arguments; + var filledValue = {}; + this.then(function(val) { + var params = Array.prototype.slice.call(callArgs, 1); + var func = val[method]; + func.apply(val, params); + filledValue = val; + deferred.resolve(val); + }); + return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); + } + + function promiseGet(what) { + var deferred = $q.defer(); + var filledValue = {}; + this.then(function(val) { + filledValue = val[what]; + deferred.resolve(filledValue); + }); + return restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue); + } + + function resolvePromise(deferred, response, data, filledValue) { + _.extend(filledValue, data); + + // Trigger the full response interceptor. + if (config.fullResponse) { + return deferred.resolve(_.extend(response, { + data: data + })); + } else { + deferred.resolve(data); + } + } + + + // Elements + function stripRestangular(elem) { + if (_.isArray(elem)) { + var array = []; + _.each(elem, function(value) { + array.push(config.isRestangularized(value) ? stripRestangular(value) : value); + }); + return array; + } else { + return _.omit(elem, _.values(_.omit(config.restangularFields, 'id'))); + } + } + + function addCustomOperation(elem) { + elem[config.restangularFields.customOperation] = _.bind(customFunction, elem); + _.each(['put', 'post', 'get', 'delete'], function(oper) { + _.each(['do', 'custom'], function(alias) { + var callOperation = oper === 'delete' ? 'remove' : oper; + var name = alias + oper.toUpperCase(); + var callFunction; + + if (callOperation !== 'put' && callOperation !== 'post') { + callFunction = customFunction; + } else { + callFunction = function(operation, elem, path, params, headers) { + return _.bind(customFunction, this)(operation, path, params, headers, elem); + }; + } + elem[name] = _.bind(callFunction, elem, callOperation); + }); + }); + elem[config.restangularFields.customGETLIST] = _.bind(fetchFunction, elem); + elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST]; + } + + function copyRestangularizedElement(fromElement, toElement) { + var copiedElement = angular.copy(fromElement, toElement); + return restangularizeElem(copiedElement[config.restangularFields.parentResource], + copiedElement, copiedElement[config.restangularFields.route], true); + } + + function restangularizeElem(parent, element, route, fromServer, collection, reqParams) { + var elem = config.onBeforeElemRestangularized(element, false, route); + + var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); + + if (config.useCannonicalId) { + localElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem); + } + + if (collection) { + localElem[config.restangularFields.getParentList] = function() { + return collection; + }; + } + + localElem[config.restangularFields.restangularCollection] = false; + localElem[config.restangularFields.get] = _.bind(getFunction, localElem); + localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem); + localElem[config.restangularFields.put] = _.bind(putFunction, localElem); + localElem[config.restangularFields.post] = _.bind(postFunction, localElem); + localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); + localElem[config.restangularFields.head] = _.bind(headFunction, localElem); + localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); + localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); + localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); + localElem[config.restangularFields.save] = _.bind(save, localElem); + + addCustomOperation(localElem); + return config.transformElem(localElem, false, route, service, true); + } + + function restangularizeCollection(parent, element, route, fromServer, reqParams) { + var elem = config.onBeforeElemRestangularized(element, true, route); + + var localElem = restangularizeBase(parent, elem, route, reqParams, fromServer); + localElem[config.restangularFields.restangularCollection] = true; + localElem[config.restangularFields.post] = _.bind(postFunction, localElem, null); + localElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem); + localElem[config.restangularFields.head] = _.bind(headFunction, localElem); + localElem[config.restangularFields.trace] = _.bind(traceFunction, localElem); + localElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem); + localElem[config.restangularFields.options] = _.bind(optionsFunction, localElem); + localElem[config.restangularFields.patch] = _.bind(patchFunction, localElem); + localElem[config.restangularFields.get] = _.bind(getById, localElem); + localElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem, null); + + addCustomOperation(localElem); + return config.transformElem(localElem, true, route, service, true); + } + + function restangularizeCollectionAndElements(parent, element, route) { + var collection = restangularizeCollection(parent, element, route, false); + _.each(collection, function(elem) { + restangularizeElem(parent, elem, route, false); + }); + return collection; + } + + function getById(id, reqParams, headers){ + return this.customGET(id.toString(), reqParams, headers); + } + + function putElementFunction(idx, params, headers) { + var __this = this; + var elemToPut = this[idx]; + var deferred = $q.defer(); + var filledArray = []; + filledArray = config.transformElem(filledArray, true, elemToPut[config.restangularFields.route], service); + elemToPut.put(params, headers).then(function(serverElem) { + var newArray = copyRestangularizedElement(__this); + newArray[idx] = serverElem; + filledArray = newArray; + deferred.resolve(newArray); + }, function(response) { + deferred.reject(response); + }); + + return restangularizePromise(deferred.promise, true, filledArray); + } + + function parseResponse(resData, operation, route, fetchUrl, response, deferred) { + var data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred); + var etag = response.headers('ETag'); + if (data && etag) { + data[config.restangularFields.etag] = etag; + } + return data; + } + + + function fetchFunction(what, reqParams, headers) { + var __this = this; + var deferred = $q.defer(); + var operation = 'getList'; + var url = urlHandler.fetchUrl(this, what); + var whatFetched = what || __this[config.restangularFields.route]; + + var request = config.fullRequestInterceptor(null, operation, + whatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {}); + + var filledArray = []; + filledArray = config.transformElem(filledArray, true, whatFetched, service); + + var method = 'getList'; + + if (config.jsonp) { + method = 'jsonp'; + } + + var okCallback = function(response) { + var resData = response.data; + var fullParams = response.config.params; + var data = parseResponse(resData, operation, whatFetched, url, response, deferred); + + // support empty response for getList() calls (some APIs respond with 204 and empty body) + if (_.isUndefined(data) || '' === data) { + data = []; + } + if (!_.isArray(data)) { + throw new Error('Response for getList SHOULD be an array and not an object or something else'); + } + var processedData = _.map(data, function(elem) { + if (!__this[config.restangularFields.restangularCollection]) { + return restangularizeElem(__this, elem, what, true, data); + } else { + return restangularizeElem(__this[config.restangularFields.parentResource], + elem, __this[config.restangularFields.route], true, data); + } + }); + + processedData = _.extend(data, processedData); + + if (!__this[config.restangularFields.restangularCollection]) { + resolvePromise( + deferred, + response, + restangularizeCollection( + __this, + processedData, + what, + true, + fullParams + ), + filledArray + ); + } else { + resolvePromise( + deferred, + response, + restangularizeCollection( + __this[config.restangularFields.parentResource], + processedData, + __this[config.restangularFields.route], + true, + fullParams + ), + filledArray + ); + } + }; + + urlHandler.resource(this, $http, request.httpConfig, request.headers, request.params, what, + this[config.restangularFields.etag], operation)[method]().then(okCallback, function error(response) { + if (response.status === 304 && __this[config.restangularFields.restangularCollection]) { + resolvePromise(deferred, response, __this, filledArray); + } else if ( _.every(config.errorInterceptors, function(cb) { return cb(response, deferred, okCallback) !== false; }) ) { + // triggered if no callback returns false + deferred.reject(response); + } + }); + + return restangularizePromise(deferred.promise, true, filledArray); + } + + function withHttpConfig(httpConfig) { + this[config.restangularFields.httpConfig] = httpConfig; + return this; + } + + function save(params, headers) { + if (this[config.restangularFields.fromServer]) { + return this[config.restangularFields.put](params, headers); + } else { + return _.bind(elemFunction, this)('post', undefined, params, undefined, headers); + } + } + + function elemFunction(operation, what, params, obj, headers) { + var __this = this; + var deferred = $q.defer(); + var resParams = params || {}; + var route = what || this[config.restangularFields.route]; + var fetchUrl = urlHandler.fetchUrl(this, what); + + var callObj = obj || this; + // fallback to etag on restangular object (since for custom methods we probably don't explicitly specify the etag field) + var etag = callObj[config.restangularFields.etag] || (operation !== 'post' ? this[config.restangularFields.etag] : null); + + if (_.isObject(callObj) && config.isRestangularized(callObj)) { + callObj = stripRestangular(callObj); + } + var request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl, + headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {}); + + var filledObject = {}; + filledObject = config.transformElem(filledObject, false, route, service); + + var okCallback = function(response) { + var resData = response.data; + var fullParams = response.config.params; + var elem = parseResponse(resData, operation, route, fetchUrl, response, deferred); + if (elem) { + var data; + if (operation === 'post' && !__this[config.restangularFields.restangularCollection]) { + data = restangularizeElem( + __this[config.restangularFields.parentResource], + elem, + route, + true, + null, + fullParams + ); + resolvePromise(deferred, response, data, filledObject); + } else { + data = restangularizeElem( + __this[config.restangularFields.parentResource], + elem, + __this[config.restangularFields.route], + true, + null, + fullParams + ); + + data[config.restangularFields.singleOne] = __this[config.restangularFields.singleOne]; + resolvePromise(deferred, response, data, filledObject); + } + + } else { + resolvePromise(deferred, response, undefined, filledObject); + } + }; + + var errorCallback = function(response) { + if (response.status === 304 && config.isSafe(operation)) { + resolvePromise(deferred, response, __this, filledObject); + } else if ( _.every(config.errorInterceptors, function(cb) { return cb(response, deferred, okCallback) !== false; }) ) { + // triggered if no callback returns false + deferred.reject(response); + } + }; + // Overriding HTTP Method + var callOperation = operation; + var callHeaders = _.extend({}, request.headers); + var isOverrideOperation = config.isOverridenMethod(operation); + if (isOverrideOperation) { + callOperation = 'post'; + callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation.toUpperCase()}); + } else if (config.jsonp && callOperation === 'get') { + callOperation = 'jsonp'; + } + + if (config.isSafe(operation)) { + if (isOverrideOperation) { + urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, + what, etag, callOperation)[callOperation]({}).then(okCallback, errorCallback); + } else { + urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, + what, etag, callOperation)[callOperation]().then(okCallback, errorCallback); + } + } else { + urlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params, + what, etag, callOperation)[callOperation](request.element).then(okCallback, errorCallback); + } + + return restangularizePromise(deferred.promise, false, filledObject); + } + + function getFunction(params, headers) { + return _.bind(elemFunction, this)('get', undefined, params, undefined, headers); + } + + function deleteFunction(params, headers) { + return _.bind(elemFunction, this)('remove', undefined, params, undefined, headers); + } + + function putFunction(params, headers) { + return _.bind(elemFunction, this)('put', undefined, params, undefined, headers); + } + + function postFunction(what, elem, params, headers) { + return _.bind(elemFunction, this)('post', what, params, elem, headers); + } + + function headFunction(params, headers) { + return _.bind(elemFunction, this)('head', undefined, params, undefined, headers); + } + + function traceFunction(params, headers) { + return _.bind(elemFunction, this)('trace', undefined, params, undefined, headers); + } + + function optionsFunction(params, headers) { + return _.bind(elemFunction, this)('options', undefined, params, undefined, headers); + } + + function patchFunction(elem, params, headers) { + return _.bind(elemFunction, this)('patch', undefined, params, elem, headers); + } + + function customFunction(operation, path, params, headers, elem) { + return _.bind(elemFunction, this)(operation, path, params, elem, headers); + } + + function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) { + var bindedFunction; + if (operation === 'getList') { + bindedFunction = _.bind(fetchFunction, this, path); + } else { + bindedFunction = _.bind(customFunction, this, operation, path); + } + + var createdFunction = function(params, headers, elem) { + var callParams = _.defaults({ + params: params, + headers: headers, + elem: elem + }, { + params: defaultParams, + headers: defaultHeaders, + elem: defaultElem + }); + return bindedFunction(callParams.params, callParams.headers, callParams.elem); + }; + + if (config.isSafe(operation)) { + this[name] = createdFunction; + } else { + this[name] = function(elem, params, headers) { + return createdFunction(params, headers, elem); + }; + } + } + + function withConfigurationFunction(configurer) { + var newConfig = angular.copy(_.omit(config, 'configuration')); + Configurer.init(newConfig, newConfig); + configurer(newConfig); + return createServiceForConfiguration(newConfig); + } + + function toService(route, parent) { + var knownCollectionMethods = _.values(config.restangularFields); + var serv = {}; + var collection = (parent || service).all(route); + serv.one = _.bind(one, (parent || service), parent, route); + serv.post = _.bind(collection.post, collection); + serv.getList = _.bind(collection.getList, collection); + + for (var prop in collection) { + if (collection.hasOwnProperty(prop) && _.isFunction(collection[prop]) && !_.includes(knownCollectionMethods, prop)) { + serv[prop] = _.bind(collection[prop], collection); + } + } + + return serv; + } + + + Configurer.init(service, config); + + service.copy = _.bind(copyRestangularizedElement, service); + + service.service = _.bind(toService, service); + + service.withConfig = _.bind(withConfigurationFunction, service); + + service.one = _.bind(one, service, null); + + service.all = _.bind(all, service, null); + + service.several = _.bind(several, service, null); + + service.oneUrl = _.bind(oneUrl, service, null); + + service.allUrl = _.bind(allUrl, service, null); + + service.stripRestangular = _.bind(stripRestangular, service); + + service.restangularizeElement = _.bind(restangularizeElem, service); + + service.restangularizeCollection = _.bind(restangularizeCollectionAndElements, service); + + return service; + } + + return createServiceForConfiguration(globalConfiguration); + }]; +}); + +})(); diff --git a/vendor/assets/javascripts/restangular.min.js b/vendor/assets/javascripts/restangular.min.js new file mode 100644 index 00000000..729f8aad --- /dev/null +++ b/vendor/assets/javascripts/restangular.min.js @@ -0,0 +1,6 @@ +/** + * Restful Resources service for AngularJS apps + * @version v1.6.1 - 2017-01-06 * @link https://github.com/mgonto/restangular + * @author Martin Gontovnikas + * @license MIT License, http://www.opensource.org/licenses/MIT + */!function(a,b){"function"==typeof define&&define.amd?define(["lodash","angular"],b):"object"==typeof module&&module.exports?module.exports=b(require("lodash"),require("angular")):b(a._,a.angular)}(this,function(a,b){var c=b.module("restangular",[]);return c.provider("Restangular",function(){var c={};c.init=function(c,d){function e(b,c,d,e){var f={};return a.each(a.keys(e),function(g){var h=e[g];h.params=a.extend({},h.params,b.defaultRequestParams[h.method.toLowerCase()]),a.isEmpty(h.params)&&delete h.params,b.isSafe(h.method)?f[g]=function(){return c(a.extend(h,{url:d}))}:f[g]=function(b){return c(a.extend(h,{url:d,data:b}))}}),f}c.configuration=d;var f=["get","head","options","trace","getlist"];d.isSafe=function(b){return a.includes(f,b.toLowerCase())};var g=/^https?:\/\//i;d.isAbsoluteUrl=function(b){return a.isUndefined(d.absoluteUrl)||a.isNull(d.absoluteUrl)?b&&g.test(b):d.absoluteUrl},d.absoluteUrl=!!a.isUndefined(d.absoluteUrl)||d.absoluteUrl,c.setSelfLinkAbsoluteUrl=function(a){d.absoluteUrl=a},d.baseUrl=a.isUndefined(d.baseUrl)?"":d.baseUrl,c.setBaseUrl=function(a){return d.baseUrl=/\/$/.test(a)?a.substring(0,a.length-1):a,this},d.extraFields=d.extraFields||[],c.setExtraFields=function(a){return d.extraFields=a,this},d.defaultHttpFields=d.defaultHttpFields||{},c.setDefaultHttpFields=function(a){return d.defaultHttpFields=a,this},d.plainByDefault=d.plainByDefault||!1,c.setPlainByDefault=function(a){return d.plainByDefault=a===!0,this},d.withHttpValues=function(b,c){return a.defaults(c,b,d.defaultHttpFields)},d.encodeIds=!!a.isUndefined(d.encodeIds)||d.encodeIds,c.setEncodeIds=function(a){d.encodeIds=a},d.defaultRequestParams=d.defaultRequestParams||{get:{},post:{},put:{},remove:{},common:{}},c.setDefaultRequestParams=function(b,c){var e=[],f=c||b;return a.isUndefined(c)?e.push("common"):a.isArray(b)?e=b:e.push(b),a.each(e,function(a){d.defaultRequestParams[a]=f}),this},c.requestParams=d.defaultRequestParams,d.defaultHeaders=d.defaultHeaders||{},c.setDefaultHeaders=function(a){return d.defaultHeaders=a,c.defaultHeaders=d.defaultHeaders,this},c.defaultHeaders=d.defaultHeaders,d.methodOverriders=d.methodOverriders||[],c.setMethodOverriders=function(b){var c=a.extend([],b);return d.isOverridenMethod("delete",c)&&c.push("remove"),d.methodOverriders=c,this},d.jsonp=!a.isUndefined(d.jsonp)&&d.jsonp,c.setJsonp=function(a){d.jsonp=a},d.isOverridenMethod=function(b,c){var e=c||d.methodOverriders;return!a.isUndefined(a.find(e,function(a){return a.toLowerCase()===b.toLowerCase()}))},d.urlCreator=d.urlCreator||"path",c.setUrlCreator=function(b){if(!a.has(d.urlCreatorFactory,b))throw new Error("URL Path selected isn't valid");return d.urlCreator=b,this},d.restangularFields=d.restangularFields||{id:"id",route:"route",parentResource:"parentResource",restangularCollection:"restangularCollection",cannonicalId:"__cannonicalId",etag:"restangularEtag",selfLink:"href",get:"get",getList:"getList",put:"put",post:"post",remove:"remove",head:"head",trace:"trace",options:"options",patch:"patch",getRestangularUrl:"getRestangularUrl",getRequestedUrl:"getRequestedUrl",putElement:"putElement",addRestangularMethod:"addRestangularMethod",getParentList:"getParentList",clone:"clone",ids:"ids",httpConfig:"_$httpConfig",reqParams:"reqParams",one:"one",all:"all",several:"several",oneUrl:"oneUrl",allUrl:"allUrl",customPUT:"customPUT",customPATCH:"customPATCH",customPOST:"customPOST",customDELETE:"customDELETE",customGET:"customGET",customGETLIST:"customGETLIST",customOperation:"customOperation",doPUT:"doPUT",doPATCH:"doPATCH",doPOST:"doPOST",doDELETE:"doDELETE",doGET:"doGET",doGETLIST:"doGETLIST",fromServer:"fromServer",withConfig:"withConfig",withHttpConfig:"withHttpConfig",singleOne:"singleOne",plain:"plain",save:"save",restangularized:"restangularized"},c.setRestangularFields=function(b){return d.restangularFields=a.extend(d.restangularFields,b),this},d.isRestangularized=function(a){return!!a[d.restangularFields.restangularized]},d.setFieldToElem=function(b,c,d){var e=b.split("."),f=c;return a.each(a.initial(e),function(a){f[a]={},f=f[a]}),f[a.last(e)]=d,this},d.getFieldFromElem=function(c,d){var e=c.split("."),f=d;return a.each(e,function(a){f&&(f=f[a])}),b.copy(f)},d.setIdToElem=function(a,b){return d.setFieldToElem(d.restangularFields.id,a,b),this},d.getIdFromElem=function(a){return d.getFieldFromElem(d.restangularFields.id,a)},d.isValidId=function(b){return""!==b&&!a.isUndefined(b)&&!a.isNull(b)},d.setUrlToElem=function(a,b){return d.setFieldToElem(d.restangularFields.selfLink,a,b),this},d.getUrlFromElem=function(a){return d.getFieldFromElem(d.restangularFields.selfLink,a)},d.useCannonicalId=!a.isUndefined(d.useCannonicalId)&&d.useCannonicalId,c.setUseCannonicalId=function(a){return d.useCannonicalId=a,this},d.getCannonicalIdFromElem=function(a){var b=a[d.restangularFields.cannonicalId],c=d.isValidId(b)?b:d.getIdFromElem(a);return c},d.responseInterceptors=d.responseInterceptors||[],d.defaultResponseInterceptor=function(a){return a},d.responseExtractor=function(c,e,f,g,h,i){var j=b.copy(d.responseInterceptors);j.push(d.defaultResponseInterceptor);var k=c;return a.each(j,function(a){k=a(k,e,f,g,h,i)}),k},c.addResponseInterceptor=function(a){return d.responseInterceptors.push(a),this},d.errorInterceptors=d.errorInterceptors||[],c.addErrorInterceptor=function(a){return d.errorInterceptors.push(a),this},c.setResponseInterceptor=c.addResponseInterceptor,c.setResponseExtractor=c.addResponseInterceptor,c.setErrorInterceptor=c.addErrorInterceptor,d.requestInterceptors=d.requestInterceptors||[],d.defaultInterceptor=function(a,b,c,d,e,f,g){return{element:a,headers:e,params:f,httpConfig:g}},d.fullRequestInterceptor=function(c,e,f,g,h,i,j){var k=b.copy(d.requestInterceptors),l=d.defaultInterceptor(c,e,f,g,h,i,j);return a.reduce(k,function(b,c){return a.extend(b,c(b.element,e,f,g,b.headers,b.params,b.httpConfig))},l)},c.addRequestInterceptor=function(a){return d.requestInterceptors.push(function(b,c,d,e,f,g,h){return{headers:f,params:g,element:a(b,c,d,e),httpConfig:h}}),this},c.setRequestInterceptor=c.addRequestInterceptor,c.addFullRequestInterceptor=function(a){return d.requestInterceptors.push(a),this},c.setFullRequestInterceptor=c.addFullRequestInterceptor,d.onBeforeElemRestangularized=d.onBeforeElemRestangularized||function(a){return a},c.setOnBeforeElemRestangularized=function(a){return d.onBeforeElemRestangularized=a,this},c.setRestangularizePromiseInterceptor=function(a){return d.restangularizePromiseInterceptor=a,this},d.onElemRestangularized=d.onElemRestangularized||function(a){return a},c.setOnElemRestangularized=function(a){return d.onElemRestangularized=a,this},d.shouldSaveParent=d.shouldSaveParent||function(){return!0},c.setParentless=function(b){return a.isArray(b)?d.shouldSaveParent=function(c){return!a.includes(b,c)}:a.isBoolean(b)&&(d.shouldSaveParent=function(){return!b}),this},d.suffix=a.isUndefined(d.suffix)?null:d.suffix,c.setRequestSuffix=function(a){return d.suffix=a,this},d.transformers=d.transformers||{},d.matchTransformers=d.matchTransformers||[],c.addElementTransformer=function(b,e,f){var g=null,h=null;2===arguments.length?h=e:(h=f,g=e);var i=function(b,c){return a.isNull(g)||b===g?h(c):c};return a.isRegExp(b)?d.matchTransformers.push({regexp:b,transformer:i}):(d.transformers[b]||(d.transformers[b]=[]),d.transformers[b].push(i)),c},c.extendCollection=function(a,b){return c.addElementTransformer(a,!0,b)},c.extendModel=function(a,b){return c.addElementTransformer(a,!1,b)},d.transformElem=function(b,c,e,f,g){if(!g&&!d.transformLocalElements&&!b[d.restangularFields.fromServer])return b;var h=b,i=d.matchTransformers;i&&a.each(i,function(a){a.regexp.test(e)&&(h=a.transformer(c,h))});var j=d.transformers[e];return j&&a.each(j,function(a){h=a(c,h)}),d.onElemRestangularized(h,c,e,f)},d.transformLocalElements=!a.isUndefined(d.transformLocalElements)&&d.transformLocalElements,c.setTransformOnlyServerElements=function(a){d.transformLocalElements=!a},d.fullResponse=!a.isUndefined(d.fullResponse)&&d.fullResponse,c.setFullResponse=function(a){return d.fullResponse=a,this},d.urlCreatorFactory={};var h=function(){};h.prototype.setConfig=function(a){return this.config=a,this},h.prototype.parentsArray=function(a){for(var b=[];a;)b.push(a),a=a[this.config.restangularFields.parentResource];return b.reverse()},h.prototype.resource=function(b,c,f,g,h,i,j,k){var l=a.defaults(h||{},this.config.defaultRequestParams.common),m=a.defaults(g||{},this.config.defaultHeaders);j&&(d.isSafe(k)?m["If-None-Match"]=j:m["If-Match"]=j);var n=this.base(b);if(i||0===i){var o="";/\/$/.test(n)||(o+="/"),o+=i,n+=o}return this.config.suffix&&n.indexOf(this.config.suffix,n.length-this.config.suffix.length)===-1&&!this.config.getUrlFromElem(b)&&(n+=this.config.suffix),b[this.config.restangularFields.httpConfig]=void 0,e(this.config,c,n,{getList:this.config.withHttpValues(f,{method:"GET",params:l,headers:m}),get:this.config.withHttpValues(f,{method:"GET",params:l,headers:m}),jsonp:this.config.withHttpValues(f,{method:"jsonp",params:l,headers:m}),put:this.config.withHttpValues(f,{method:"PUT",params:l,headers:m}),post:this.config.withHttpValues(f,{method:"POST",params:l,headers:m}),remove:this.config.withHttpValues(f,{method:"DELETE",params:l,headers:m}),head:this.config.withHttpValues(f,{method:"HEAD",params:l,headers:m}),trace:this.config.withHttpValues(f,{method:"TRACE",params:l,headers:m}),options:this.config.withHttpValues(f,{method:"OPTIONS",params:l,headers:m}),patch:this.config.withHttpValues(f,{method:"PATCH",params:l,headers:m})})};var i=function(){};i.prototype=new h,i.prototype.normalizeUrl=function(a){var b=/((?:http[s]?:)?\/\/)?(.*)?/.exec(a);return b[2]=b[2].replace(/[\\\/]+/g,"/"),"undefined"!=typeof b[1]?b[1]+b[2]:b[2]},i.prototype.base=function(b){var c=this;return a.reduce(this.parentsArray(b),function(a,b){var e,f=c.config.getUrlFromElem(b);if(f){if(c.config.isAbsoluteUrl(f))return f;e=f}else if(e=b[c.config.restangularFields.route],b[c.config.restangularFields.restangularCollection]){var g=b[c.config.restangularFields.ids];g&&(e+="/"+g.join(","))}else{var h;h=c.config.useCannonicalId?c.config.getCannonicalIdFromElem(b):c.config.getIdFromElem(b),d.isValidId(h)&&!b.singleOne&&(e+="/"+(c.config.encodeIds?encodeURIComponent(h):h))}return a=a.replace(/\/$/,"")+"/"+e,c.normalizeUrl(a)},this.config.baseUrl)},i.prototype.fetchUrl=function(a,b){var c=this.base(a);return b&&(c+="/"+b),c},i.prototype.fetchRequestedUrl=function(a,c){function e(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b.sort()}function f(a,b,c){for(var d=e(a),f=0;f= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(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; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + 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 = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = 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 = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (isArrayLike(obj)) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : _.keys(obj).length; + }; + + // Split a collection into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(obj, predicate, context) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + return [pass, fail]; + }; + + // 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; + if (n == null || guard) return array[0]; + return _.initial(array, array.length - n); + }; + + // 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. + _.initial = function(array, n, guard) { + return slice.call(array, 0, Math.max(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. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[array.length - 1]; + return _.rest(array, Math.max(0, array.length - n)); + }; + + // 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. + _.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, strict, startIndex) { + var output = [], idx = 0; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, false); + }; + + // 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, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + return result; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(flatten(arguments, true, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + return result; + }; + + // 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 = flatten(arguments, true, true, 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() { + return _.unzip(arguments); + }; + + // Complement of _.zip. Unzip accepts an array of arrays and groups + // each array's elements on shared indices + _.unzip = function(array) { + var length = array && _.max(array, getLength).length || 0; + var result = Array(length); + + for (var index = 0; index < length; index++) { + result[index] = _.pluck(array, index); + } + return result; + }; + + // 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) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + return -1; + }; + } + + // Returns the first index on an array-like that passes a predicate test + _.findIndex = createPredicateIndexFinder(1); + _.findLastIndex = createPredicateIndexFinder(-1); + + // 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, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; + } + + // Return the position of the first occurrence of an item in an array, + // or -1 if the item is not included in the array. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); + _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); + + // 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 (stop == null) { + stop = start || 0; + start = 0; + } + step = step || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Determines whether to execute a function as a constructor + // or a normal function with the provided arguments + var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + if (_.isObject(result)) return result; + return self; + }; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + return bound; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + return bound; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + memoize.cache = {}; + return memoize; + }; + + // 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 = _.partial(_.delay, _, 1); + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + 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, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // 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 _.partial(wrapper, func); + }; + + // Returns a negated version of the passed-in predicate. + _.negate = function(predicate) { + return function() { + return !predicate.apply(this, arguments); + }; + }; + + // 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 args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + return memo; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = _.partial(_.before, 2); + + // Object Functions + // ---------------- + + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + + function collectNonEnumProps(obj, keys) { + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; + + // Constructor is a special case. + var prop = 'constructor'; + if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); + + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Returns the results of applying the iteratee to each element of the object + // In contrast to _.map it returns an object + _.mapObject = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + result[obj[keys[i]]] = keys[i]; + } + 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 = createAssigner(_.allKeys); + + // Assigns a given object with all the own properties in the passed-in object(s) + // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + _.extendOwn = _.assign = createAssigner(_.keys); + + // Returns the first key on an object that passes a predicate test + _.findKey = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(object, oiteratee, context) { + var result = {}, obj = object, iteratee, keys; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + return _.pick(obj, iteratee, context); + }; + + // Fill in a given object with default properties. + _.defaults = createAssigner(_.allKeys, true); + + // Creates an object that inherits from the given prototype object. + // If additional properties are provided then they will be added to the + // created object. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + if (props) _.extendOwn(result, props); + return result; + }; + + // 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; + }; + + // Returns whether an object has a given set of `key:value` pairs. + _.isMatch = function(object, attrs) { + var keys = _.keys(attrs), length = keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + return true; + }; + + + // 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, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +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; + } + + var areArrays = className === '[object Array]'; + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + + // Objects with different constructors are not equivalent, but `Object`s or `Array`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) + && ('constructor' in a && 'constructor' in b)) { + 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`. + + // Initializing stack of traversed objects. + // It's done here since we only need them for objects and arrays comparison. + aStack = aStack || []; + bStack = bStack || []; + 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); + + // Recursively compare objects and arrays. + if (areArrays) { + // Compare array lengths to determine if a deep comparison is necessary. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return true; + }; + + // 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 (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; + return _.keys(obj).length === 0; + }; + + // 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) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. + _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) === '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE < 9), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return _.has(obj, 'callee'); + }; + } + + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, + // IE 11 (#1621), and in Safari 8 (#1929). + if (typeof /./ != 'function' && typeof Int8Array != 'object') { + _.isFunction = function(obj) { + return typeof obj == 'function' || false; + }; + } + + // 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 obj != null && 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 iteratees. + _.identity = function(value) { + return value; + }; + + // Predicate-generating functions. Often useful outside of Underscore. + _.constant = function(value) { + return function() { + return value; + }; + }; + + _.noop = function(){}; + + _.property = property; + + // Generates a function for a given object that returns a given property. + _.propertyOf = function(obj) { + return obj == null ? function(){} : function(key) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of + // `key:value` pairs. + _.matcher = _.matches = function(attrs) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(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 + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { + return new Date().getTime(); + }; + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.escape = createEscaper(escapeMap); + _.unescape = createEscaper(unescapeMap); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property, fallback) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + return _.isFunction(value) ? value.call(object) : value; + }; + + // 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', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; + + var escapeChar = function(match) { + return '\\' + escapes[match]; + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + // NB: `oldSettings` only exists for backwards compatibility. + _.template = function(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = 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, escapeChar); + index = offset + match.length; + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + + // Adobe VMs need the match returned to produce the correct offest. + 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; + } + + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled source as a convenience for precompilation. + var argument = settings.variable || 'obj'; + template.source = 'function(' + argument + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // 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(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // 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(this, func.apply(_, args)); + }; + }); + }; + + // 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(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(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } +}.call(this)); diff --git a/vendor/assets/javascripts/underscore.min.js b/vendor/assets/javascripts/underscore.min.js new file mode 100644 index 00000000..f01025b7 --- /dev/null +++ b/vendor/assets/javascripts/underscore.min.js @@ -0,0 +1,6 @@ +// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this); +//# sourceMappingURL=underscore-min.map \ No newline at end of file diff --git a/vendor/assets/javascripts/xeditable.min.js b/vendor/assets/javascripts/xeditable.min.js new file mode 100755 index 00000000..7d527bda --- /dev/null +++ b/vendor/assets/javascripts/xeditable.min.js @@ -0,0 +1,7 @@ +/*! +angular-xeditable - 0.6.0 +Edit-in-place for angular.js +Build date: 2016-12-27 +*/ +angular.module("xeditable",[]).value("editableOptions",{theme:"default",icon_set:"default",buttons:"right",blurElem:"cancel",blurForm:"ignore",activate:"focus",isDisabled:!1,activationEvent:"click",submitButtonTitle:"Submit",submitButtonAriaLabel:"Submit",cancelButtonTitle:"Cancel",cancelButtonAriaLabel:"Cancel",clearButtonTitle:"Clear",clearButtonAriaLabel:"Clear",displayClearButton:!1}),angular.module("xeditable").directive("editableBsdate",["editableDirectiveFactory","$injector","$parse",function(a,b,c){uibDatepickerConfig=b.get("uibDatepickerConfig"),uibDatepickerPopupConfig=b.get("uibDatepickerPopupConfig");var d=[["eIsOpen","is-open"],["eDateDisabled","date-disabled"],["eDatepickerPopup","uib-datepicker-popup"],["eShowButtonBar","show-button-bar"],["eCurrentText","current-text"],["eClearText","clear-text"],["eCloseText","close-text"],["eCloseOnDateSelection","close-on-date-selection"],["eDatePickerAppendToBody","datepicker-append-to-body"],["eOnOpenFocus","on-open-focus"],["eName","name"],["eDateDisabled","date-disabled"]],e=[["eFormatDay","formatDay"],["eFormatMonth","formatMonth"],["eFormatYear","formatYear"],["eFormatDayHeader","formatDayHeader"],["eFormatDayTitle","formatDayTitle"],["eFormatMonthTitle","formatMonthTitle"],["eMaxMode","maxMode"],["eMinMode","minMode"],["eDatepickerMode","datepickerMode"]];return a({directiveName:"editableBsdate",inputTpl:"
",render:function(){this.parent.render.call(this);var a=this.attrs,b=this.scope,f=angular.element('');f.attr("uib-datepicker-popup",a.eDatepickerPopupXEditable||uibDatepickerPopupConfig.datepickerPopup),f.attr("year-range",a.eYearRange||20),f.attr("ng-readonly",a.eReadonly||!1);for(var g=d.length-1;g>=0;g--){var h=a[d[g][0]];"undefined"!=typeof h&&f.attr(d[g][1],h)}a.eNgChange&&(f.attr("ng-change",a.eNgChange),this.inputEl.removeAttr("ng-change")),a.eStyle&&(f.attr("style",a.eStyle),this.inputEl.removeAttr("style"));var i={maxDate:b.$eval(a.eMaxDate)||uibDatepickerConfig.maxDate,minDate:b.$eval(a.eMinDate)||uibDatepickerConfig.minDate,showWeeks:a.eShowWeeks?"true"===a.eShowWeeks.toLowerCase():uibDatepickerConfig.showWeeks,startingDay:a.eStartingDay||0,initDate:b.$eval(a.eInitDate)||new Date};if(a.eDatepickerOptions){var j=c(a.eDatepickerOptions)(b);angular.extend(i,j)}for(var k=e.length-1;k>=0;k--){var l=a[e[k][0]];"undefined"!=typeof l&&(i[e[k][1]]=l)}b.dateOptions=i;var m=angular.isDefined(a.eShowCalendarButton)?a.eShowCalendarButton:"true";if("true"===m){var n=angular.element(''),o=angular.element('');n.attr("ng-click",a.eNgClick),o.append(n),this.inputEl.append(o)}else f.attr("ng-click",a.eNgClick);f.attr("datepicker-options","dateOptions"),this.inputEl.prepend(f),this.inputEl.removeAttr("class"),this.inputEl.removeAttr("ng-click"),this.inputEl.removeAttr("is-open"),this.inputEl.removeAttr("init-date"),this.inputEl.removeAttr("datepicker-popup"),this.inputEl.removeAttr("required"),this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("date-picker-append-to-body"),this.inputEl.removeAttr("name"),this.inputEl.attr("class","input-group")}})}]),angular.module("xeditable").directive("editableBstime",["editableDirectiveFactory",function(a){return a({directiveName:"editableBstime",inputTpl:"",render:function(){this.parent.render.call(this);var a=angular.element('
');a.attr("ng-model",this.inputEl.attr("ng-model")),this.inputEl.removeAttr("ng-model"),this.attrs.eNgChange&&(a.attr("ng-change",this.inputEl.attr("ng-change")),this.inputEl.removeAttr("ng-change")),this.inputEl.wrap(a)}})}]),angular.module("xeditable").directive("editableCheckbox",["editableDirectiveFactory",function(a){return a({directiveName:"editableCheckbox",inputTpl:'',render:function(){this.parent.render.call(this),this.attrs.eTitle&&(this.inputEl.wrap(""),this.inputEl.parent().append(""+this.attrs.eTitle+""))},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){setTimeout(function(){a.scope.$apply(function(){a.scope.$form.$submit()})},500)})}})}]),angular.module("xeditable").directive("editableChecklist",["editableDirectiveFactory","editableNgOptionsParser",function(a,b){return a({directiveName:"editableChecklist",inputTpl:"",useCopy:!0,render:function(){this.parent.render.call(this);var a=b(this.attrs.eNgOptions),c="",d="";this.attrs.eNgChange&&(c=' ng-change="'+this.attrs.eNgChange+'"'),this.attrs.eChecklistComparator&&(d=' checklist-comparator="'+this.attrs.eChecklistComparator+'"');var e='';this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("ng-options"),this.inputEl.removeAttr("ng-change"),this.inputEl.removeAttr("checklist-comparator"),this.inputEl.html(e)}})}]),angular.module("xeditable").directive("editableCombodate",["editableDirectiveFactory","editableCombodate",function(a,b){return a({directiveName:"editableCombodate",inputTpl:'',render:function(){this.parent.render.call(this);var a={value:new Date(this.scope.$data)},c=this;angular.forEach(["format","template","minYear","maxYear","yearDescending","minuteStep","secondStep","firstItem","errorClass","customClass","roundTime","smartDays"],function(b){var d="e"+b.charAt(0).toUpperCase()+b.slice(1);d in c.attrs&&("minYear"==b||"maxYear"==b||"minuteStep"==b||"secondStep"==b?a[b]=parseInt(c.attrs[d],10):a[b]=c.attrs[d])});var d=b.getInstance(this.inputEl,a);d.$widget.find("select").bind("change",function(a){c.scope.$data=new Date(d.getValue()).toISOString()})}})}]),function(){var a=function(a){return a.toLowerCase().replace(/-(.)/g,function(a,b){return b.toUpperCase()})},b="text|password|email|tel|number|url|search|color|date|datetime|datetime-local|time|month|week|file".split("|");angular.forEach(b,function(b){var c=a("editable-"+b);angular.module("xeditable").directive(c,["editableDirectiveFactory",function(a){return a({directiveName:c,inputTpl:'',render:function(){if(this.parent.render.call(this),this.attrs.eInputgroupleft||this.attrs.eInputgroupright){if(this.inputEl.wrap('
'),this.attrs.eInputgroupleft){var a=angular.element(''+this.attrs.eInputgroupleft+"");this.inputEl.parent().prepend(a)}if(this.attrs.eInputgroupright){var b=angular.element(''+this.attrs.eInputgroupright+"");this.inputEl.parent().append(b)}}if(this.attrs.eLabel){var c=angular.element("");this.attrs.eInputgroupleft||this.attrs.eInputgroupright?this.inputEl.parent().parent().prepend(c):this.inputEl.parent().prepend(c)}this.attrs.eFormclass&&this.editorEl.addClass(this.attrs.eFormclass)},autosubmit:function(){var a=this;a.inputEl.bind("keydown",function(b){9===b.keyCode&&a.scope.$apply(function(){a.scope.$form.$submit()})})}})}])}),angular.module("xeditable").directive("editableRange",["editableDirectiveFactory","$interpolate",function(a,b){return a({directiveName:"editableRange",inputTpl:'',render:function(){this.parent.render.call(this),this.inputEl.after(""+b.startSymbol()+"$data"+b.endSymbol()+"")}})}])}(),angular.module("xeditable").directive("editableTagsInput",["editableDirectiveFactory","editableUtils",function(a,b){var c=a({directiveName:"editableTagsInput",inputTpl:"",render:function(){this.parent.render.call(this),this.inputEl.append(b.rename("auto-complete",this.attrs.$autoCompleteElement)),this.inputEl.removeAttr("ng-model"),this.inputEl.attr("ng-model","$parent.$data")}}),d=c.link;return c.link=function(a,b,c,e){var f=b.find("editable-tags-input-auto-complete");return c.$autoCompleteElement=f.clone(),f.remove(),d(a,b,c,e)},c}]),angular.module("xeditable").directive("editableRadiolist",["editableDirectiveFactory","editableNgOptionsParser","$interpolate",function(a,b,c){return a({directiveName:"editableRadiolist",inputTpl:"",render:function(){this.parent.render.call(this);var a=b(this.attrs.eNgOptions),d="";this.attrs.eNgChange&&(d='ng-change="'+this.attrs.eNgChange+'"');var e='';this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("ng-options"),this.inputEl.removeAttr("ng-change"),this.inputEl.html(e)},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){setTimeout(function(){a.scope.$apply(function(){a.scope.$form.$submit()})},500)})}})}]),angular.module("xeditable").directive("editableSelect",["editableDirectiveFactory",function(a){return a({directiveName:"editableSelect",inputTpl:"",render:function(){if(this.parent.render.call(this),this.attrs.ePlaceholder){var a=angular.element('");this.inputEl.append(a)}},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){a.scope.$apply(function(){a.scope.$form.$submit()})})}})}]),angular.module("xeditable").directive("editableTextarea",["editableDirectiveFactory",function(a){return a({directiveName:"editableTextarea",inputTpl:"",addListeners:function(){var a=this;a.parent.addListeners.call(a),a.single&&"no"!==a.buttons&&a.autosubmit()},autosubmit:function(){var a=this;a.inputEl.bind("keydown",function(b){a.attrs.submitOnEnter?13!==b.keyCode||b.shiftKey||a.scope.$apply(function(){a.scope.$form.$submit()}):(b.ctrlKey||b.metaKey)&&13===b.keyCode&&a.scope.$apply(function(){a.scope.$form.$submit()})})}})}]),angular.module("xeditable").directive("editableUidate",["editableDirectiveFactory",function(a){return a({directiveName:"editableUidate",inputTpl:'',render:function(){this.parent.render.call(this),this.inputEl.attr("ui-date",this.attrs.eUiDate),this.inputEl.attr("placeholder",this.attrs.ePlaceholder)}})}]),angular.module("xeditable").directive("editableUiSelect",["editableDirectiveFactory","editableUtils",function(a,b){var c=a({directiveName:"editableUiSelect",inputTpl:"",render:function(){this.parent.render.call(this),this.inputEl.append(b.rename("ui-select-match",this.attrs.$matchElement)),this.inputEl.append(b.rename("ui-select-choices",this.attrs.$choicesElement)),this.inputEl.removeAttr("ng-model"),this.inputEl.attr("ng-model","$parent.$parent.$data")}}),d=c.link;return c.link=function(a,b,c,e){var f=b.find("editable-ui-select-match"),g=b.find("editable-ui-select-choices");return c.$matchElement=f.clone(),c.$choicesElement=g.clone(),f.remove(),g.remove(),d(a,b,c,e)},c}]),angular.module("xeditable").factory("editableController",["$q","editableUtils",function(a,b){function c(a,c,d,e,f,g,h,i,j,k){var l,m,n=this;n.scope=a,n.elem=d,n.attrs=c,n.inputEl=null,n.editorEl=null,n.single=!0,n.error="",n.theme=f[c.editableTheme]||f[h.theme]||f["default"],n.parent={};var o=c.editableTheme||h.theme||"default",p=c.editableIconSet||h.icon_set;n.icon_set="default"===p?g["default"][o]:g.external[p],n.inputTpl="",n.directiveName="",n.useCopy=!1,n.single=null,n.buttons="right",n.init=function(b){if(n.single=b,n.name=c.eName||c[n.directiveName],!c[n.directiveName])throw"You should provide value for `"+n.directiveName+"` in editable element!";l=e(c[n.directiveName]),n.single?n.buttons=n.attrs.buttons||h.buttons:n.buttons="no",c.eName&&n.scope.$watch("$data",function(a){n.scope.$form.$data[c.eName]=a}),c.onshow&&(n.onshow=function(){return n.catchError(e(c.onshow)(a))}),c.onhide&&(n.onhide=function(){return e(c.onhide)(a)}),c.oncancel&&(n.oncancel=function(){return e(c.oncancel)(a)}),c.onbeforesave&&(n.onbeforesave=function(){return n.catchError(e(c.onbeforesave)(a))}),c.onaftersave&&(n.onaftersave=function(){return n.catchError(e(c.onaftersave)(a))}),a.$parent.$watch(c[n.directiveName],function(a,b){n.setLocalValue(),n.handleEmpty()})},n.render=function(){var a=n.theme;n.inputEl=angular.element(n.inputTpl),n.controlsEl=angular.element(a.controlsTpl),n.controlsEl.append(n.inputEl),"no"!==n.buttons&&(n.buttonsEl=angular.element(a.buttonsTpl),n.submitEl=angular.element(a.submitTpl),n.resetEl=angular.element(a.resetTpl),n.cancelEl=angular.element(a.cancelTpl),n.submitEl.attr("title",h.submitButtonTitle),n.submitEl.attr("aria-label",h.submitButtonAriaLabel),n.cancelEl.attr("title",h.cancelButtonTitle),n.cancelEl.attr("aria-label",h.cancelButtonAriaLabel),n.resetEl.attr("title",h.clearButtonTitle),n.resetEl.attr("aria-label",h.clearButtonAriaLabel),n.icon_set&&(n.submitEl.find("span").addClass(n.icon_set.ok),n.cancelEl.find("span").addClass(n.icon_set.cancel),n.resetEl.find("span").addClass(n.icon_set.clear)),n.buttonsEl.append(n.submitEl).append(n.cancelEl),h.displayClearButton&&n.buttonsEl.append(n.resetEl),n.controlsEl.append(n.buttonsEl),n.inputEl.addClass("editable-has-buttons")),n.errorEl=angular.element(a.errorTpl),n.controlsEl.append(n.errorEl),n.editorEl=angular.element(n.single?a.formTpl:a.noformTpl),n.editorEl.append(n.controlsEl);for(var d in c.$attr)if(!(d.length<=1)){var e=!1,f=d.substring(1,2);if("e"===d.substring(0,1)&&f===f.toUpperCase()&&(e=d.substring(1),"Form"!==e&&"NgSubmit"!==e)){var g=e.substring(0,1),i=e.substring(1,2);e=i===i.toUpperCase()&&g===g.toUpperCase()?g.toLowerCase()+"-"+b.camelToDash(e.substring(1)):g.toLowerCase()+b.camelToDash(e.substring(1));var j="value"!==e&&""===c[d]?e:c[d];n.inputEl.attr(e,j)}}n.inputEl.addClass("editable-input"),n.inputEl.attr("ng-model","$parent.$data"),n.editorEl.addClass(b.camelToDash(n.directiveName)),n.single&&(n.editorEl.attr("editable-form","$form"),n.editorEl.attr("blur",n.attrs.blur||("no"===n.buttons?"cancel":h.blurElem))),angular.isFunction(a.postrender)&&a.postrender.call(n)},n.setLocalValue=function(){n.scope.$data=n.useCopy?angular.copy(l(a.$parent)):l(a.$parent)};var q=null;n.show=function(){return n.setLocalValue(),n.render(),d.after(n.editorEl),q=a.$new(),j(n.editorEl)(q),n.addListeners(),d.addClass("editable-hide"),n.onshow()},n.hide=function(){return q.$destroy(),n.controlsEl.remove(),n.editorEl.remove(),d.removeClass("editable-hide"),n.onhide()},n.cancel=function(){n.oncancel()},n.addListeners=function(){n.inputEl.bind("keyup",function(a){if(n.single)switch(a.keyCode){case 27:n.scope.$apply(function(){n.scope.$form.$cancel()})}}),n.single&&"no"===n.buttons&&n.autosubmit(),n.editorEl.bind("click",function(a){a.which&&1!==a.which||n.scope.$form.$visible&&(n.scope.$form._clicked=!0)})},n.setWaiting=function(a){a?(m=!n.inputEl.attr("disabled")&&!n.inputEl.attr("ng-disabled")&&!n.inputEl.attr("ng-enabled"),m&&(n.inputEl.attr("disabled","disabled"),n.buttonsEl&&n.buttonsEl.find("button").attr("disabled","disabled"))):m&&(n.inputEl.removeAttr("disabled"),n.buttonsEl&&n.buttonsEl.find("button").removeAttr("disabled"))},n.activate=function(a,b){setTimeout(function(){var c=n.inputEl[0];"focus"===h.activate&&c.focus?(void 0!==a&&""!==a&&c.setSelectionRange&&(b=b||a,c.onfocus=function(){setTimeout(function(){try{this.setSelectionRange(a,b)}catch(c){}}.bind(this))}),"editableRadiolist"==n.directiveName||"editableChecklist"==n.directiveName||"editableBsdate"==n.directiveName||"editableTagsInput"==n.directiveName?c.querySelector(".ng-pristine").focus():c.focus()):"select"===h.activate&&(c.select?c.select():c.focus&&c.focus())},0)},n.setError=function(b){angular.isObject(b)||(a.$error=b,n.error=b)},n.catchError=function(a,b){return angular.isObject(a)&&b!==!0?k.when(a).then(angular.bind(this,function(a){this.catchError(a,!0)}),angular.bind(this,function(a){this.catchError(a,!0)})):b&&angular.isObject(a)&&a.status&&200!==a.status&&a.data&&angular.isString(a.data)?(this.setError(a.data),a=a.data):angular.isString(a)&&this.setError(a),a},n.save=function(){l.assign(a.$parent,n.useCopy?angular.copy(n.scope.$data):n.scope.$data)},n.handleEmpty=function(){var b=l(a.$parent),c=null===b||void 0===b||""===b||angular.isArray(b)&&0===b.length;d.toggleClass("editable-empty",c)},n.autosubmit=angular.noop,n.onshow=angular.noop,n.onhide=angular.noop,n.oncancel=angular.noop,n.onbeforesave=angular.noop,n.onaftersave=angular.noop}return c.$inject=["$scope","$attrs","$element","$parse","editableThemes","editableIcons","editableOptions","$rootScope","$compile","$q"],c}]),angular.module("xeditable").factory("editableDirectiveFactory",["$parse","$compile","editableThemes","$rootScope","$document","editableController","editableFormController","editableOptions",function(a,b,c,d,e,f,g,h){return function(b){return{restrict:"A",scope:!0,require:[b.directiveName,"?^form"],controller:f,link:function(c,f,i,j){var k,l=j[0],m=!1;if(j[1])k=j[1],m=void 0===i.eSingle;else if(i.eForm){var n=a(i.eForm)(c);if(n)k=n,m=!0;else if(f&&"function"==typeof f.parents&&f.parents().last().find("form[name="+i.eForm+"]").length)k=null,m=!0;else for(var o=0;o=0&&a.splice(c,1),b},camelToDash:function(a){var b=/[A-Z]/g;return a.replace(b,function(a,b){return(b?"-":"")+a.toLowerCase()})},dashToCamel:function(a){var b=/([\:\-\_]+(.))/g,c=/^moz([A-Z])/;return a.replace(b,function(a,b,c,d){return d?c.toUpperCase():c}).replace(c,"Moz$1")},rename:function(a,b){if(b[0]&&b[0].attributes){var c=angular.element("<"+a+"/>");c.html(b.html());for(var d=b[0].attributes,e=0;e').html(this.getTemplate()),this.initCombos(),this.options.smartDays){var a=this;this.$widget.find("select").bind("change",function(b){(angular.element(b.target).hasClass("month")||angular.element(b.target).hasClass("year"))&&a.fillCombo("day")})}this.$widget.find("select").css("width","auto"),this.$element.css("display","none").after(this.$widget),this.setValue(this.$element.val()||this.options.value)},getTemplate:function(){var a=this.options.template,b=this.options.customClass;return angular.forEach(this.map,function(b,c){b=b[0];var d=new RegExp(b+"+"),e=b.length>1?b.substring(1,2):b;a=a.replace(d,"{"+e+"}")}),a=a.replace(/ /g," "),angular.forEach(this.map,function(c,d){c=c[0];var e=c.length>1?c.substring(1,2):c;a=a.replace("{"+e+"}",'')}),a},initCombos:function(){for(var a in this.map){var b=this.$widget[0].querySelectorAll("."+a);this["$"+a]=b.length?angular.element(b):null,this.fillCombo(a)}},fillCombo:function(a){var b=this["$"+a];if(b){var c="fill"+a.charAt(0).toUpperCase()+a.slice(1),d=this[c](),e=b.val();b.html("");for(var f=0;f'+d[f][1]+"");b.val(e)}},fillCommon:function(a){var b,c=[];if("name"===this.options.firstItem){b=moment.relativeTime||moment.langData()._relativeTime;var d="function"==typeof b[a]?b[a](1,!0,a,!1):b[a];d=d.split(" ").reverse()[0],c.push(["",d])}else"empty"===this.options.firstItem&&c.push(["",""]);return c},fillDay:function(){var a,b,c=this.fillCommon("d"),d=-1!==this.options.template.indexOf("DD"),e=31;if(this.options.smartDays&&this.$month&&this.$year){var f=parseInt(this.$month.val(),10),g=parseInt(this.$year.val(),10);isNaN(f)||isNaN(g)||(e=moment([g,f]).daysInMonth())}for(b=1;e>=b;b++)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillMonth:function(){var a,b,c=this.fillCommon("M"),d=-1!==this.options.template.indexOf("MMMM"),e=-1!==this.options.template.indexOf("MMM"),f=-1!==this.options.template.indexOf("MM");for(b=0;11>=b;b++)a=d?moment().date(1).month(b).format("MMMM"):e?moment().date(1).month(b).format("MMM"):f?this.leadZero(b+1):b+1,c.push([b,a]);return c},fillYear:function(){var a,b,c=[],d=-1!==this.options.template.indexOf("YYYY");for(b=this.options.maxYear;b>=this.options.minYear;b--)a=d?b:(b+"").substring(2),c[this.options.yearDescending?"push":"unshift"]([b,a]);return c=this.fillCommon("y").concat(c)},fillHour:function(){var a,b,c=this.fillCommon("h"),d=-1!==this.options.template.indexOf("h"),e=(-1!==this.options.template.indexOf("H"),-1!==this.options.template.toLowerCase().indexOf("hh")),f=d?1:0,g=d?12:23;for(b=f;g>=b;b++)a=e?this.leadZero(b):b,c.push([b,a]);return c},fillMinute:function(){var a,b,c=this.fillCommon("m"),d=-1!==this.options.template.indexOf("mm");for(b=0;59>=b;b+=this.options.minuteStep)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillSecond:function(){var a,b,c=this.fillCommon("s"),d=-1!==this.options.template.indexOf("ss");for(b=0;59>=b;b+=this.options.secondStep)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillAmpm:function(){var a=-1!==this.options.template.indexOf("a"),b=(-1!==this.options.template.indexOf("A"),[["am",a?"am":"AM"],["pm",a?"pm":"PM"]]);return b},getValue:function(a){var b,c={},d=this,e=!1;return angular.forEach(this.map,function(a,b){if("ampm"!==b){var f="day"===b?1:0;return c[b]=d["$"+b]?parseInt(d["$"+b].val(),10):f,isNaN(c[b])?(e=!0,!1):void 0}}),e?"":(this.$ampm&&(12===c.hour?c.hour="am"===this.$ampm.val()?0:12:c.hour="am"===this.$ampm.val()?c.hour:c.hour+12),b=moment([c.year,c.month,c.day,c.hour,c.minute,c.second]),this.highlight(b),a=void 0===a?this.options.format:a,null===a?b.isValid()?b:null:b.isValid()?b.format(a):"")},setValue:function(a){function b(a,b){var c={};return angular.forEach(a.children("option"),function(a,d){var e=angular.element(a).attr("value");if(""!==e){var f=Math.abs(e-b);("undefined"==typeof c.distance||f=12?(e.ampm="pm",e.hour>12&&(e.hour-=12)):(e.ampm="am",0===e.hour&&(e.hour=12))),angular.forEach(e,function(a,c){d["$"+c]&&("minute"===c&&d.options.minuteStep>1&&d.options.roundTime&&(a=b(d["$"+c],a)),"second"===c&&d.options.secondStep>1&&d.options.roundTime&&(a=b(d["$"+c],a)),d["$"+c].val(a))}),this.options.smartDays&&this.fillCombo("day"),this.$element.val(c.format(this.options.format)).triggerHandler("change"))}},highlight:function(a){a.isValid()?this.options.errorClass?this.$widget.removeClass(this.options.errorClass):this.$widget.find("select").css("border-color",this.borderColor):this.options.errorClass?this.$widget.addClass(this.options.errorClass):(this.borderColor||(this.borderColor=this.$widget.find("select").css("border-color")),this.$widget.find("select").css("border-color","red"))},leadZero:function(a){return 9>=a?"0"+a:a},destroy:function(){this.$widget.remove(),this.$element.removeData("combodate").show()}},{getInstance:function(b,c){return new a(b,c)}}}]),angular.module("xeditable").factory("editableIcons",function(){var a={"default":{bs2:{ok:"icon-ok icon-white",cancel:"icon-remove",clear:"icon-trash"},bs3:{ok:"glyphicon glyphicon-ok",cancel:"glyphicon glyphicon-remove",clear:"glyphicon glyphicon-trash"}},external:{"font-awesome":{ok:"fa fa-check",cancel:"fa fa-times",clear:"fa fa-trash"}}};return a}),angular.module("xeditable").factory("editableThemes",function(){var a={"default":{formTpl:'
',noformTpl:'',controlsTpl:'',inputTpl:"",errorTpl:'
', +buttonsTpl:'',submitTpl:'',cancelTpl:'',resetTpl:''},bs2:{formTpl:'
',noformTpl:'',controlsTpl:'
',inputTpl:"",errorTpl:'
',buttonsTpl:'',submitTpl:'',cancelTpl:'',resetTpl:''},bs3:{formTpl:'
',noformTpl:'',controlsTpl:'
',inputTpl:"",errorTpl:'
',buttonsTpl:'',submitTpl:'',cancelTpl:'',resetTpl:'',buttonsClass:"",inputClass:"",postrender:function(){switch(this.directiveName){case"editableText":case"editableSelect":case"editableTextarea":case"editableEmail":case"editableTel":case"editableNumber":case"editableUrl":case"editableSearch":case"editableDate":case"editableDatetime":case"editableBsdate":case"editableTime":case"editableMonth":case"editableWeek":case"editablePassword":case"editableDatetimeLocal":if(this.inputEl.addClass("form-control"),this.theme.inputClass){if(this.inputEl.attr("multiple")&&("input-sm"===this.theme.inputClass||"input-lg"===this.theme.inputClass))break;this.inputEl.addClass(this.theme.inputClass)}break;case"editableCheckbox":this.editorEl.addClass("checkbox")}this.buttonsEl&&this.theme.buttonsClass&&this.buttonsEl.find("button").addClass(this.theme.buttonsClass)}},semantic:{formTpl:'
',noformTpl:'',controlsTpl:'
',inputTpl:"",errorTpl:'
',buttonsTpl:'',submitTpl:'',cancelTpl:'',resetTpl:''}};return a}); \ No newline at end of file diff --git a/vendor/assets/stylesheets/.keep b/vendor/assets/stylesheets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/vendor/assets/stylesheets/ng-animate.css b/vendor/assets/stylesheets/ng-animate.css new file mode 100644 index 00000000..8312e1fe --- /dev/null +++ b/vendor/assets/stylesheets/ng-animate.css @@ -0,0 +1,1262 @@ +/* ------------------------------------------- */ +/* Mixins +/* ------------------------------------------- */ +/* ------------------------------------------- */ +/* Toggle Fade +/* ------------------------------------------- */ +/* line 64, ../sass/ng-animation.scss */ +.toggle { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 66, ../sass/ng-animation.scss */ +.toggle.ng-enter { + opacity: 0; + transition-duration: 250ms; + -webkit-transition-duration: 250ms; +} +/* line 71, ../sass/ng-animation.scss */ +.toggle.ng-enter-active { + opacity: 1; +} +/* line 75, ../sass/ng-animation.scss */ +.toggle.ng-leave { + opacity: 1; + transition-duration: 250ms; + -webkit-transition-duration: 250ms; +} +/* line 80, ../sass/ng-animation.scss */ +.toggle.ng-leave-active { + opacity: 0; +} +/* line 85, ../sass/ng-animation.scss */ +.toggle.ng-hide-add { + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 89, ../sass/ng-animation.scss */ +.toggle.ng-hide-add.ng-hide-add-active { + opacity: 0; +} +/* line 94, ../sass/ng-animation.scss */ +.toggle.ng-hide-remove { + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 99, ../sass/ng-animation.scss */ +.toggle.ng-hide-remove.ng-hide-remove-active { + opacity: 1; +} + +/* ------------------------------------------- */ +/* Slide Top +/* ------------------------------------------- */ +/* line 109, ../sass/ng-animation.scss */ +.slide-top { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 111, ../sass/ng-animation.scss */ +.slide-top.ng-enter { + transform: translateY(60px); + -ms-transform: translateY(60px); + -webkit-transform: translateY(60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 117, ../sass/ng-animation.scss */ +.slide-top.ng-enter-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} +/* line 122, ../sass/ng-animation.scss */ +.slide-top.ng-leave { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 128, ../sass/ng-animation.scss */ +.slide-top.ng-leave-active { + transform: translateY(60px); + -ms-transform: translateY(60px); + -webkit-transform: translateY(60px); + opacity: 0; +} +/* line 134, ../sass/ng-animation.scss */ +.slide-top.ng-hide-add { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 139, ../sass/ng-animation.scss */ +.slide-top.ng-hide-add.ng-hide-add-active { + transform: translateY(60px); + -ms-transform: translateY(60px); + -webkit-transform: translateY(60px); + opacity: 0; +} +/* line 145, ../sass/ng-animation.scss */ +.slide-top.ng-hide-remove { + transform: translateY(60px); + -ms-transform: translateY(60px); + -webkit-transform: translateY(60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 151, ../sass/ng-animation.scss */ +.slide-top.ng-hide-remove.ng-hide-remove-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Slide Rigth +/* ------------------------------------------- */ +/* line 163, ../sass/ng-animation.scss */ +.slide-right { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 165, ../sass/ng-animation.scss */ +.slide-right.ng-enter { + transform: translateX(60px); + -ms-transform: translateX(60px); + -webkit-transform: translateX(60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 171, ../sass/ng-animation.scss */ +.slide-right.ng-enter-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} +/* line 176, ../sass/ng-animation.scss */ +.slide-right.ng-leave { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 182, ../sass/ng-animation.scss */ +.slide-right.ng-leave-active { + transform: translateX(60px); + -ms-transform: translateX(60px); + -webkit-transform: translateX(60px); + opacity: 0; +} +/* line 188, ../sass/ng-animation.scss */ +.slide-right.ng-hide-add { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 193, ../sass/ng-animation.scss */ +.slide-right.ng-hide-add.ng-hide-add-active { + transform: translateX(60px); + -ms-transform: translateX(60px); + -webkit-transform: translateX(60px); + opacity: 0; +} +/* line 199, ../sass/ng-animation.scss */ +.slide-right.ng-hide-remove { + transform: translateX(60px); + -ms-transform: translateX(60px); + -webkit-transform: translateX(60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 205, ../sass/ng-animation.scss */ +.slide-right.ng-hide-remove.ng-hide-remove-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Slide Left +/* ------------------------------------------- */ +/* line 217, ../sass/ng-animation.scss */ +.slide-left { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 219, ../sass/ng-animation.scss */ +.slide-left.ng-enter { + transform: translateX(-60px); + -ms-transform: translateX(-60px); + -webkit-transform: translateX(-60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 225, ../sass/ng-animation.scss */ +.slide-left.ng-enter-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} +/* line 230, ../sass/ng-animation.scss */ +.slide-left.ng-leave { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 236, ../sass/ng-animation.scss */ +.slide-left.ng-leave-active { + transform: translateX(-60px); + -ms-transform: translateX(-60px); + -webkit-transform: translateX(-60px); + opacity: 0; +} +/* line 242, ../sass/ng-animation.scss */ +.slide-left.ng-hide-add { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 247, ../sass/ng-animation.scss */ +.slide-left.ng-hide-add.ng-hide-add-active { + transform: translateX(-60px); + -ms-transform: translateX(-60px); + -webkit-transform: translateX(-60px); + opacity: 0; +} +/* line 253, ../sass/ng-animation.scss */ +.slide-left.ng-hide-remove { + transform: translateX(-60px); + -ms-transform: translateX(-60px); + -webkit-transform: translateX(-60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 259, ../sass/ng-animation.scss */ +.slide-left.ng-hide-remove.ng-hide-remove-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Slide Down +/* ------------------------------------------- */ +/* line 270, ../sass/ng-animation.scss */ +.slide-down { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 273, ../sass/ng-animation.scss */ +.slide-down.ng-enter { + transform: translateY(-60px); + -ms-transform: translateY(-60px); + -webkit-transform: translateY(-60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 279, ../sass/ng-animation.scss */ +.slide-down.ng-enter-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} +/* line 284, ../sass/ng-animation.scss */ +.slide-down.ng-leave { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 290, ../sass/ng-animation.scss */ +.slide-down.ng-leave-active { + transform: translateY(-60px); + -ms-transform: translateY(-60px); + -webkit-transform: translateY(-60px); + opacity: 0; +} +/* line 296, ../sass/ng-animation.scss */ +.slide-down.ng-hide-add { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 301, ../sass/ng-animation.scss */ +.slide-down.ng-hide-add.ng-hide-add-active { + transform: translateY(-60px); + -ms-transform: translateY(-60px); + -webkit-transform: translateY(-60px); + opacity: 0; +} +/* line 307, ../sass/ng-animation.scss */ +.slide-down.ng-hide-remove { + transform: translateY(-60px); + -ms-transform: translateY(-60px); + -webkit-transform: translateY(-60px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 313, ../sass/ng-animation.scss */ +.slide-down.ng-hide-remove.ng-hide-remove-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Bouncy Slide Top +/* ------------------------------------------- */ +/* line 325, ../sass/ng-animation.scss */ +.bouncy-slide-top { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 328, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-enter { + transform: translateY(240px); + -ms-transform: translateY(240px); + -webkit-transform: translateY(240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 334, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-enter-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} +/* line 339, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-leave { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 345, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-leave-active { + transform: translateY(240px); + -ms-transform: translateY(240px); + -webkit-transform: translateY(240px); + opacity: 0; +} +/* line 351, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-hide-add { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 356, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-hide-add.ng-hide-add-active { + transform: translateY(240px); + -ms-transform: translateY(240px); + -webkit-transform: translateY(240px); + opacity: 0; +} +/* line 362, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-hide-remove { + transform: translateY(240px); + -ms-transform: translateY(240px); + -webkit-transform: translateY(240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 368, ../sass/ng-animation.scss */ +.bouncy-slide-top.ng-hide-remove.ng-hide-remove-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Bouncy Slide Rigth +/* ------------------------------------------- */ +/* line 379, ../sass/ng-animation.scss */ +.bouncy-slide-right { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 382, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-enter { + transform: translateX(240px); + -ms-transform: translateX(240px); + -webkit-transform: translateX(240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 388, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-enter-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} +/* line 393, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-leave { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 399, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-leave-active { + transform: translateX(240px); + -ms-transform: translateX(240px); + -webkit-transform: translateX(240px); + opacity: 0; +} +/* line 405, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-hide-add { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 410, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-hide-add.ng-hide-add-active { + transform: translateX(240px); + -ms-transform: translateX(240px); + -webkit-transform: translateX(240px); + opacity: 0; +} +/* line 416, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-hide-remove { + transform: translateX(240px); + -ms-transform: translateX(240px); + -webkit-transform: translateX(240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 422, ../sass/ng-animation.scss */ +.bouncy-slide-right.ng-hide-remove.ng-hide-remove-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Bouncy Slide Left +/* ------------------------------------------- */ +/* line 434, ../sass/ng-animation.scss */ +.bouncy-slide-left { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 437, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-enter { + transform: translateX(-240px); + -ms-transform: translateX(-240px); + -webkit-transform: translateX(-240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 443, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-enter-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} +/* line 448, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-leave { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 454, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-leave-active { + transform: translateX(-240px); + -ms-transform: translateX(-240px); + -webkit-transform: translateX(-240px); + opacity: 0; +} +/* line 460, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-hide-add { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 465, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-hide-add.ng-hide-add-active { + transform: translateX(-240px); + -ms-transform: translateX(-240px); + -webkit-transform: translateX(-240px); + opacity: 0; +} +/* line 471, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-hide-remove { + transform: translateX(-240px); + -ms-transform: translateX(-240px); + -webkit-transform: translateX(-240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 477, ../sass/ng-animation.scss */ +.bouncy-slide-left.ng-hide-remove.ng-hide-remove-active { + transform: translateX(0); + -ms-transform: translateX(0); + -webkit-transform: translateX(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Bouncy Slide Down +/* ------------------------------------------- */ +/* line 488, ../sass/ng-animation.scss */ +.bouncy-slide-down { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 491, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-enter { + transform: translateY(-240px); + -ms-transform: translateY(-240px); + -webkit-transform: translateY(-240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 497, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-enter-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} +/* line 502, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-leave { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 508, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-leave-active { + transform: translateY(-240px); + -ms-transform: translateY(-240px); + -webkit-transform: translateY(-240px); + opacity: 0; +} +/* line 514, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-hide-add { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 519, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-hide-add.ng-hide-add-active { + transform: translateY(-240px); + -ms-transform: translateY(-240px); + -webkit-transform: translateY(-240px); + opacity: 0; +} +/* line 525, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-hide-remove { + transform: translateY(-240px); + -ms-transform: translateY(-240px); + -webkit-transform: translateY(-240px); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 531, ../sass/ng-animation.scss */ +.bouncy-slide-down.ng-hide-remove.ng-hide-remove-active { + transform: translateY(0); + -ms-transform: translateY(0); + -webkit-transform: translateY(0); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Scale Fade +/* ------------------------------------------- */ +/* line 544, ../sass/ng-animation.scss */ +.scale-fade { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 547, ../sass/ng-animation.scss */ +.scale-fade.ng-enter { + transform: scale(0.7); + -ms-transform: scale(0.7); + -webkit-transform: scale(0.7); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 553, ../sass/ng-animation.scss */ +.scale-fade.ng-enter-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} +/* line 558, ../sass/ng-animation.scss */ +.scale-fade.ng-leave { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 564, ../sass/ng-animation.scss */ +.scale-fade.ng-leave-active { + transform: scale(0.7); + -ms-transform: scale(0.7); + -webkit-transform: scale(0.7); + opacity: 0; +} +/* line 570, ../sass/ng-animation.scss */ +.scale-fade.ng-hide-add { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 575, ../sass/ng-animation.scss */ +.scale-fade.ng-hide-add.ng-hide-add-active { + transform: scale(0.7); + -ms-transform: scale(0.7); + -webkit-transform: scale(0.7); + opacity: 0; +} +/* line 581, ../sass/ng-animation.scss */ +.scale-fade.ng-hide-remove { + transform: scale(0.7); + -ms-transform: scale(0.7); + -webkit-transform: scale(0.7); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 587, ../sass/ng-animation.scss */ +.scale-fade.ng-hide-remove.ng-hide-remove-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Spin Fade +/* ------------------------------------------- */ +/* line 598, ../sass/ng-animation.scss */ +.spin-toggle { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 601, ../sass/ng-animation.scss */ +.spin-toggle.ng-enter { + transform: rotate(225deg); + -ms-transform: rotate(225deg); + -webkit-transform: rotate(225deg); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 607, ../sass/ng-animation.scss */ +.spin-toggle.ng-enter-active { + transform: rotate(0deg); + -ms-transform: rotate(0deg); + -webkit-transform: rotate(0deg); + opacity: 1; +} +/* line 612, ../sass/ng-animation.scss */ +.spin-toggle.ng-leave { + transform: rotate(0deg); + -ms-transform: rotate(0deg); + -webkit-transform: rotate(0deg); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 618, ../sass/ng-animation.scss */ +.spin-toggle.ng-leave-active { + transform: rotate(90deg); + -ms-transform: rotate(90deg); + -webkit-transform: rotate(90deg); + opacity: 0; +} +/* line 624, ../sass/ng-animation.scss */ +.spin-toggle.ng-hide-add { + transform: rotate(0deg); + -ms-transform: rotate(0deg); + -webkit-transform: rotate(0deg); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 629, ../sass/ng-animation.scss */ +.spin-toggle.ng-hide-add.ng-hide-add-active { + transform: rotate(90deg); + -ms-transform: rotate(90deg); + -webkit-transform: rotate(90deg); + opacity: 0; +} +/* line 635, ../sass/ng-animation.scss */ +.spin-toggle.ng-hide-remove { + transform: rotate(225deg); + -ms-transform: rotate(225deg); + -webkit-transform: rotate(225deg); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 641, ../sass/ng-animation.scss */ +.spin-toggle.ng-hide-remove.ng-hide-remove-active { + transform: rotate(0deg); + -ms-transform: rotate(0deg); + -webkit-transform: rotate(0deg); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Scale in Fade +/* ------------------------------------------- */ +/* line 653, ../sass/ng-animation.scss */ +.scale-fade-in { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 656, ../sass/ng-animation.scss */ +.scale-fade-in.ng-enter { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 0; +} +/* line 662, ../sass/ng-animation.scss */ +.scale-fade-in.ng-enter-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} +/* line 667, ../sass/ng-animation.scss */ +.scale-fade-in.ng-leave { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 673, ../sass/ng-animation.scss */ +.scale-fade-in.ng-leave-active { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + opacity: 0; +} +/* line 679, ../sass/ng-animation.scss */ +.scale-fade-in.ng-hide-add { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + opacity: 1; +} +/* line 684, ../sass/ng-animation.scss */ +.scale-fade-in.ng-hide-add.ng-hide-add-active { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + opacity: 0; +} +/* line 690, ../sass/ng-animation.scss */ +.scale-fade-in.ng-hide-remove { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + transition-duration: 250ms; + -webkit-transition-duration: 250ms; + display: block !important; + opacity: 0; +} +/* line 696, ../sass/ng-animation.scss */ +.scale-fade-in.ng-hide-remove.ng-hide-remove-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Bouncy Scale in Fade +/* ------------------------------------------- */ +/* line 708, ../sass/ng-animation.scss */ +.bouncy-scale-in { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 711, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-enter { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + transition-duration: 450ms; + -webkit-transition-duration: 450ms; + opacity: 0; +} +/* line 717, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-enter-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} +/* line 722, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-leave { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 450ms; + -webkit-transition-duration: 450ms; + opacity: 1; +} +/* line 728, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-leave-active { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + opacity: 0; +} +/* line 734, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-hide-add { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + transition-duration: 450ms; + -webkit-transition-duration: 450ms; + opacity: 1; +} +/* line 739, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-hide-add.ng-hide-add-active { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + opacity: 0; +} +/* line 745, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-hide-remove { + transform: scale(3); + -ms-transform: scale(3); + -webkit-transform: scale(3); + transition-duration: 450ms; + -webkit-transition-duration: 450ms; + display: block !important; + opacity: 0; +} +/* line 751, ../sass/ng-animation.scss */ +.bouncy-scale-in.ng-hide-remove.ng-hide-remove-active { + transform: scale(1); + -ms-transform: scale(1); + -webkit-transform: scale(1); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Flip In +/* ------------------------------------------- */ +/* line 763, ../sass/ng-animation.scss */ +.flip-in { + -webkit-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition: all 0 cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ + -webkit-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -moz-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -ms-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + -o-transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94); + /* easeOutQuad */ +} +/* line 766, ../sass/ng-animation.scss */ +.flip-in.ng-enter { + transform: perspective(300px) rotateX(90deg); + -ms-transform: perspective(300px) rotateX(90deg); + -webkit-transform: perspective(300px) rotateX(90deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 0.7; +} +/* line 772, ../sass/ng-animation.scss */ +.flip-in.ng-enter-active { + transform: perspective(300px) rotateX(0deg); + -ms-transform: perspective(300px) rotateX(0deg); + -webkit-transform: perspective(300px) rotateX(0deg); + opacity: 1; +} +/* line 777, ../sass/ng-animation.scss */ +.flip-in.ng-leave { + transform: perspective(300px) rotateX(0deg); + -ms-transform: perspective(300px) rotateX(0deg); + -webkit-transform: perspective(300px) rotateX(0deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 1; +} +/* line 783, ../sass/ng-animation.scss */ +.flip-in.ng-leave-active { + transform: perspective(300px) rotateX(135deg); + -ms-transform: perspective(300px) rotateX(135deg); + -webkit-transform: perspective(300px) rotateX(135deg); + opacity: 0.7; +} +/* line 789, ../sass/ng-animation.scss */ +.flip-in.ng-hide-add { + transform: perspective(300px) rotateX(0deg); + -ms-transform: perspective(300px) rotateX(0deg); + -webkit-transform: perspective(300px) rotateX(0deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 1; +} +/* line 794, ../sass/ng-animation.scss */ +.flip-in.ng-hide-add.ng-hide-add-active { + transform: perspective(300px) rotateX(135deg); + -ms-transform: perspective(300px) rotateX(135deg); + -webkit-transform: perspective(300px) rotateX(135deg); + opacity: 0; +} +/* line 800, ../sass/ng-animation.scss */ +.flip-in.ng-hide-remove { + transform: perspective(300px) rotateX(90deg); + -ms-transform: perspective(300px) rotateX(90deg); + -webkit-transform: perspective(300px) rotateX(90deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + display: block !important; + opacity: 0; +} +/* line 806, ../sass/ng-animation.scss */ +.flip-in.ng-hide-remove.ng-hide-remove-active { + transform: perspective(300px) rotateX(0deg); + -ms-transform: perspective(300px) rotateX(0deg); + -webkit-transform: perspective(300px) rotateX(0deg); + opacity: 1; +} + +/* ------------------------------------------- */ +/* Rotate In +/* ------------------------------------------- */ +/* line 817, ../sass/ng-animation.scss */ +.rotate-in { + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1); + /* older webkit */ + -webkit-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -moz-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -ms-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + -o-transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + transition: all 0 cubic-bezier(0.175, 0.885, 0.32, 1.275); + /* easeOutBack */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1); + /* older webkit */ + -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + transition-timing-function: cubic-bezier(0.175, 0.885, 0.45, 1.595); + /* custom */ +} +/* line 820, ../sass/ng-animation.scss */ +.rotate-in.ng-enter { + transform: perspective(300px) rotateY(40deg); + -ms-transform: perspective(300px) rotateY(40deg); + -webkit-transform: perspective(300px) rotateY(40deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 0.7; +} +/* line 826, ../sass/ng-animation.scss */ +.rotate-in.ng-enter-active { + transform: perspective(300px) rotateY(0deg); + -ms-transform: perspective(300px) rotateY(0deg); + -webkit-transform: perspective(300px) rotateY(0deg); + opacity: 1; +} +/* line 831, ../sass/ng-animation.scss */ +.rotate-in.ng-leave { + transform: perspective(300px) rotateY(0deg); + -ms-transform: perspective(300px) rotateY(0deg); + -webkit-transform: perspective(300px) rotateY(0deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 1; +} +/* line 837, ../sass/ng-animation.scss */ +.rotate-in.ng-leave-active { + transform: perspective(300px) rotateY(-40deg); + -ms-transform: perspective(300px) rotateY(-40deg); + -webkit-transform: perspective(300px) rotateY(-40deg); + opacity: 0.7; +} +/* line 843, ../sass/ng-animation.scss */ +.rotate-in.ng-hide-add { + transform: perspective(300px) rotateY(0deg); + -ms-transform: perspective(300px) rotateY(0deg); + -webkit-transform: perspective(300px) rotateY(0deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + opacity: 1; +} +/* line 848, ../sass/ng-animation.scss */ +.rotate-in.ng-hide-add.ng-hide-add-active { + transform: perspective(300px) rotateY(-40deg); + -ms-transform: perspective(300px) rotateY(-40deg); + -webkit-transform: perspective(300px) rotateY(-40deg); + opacity: 0; +} +/* line 854, ../sass/ng-animation.scss */ +.rotate-in.ng-hide-remove { + transform: perspective(300px) rotateY(40deg); + -ms-transform: perspective(300px) rotateY(40deg); + -webkit-transform: perspective(300px) rotateY(40deg); + transition-duration: 550ms; + -webkit-transition-duration: 550ms; + display: block !important; + opacity: 0; +} +/* line 860, ../sass/ng-animation.scss */ +.rotate-in.ng-hide-remove.ng-hide-remove-active { + transform: perspective(300px) rotateY(0deg); + -ms-transform: perspective(300px) rotateY(0deg); + -webkit-transform: perspective(300px) rotateY(0deg); + opacity: 1; +} \ No newline at end of file diff --git a/vendor/assets/stylesheets/xeditable.min.css b/vendor/assets/stylesheets/xeditable.min.css new file mode 100755 index 00000000..b06b395c --- /dev/null +++ b/vendor/assets/stylesheets/xeditable.min.css @@ -0,0 +1,7 @@ +/*! +angular-xeditable - 0.6.0 +Edit-in-place for angular.js +Build date: 2016-12-27 +*/ + +.editable-wrap{display:inline-block;white-space:pre;margin:0}.editable-wrap .editable-controls,.editable-wrap .editable-error{margin-bottom:0}.editable-wrap .editable-controls>input,.editable-wrap .editable-controls>select,.editable-wrap .editable-controls>textarea{margin-bottom:0}.editable-wrap .editable-input{display:inline-block}.editable-buttons{display:inline-block;vertical-align:top}.editable-buttons button{margin-left:5px}.editable-input.editable-has-buttons{width:auto}.editable-text{white-space:nowrap}.editable-bsdate{white-space:nowrap}.editable-bstime{white-space:nowrap}.editable-bstime .editable-input input[type=text]{width:46px}.editable-bstime .well-small{margin-bottom:0;padding:10px}.editable-range output{display:inline-block;min-width:30px;vertical-align:top;text-align:center}.editable-color input[type=color]{width:50px}.editable-checkbox label span,.editable-checklist label span,.editable-radiolist label span{margin-left:7px;margin-right:10px}.editable-hide{display:none!important}.editable-click,a.editable-click{text-decoration:none;color:#428bca;border-bottom:dashed 1px #428bca}.editable-click:hover,a.editable-click:hover{text-decoration:none;color:#2a6496;border-bottom-color:#2a6496}.editable-empty,.editable-empty:hover,.editable-empty:focus,a.editable-empty,a.editable-empty:hover,a.editable-empty:focus{font-style:italic;color:#D14;text-decoration:none}.popover-wrapper>a{display:inline!important}.popover-wrapper{display:inline;position:relative}.popover-wrapper form{position:absolute;top:-53px;background:#FFF;border:1px solid #AAA;border-radius:5px;padding:7px;width:auto;display:inline-block;left:50%;z-index:101}.popover-wrapper form:before{content:"";width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #AAA;position:absolute;bottom:-10px}.popover-wrapper form:after{content:"";width:0;height:0;border-left:9px solid transparent;border-right:9px solid transparent;border-top:9px solid #FFF;position:absolute;bottom:-9px}@media screen and (max-width:750px){.popover-wrapper form{margin-left:-60px}.popover-wrapper form:before{left:50px}.popover-wrapper form:after{left:51px}}@media screen and (min-width:750px){.popover-wrapper form{margin-left:-110px}.popover-wrapper form:before{left:100px}.popover-wrapper form:after{left:101px}} \ No newline at end of file