+ <%= 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 %>
+
+
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 @@
+
+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 @@
+
+
+
+
+
+
Edit Card
+
+
+
+
+
Members
+
+
{{ member.username }}
X
+
+
+
+
+
Activities
+
+
{{ a.user.username }} {{ a.activity }} on {{ a.created_at | date }}
+
+
+
+
+
+
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 @@
+
+
+
+
+
\ 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.
+ *
+ * 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
+ *
+ *
+ * @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
+ *
+ *
+ * @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
+ *
+ *
+ * @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
+ *
+ *
+ *
+ * @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"}
+ *
+ * @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.
+ *
+ *
+ *
+ * @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:
+ *
+ *
+ * @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.
+ *
+ *
+ *
+ * @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.
+ *
+ *
+ *
+ * @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.:
+ *
+ *
+ *
+ * - ** 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.
+ *
+ *
+ * // 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
+ *
+ *
+
+ * @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
+ *
+ *
+ *
+ * @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
+ *
+ *
+ * @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
+ *
+ *
+ * @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
+ *
+ *
+ * @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:
+ *
+ *
+ * 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:
+ *
+ *
+ * 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:
+ *
+ *
+ * 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
+ *
+ *
+ * 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:
+ *
+ *
+ *
+ * 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:
+ *