├── .rspec ├── .bundle └── config ├── lib ├── spree_searchkick.rb ├── spree_searchkick │ ├── version.rb │ ├── factories.rb │ └── engine.rb ├── generators │ └── spree_searchkick │ │ └── install │ │ └── install_generator.rb └── spree │ ├── core │ └── searchkick_filters.rb │ └── search │ └── searchkick.rb ├── app ├── views │ └── spree │ │ └── shared │ │ ├── _typeahead_search.erb │ │ ├── _filters.html.erb │ │ └── _es_filter.html.erb ├── models │ └── spree │ │ ├── property_decorator.rb │ │ ├── taxonomy_decorator.rb │ │ ├── order_decorator.rb │ │ └── product_decorator.rb ├── assets │ ├── javascripts │ │ └── spree │ │ │ ├── backend │ │ │ └── spree_searchkick.js │ │ │ └── frontend │ │ │ ├── spree_searchkick.js │ │ │ └── typeahead.bundle.js │ └── stylesheets │ │ └── spree │ │ ├── backend │ │ └── spree_searchkick.css │ │ └── frontend │ │ └── spree_searchkick.css ├── overrides │ ├── typeahead_search.rb │ └── spree │ │ └── admin │ │ ├── taxonomies │ │ └── _form │ │ │ └── add_filterable_to_taxonomy_form.html.erb.deface │ │ └── properties │ │ └── _form │ │ └── add_filterable_to_property_form.html.erb.deface ├── helpers │ └── spree │ │ └── products_helper_decorator.rb └── controllers │ └── spree │ └── products_controller_decorator.rb ├── .gitignore ├── db └── migrate │ ├── 20150819222417_add_filtrable_to_spree_taxonomies.rb │ └── 20151009155442_add_filterable_to_spree_property.rb ├── config ├── locales │ └── en.yml └── routes.rb ├── bin └── rails ├── spec ├── models │ └── spree │ │ ├── property_spec.rb │ │ ├── taxonomy_spec.rb │ │ ├── order_spec.rb │ │ └── product_spec.rb ├── routing │ └── spree │ │ └── products_routes_spec.rb ├── support │ └── elasticsearch.rb ├── controllers │ └── spree │ │ └── products_controller_spec.rb ├── lib │ └── spree │ │ └── search │ │ └── searchkick_spec.rb └── spec_helper.rb ├── Gemfile ├── .travis.yml ├── Rakefile ├── spree_searchkick.gemspec ├── LICENSE └── README.md /.rspec: -------------------------------------------------------------------------------- 1 | --color -------------------------------------------------------------------------------- /.bundle/config: -------------------------------------------------------------------------------- 1 | --- 2 | BUNDLE_JOBS: 8 3 | -------------------------------------------------------------------------------- /lib/spree_searchkick.rb: -------------------------------------------------------------------------------- 1 | require 'spree_core' 2 | require 'spree_searchkick/engine' 3 | -------------------------------------------------------------------------------- /lib/spree_searchkick/version.rb: -------------------------------------------------------------------------------- 1 | module SpreeSearchkick 2 | VERSION = '3.1.0'.freeze 3 | end 4 | -------------------------------------------------------------------------------- /app/views/spree/shared/_typeahead_search.erb: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | \#* 2 | *~ 3 | .#* 4 | .DS_Store 5 | .idea 6 | .project 7 | .sass-cache 8 | coverage 9 | Gemfile.lock 10 | tmp 11 | nbproject 12 | pkg 13 | *.swp 14 | spec/dummy 15 | -------------------------------------------------------------------------------- /app/models/spree/property_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::Property.class_eval do 2 | scope :filterable, -> { where(filterable: true) } 3 | 4 | def filter_name 5 | name.downcase.to_s 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/models/spree/taxonomy_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::Taxonomy.class_eval do 2 | scope :filterable, -> { where(filterable: true) } 3 | 4 | def filter_name 5 | "#{name.downcase}_ids" 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/assets/javascripts/spree/backend/spree_searchkick.js: -------------------------------------------------------------------------------- 1 | // Placeholder manifest file. 2 | // the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/backend/all.js' -------------------------------------------------------------------------------- /app/assets/stylesheets/spree/backend/spree_searchkick.css: -------------------------------------------------------------------------------- 1 | /* 2 | Placeholder manifest file. 3 | the installer will append this file to the app vendored assets here: 'vendor/assets/stylesheets/spree/backend/all.css' 4 | */ 5 | -------------------------------------------------------------------------------- /db/migrate/20150819222417_add_filtrable_to_spree_taxonomies.rb: -------------------------------------------------------------------------------- 1 | class AddFiltrableToSpreeTaxonomies < ActiveRecord::Migration[5.1] 2 | def change 3 | add_column :spree_taxonomies, :filterable, :boolean 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20151009155442_add_filterable_to_spree_property.rb: -------------------------------------------------------------------------------- 1 | class AddFilterableToSpreeProperty < ActiveRecord::Migration[5.1] 2 | def change 3 | add_column :spree_properties, :filterable, :boolean 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Sample localization file for English. Add more files in this directory for other locales. 2 | # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. 3 | 4 | en: 5 | hello: "Hello world" 6 | -------------------------------------------------------------------------------- /app/models/spree/order_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::Order.class_eval do 2 | Spree::Order.state_machine.after_transition to: :complete, do: :reindex_order_products 3 | 4 | def reindex_order_products 5 | return unless complete? 6 | products.map(&:reindex) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/overrides/typeahead_search.rb: -------------------------------------------------------------------------------- 1 | Deface::Override.new(virtual_path: 'spree/shared/_nav_bar', 2 | name: 'typeahead_search', 3 | insert_after: 'li#search-bar', 4 | partial: 'spree/shared/typeahead_search', 5 | disabled: false) 6 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Spree::Core::Engine.routes.draw do 2 | # Add your extension routes here 3 | get '/best', to: 'products#best_selling' 4 | get '/best/t/*id/', to: 'products#best_selling', as: :best_selling_taxon 5 | get '/autocomplete/products', to: 'products#autocomplete', as: :autocomplete 6 | end 7 | -------------------------------------------------------------------------------- /lib/spree_searchkick/factories.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | # Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them. 3 | # 4 | # Example adding this to your spec_helper will load these Factories for use: 5 | # require 'spree_searchkick/factories' 6 | end 7 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. 2 | 3 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 4 | ENGINE_PATH = File.expand_path('../../lib/spree_searchkick/engine', __FILE__) 5 | 6 | require 'rails/all' 7 | require 'rails/engine/commands' 8 | -------------------------------------------------------------------------------- /spec/models/spree/property_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | RSpec.describe Spree::Property, type: :model do 4 | describe '#filter_name' do 5 | let(:property) { create(:property, name: 'awesome_property') } 6 | 7 | it 'respond with property name downcased' do 8 | expect(property.filter_name).to eq('awesome_property') 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'spree', github: 'spree/spree' 4 | # Provides basic authentication functionality for testing parts of your engine 5 | gem 'spree_auth_devise', github: 'spree/spree_auth_devise' 6 | 7 | # Provides searchkick functionalities for testing 8 | gem 'searchkick', '>= 2.4.0' 9 | 10 | gem 'rails-controller-testing' 11 | 12 | gemspec 13 | -------------------------------------------------------------------------------- /spec/models/spree/taxonomy_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | RSpec.describe Spree::Taxonomy, type: :model do 4 | describe '#filter_name' do 5 | let(:taxonomy) { create(:taxonomy, name: 'awesome_category') } 6 | 7 | it 'respond with taxonomy name downcased' do 8 | expect(taxonomy.filter_name).to eq('awesome_category_ids') 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.3 4 | - 2.4 5 | addons: 6 | apt: 7 | sources: 8 | - elasticsearch-6.x 9 | packages: 10 | - elasticsearch 11 | services: 12 | - elasticsearch 13 | sudo: false 14 | cache: bundler 15 | before_script: 16 | - sh -e /etc/init.d/xvfb start 17 | - export DISPLAY=:99.0 18 | - bundle exec rake test_app 19 | script: 20 | - bundle exec rspec spec -------------------------------------------------------------------------------- /app/helpers/spree/products_helper_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::ProductsHelper.module_eval do 2 | def cache_key_for_products 3 | count = @products.count 4 | hash = Digest::SHA1.hexdigest(params.to_json) 5 | max_updated_at = @products.map(&:updated_at).max || Date.today 6 | "#{I18n.locale}/#{current_currency}/spree/products/all-#{params[:page]}-#{hash}-#{count}-#{max_updated_at.to_s(:number)}" 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/overrides/spree/admin/taxonomies/_form/add_filterable_to_taxonomy_form.html.erb.deface: -------------------------------------------------------------------------------- 1 | 2 | <%= f.field_container :filterable, class: ['form-group'] do %> 3 | <%= f.label :filterable, Spree.t(:filterable) %> * 4 | <%= error_message_on :taxonomy, :filterable, :class => 'error-message' %> 5 | <%= check_box :taxonomy, :filterable, :class => 'form-control' %> 6 | <% end %> 7 | -------------------------------------------------------------------------------- /app/overrides/spree/admin/properties/_form/add_filterable_to_property_form.html.erb.deface: -------------------------------------------------------------------------------- 1 | 2 |
3 | <%= f.field_container :filterable, class: ['form-group'] do %> 4 | <%= f.label :filterable, Spree.t(:filterable) %> * 5 | <%= error_message_on :property, :filterable, :class => 'error-message' %> 6 | <%= check_box :property, :filterable, :class => 'form-control' %> 7 | <% end %> 8 |
-------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler' 2 | Bundler::GemHelper.install_tasks 3 | 4 | require 'rspec/core/rake_task' 5 | require 'spree/testing_support/extension_rake' 6 | 7 | RSpec::Core::RakeTask.new 8 | 9 | task :default do 10 | if Dir['spec/dummy'].empty? 11 | Rake::Task[:test_app].invoke 12 | Dir.chdir('../../') 13 | end 14 | Rake::Task[:spec].invoke 15 | end 16 | 17 | desc 'Generates a dummy app for testing' 18 | task :test_app do 19 | ENV['LIB_NAME'] = 'spree_searchkick' 20 | Rake::Task['extension:test_app'].invoke 21 | end 22 | -------------------------------------------------------------------------------- /app/views/spree/shared/_filters.html.erb: -------------------------------------------------------------------------------- 1 | <% 2 | aggregations = @products.aggs 3 | filters = Spree::Core::SearchkickFilters.applicable_filters(aggregations) 4 | %> 5 | <%= form_tag '', :method => :get, :id => 'sidebar_products_search' do %> 6 | <%= hidden_field_tag 'per_page', params[:per_page] %> 7 | <% filters.each do |filter| %> 8 | <% next if filter[:options].empty? %> 9 | <%= render partial: "spree/shared/es_filter", locals: { filter: filter } %> 10 | <% end %> 11 | <%= submit_tag Spree.t(:search), :name => nil, :class => 'btn btn-primary' %> 12 | <% end %> -------------------------------------------------------------------------------- /app/views/spree/shared/_es_filter.html.erb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/models/spree/order_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | RSpec.describe Spree::Order, type: :model do 4 | describe '#reindex_order_products' do 5 | context 'when order is completed' do 6 | let(:order) { create(:completed_order_with_totals) } 7 | 8 | before(:each) do 9 | Spree::Product.searchkick_index.refresh 10 | Spree::Product.reindex 11 | end 12 | 13 | it 'reindex order items after transition to complete' do 14 | order.reindex_order_products 15 | product = order.products.first 16 | expect(product.search_data[:conversions]).to eq(1) 17 | end 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/controllers/spree/products_controller_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::ProductsController.class_eval do 2 | before_action :load_taxon, only: [:best_selling] 3 | 4 | # Sort by conversions desc 5 | def best_selling 6 | params.merge(taxon: @taxon.id) if @taxon 7 | @searcher = build_searcher(params.merge(conversions: true)) 8 | @products = @searcher.retrieve_products 9 | render action: :index 10 | end 11 | 12 | def autocomplete 13 | keywords = params[:keywords] ||= nil 14 | json = Spree::Product.autocomplete(keywords) 15 | render json: json 16 | end 17 | 18 | private 19 | 20 | def load_taxon 21 | @taxon = Spree::Taxon.friendly.find(params[:id]) if params[:id] 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /lib/spree_searchkick/engine.rb: -------------------------------------------------------------------------------- 1 | module SpreeSearchkick 2 | class Engine < Rails::Engine 3 | require 'spree/core' 4 | isolate_namespace Spree 5 | engine_name 'spree_searchkick' 6 | 7 | config.autoload_paths += %W[#{config.root}/lib] 8 | 9 | # use rspec for tests 10 | config.generators do |g| 11 | g.test_framework :rspec 12 | end 13 | 14 | def self.activate 15 | Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c| 16 | Rails.configuration.cache_classes ? require(c) : load(c) 17 | end 18 | Spree::Config.searcher_class = Spree::Search::Searchkick 19 | end 20 | 21 | config.to_prepare &method(:activate).to_proc 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /spec/routing/spree/products_routes_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | RSpec.describe Spree::ProductsController, type: :routing do 4 | describe 'routing' do 5 | routes { Spree::Core::Engine.routes } 6 | let(:taxon) { create(:taxon) } 7 | 8 | context 'best selling products' do 9 | it 'routes to #best_selling' do 10 | expect(get: best_path).to route_to(controller: 'spree/products', action: 'best_selling') 11 | end 12 | end 13 | 14 | context 'best selling products by taxon' do 15 | it 'routes to #create' do 16 | expect(get: best_selling_taxon_path(taxon.permalink)).to route_to(controller: 'spree/products', action: 'best_selling', id: taxon.permalink) 17 | end 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/assets/javascripts/spree/frontend/spree_searchkick.js: -------------------------------------------------------------------------------- 1 | // Placeholder manifest file. 2 | // the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js' 3 | //= require_tree . 4 | 5 | Spree.typeaheadSearch = function() { 6 | var products = new Bloodhound({ 7 | datumTokenizer: Bloodhound.tokenizers.whitespace, 8 | queryTokenizer: Bloodhound.tokenizers.whitespace, 9 | limit: 10, 10 | prefetch: Spree.pathFor('autocomplete/products.json'), 11 | remote: { 12 | url: Spree.pathFor('autocomplete/products.json?keywords=%25QUERY'), 13 | wildcard: '%QUERY' 14 | } 15 | }); 16 | 17 | products.initialize(); 18 | 19 | // passing in `null` for the `options` arguments will result in the default 20 | // options being used 21 | $('#keywords').typeahead({ 22 | minLength: 2, 23 | highlight: true 24 | }, { 25 | name: 'products', 26 | source: products 27 | }); 28 | } -------------------------------------------------------------------------------- /spec/models/spree/product_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | require 'pry' 3 | 4 | RSpec.describe Spree::Product, type: :model do 5 | describe 'searches' do 6 | let(:product) { create(:product) } 7 | 8 | it 'autocomplete by name' do 9 | keyword = product.name[0..6] 10 | Spree::Product.reindex 11 | expect(Spree::Product.autocomplete(keyword)).to eq([product.name.strip]) 12 | end 13 | 14 | context 'products that are not yet available' do 15 | let(:product) { create(:product, available_on: nil) } 16 | 17 | it 'does not return them in autocomplete' do 18 | keyword = product.name[0..6] 19 | Spree::Product.reindex 20 | expect(Spree::Product.autocomplete(keyword)).to eq([]) 21 | end 22 | end 23 | 24 | context 'products with no price' do 25 | let(:product) do 26 | create(:product).tap { |_| Spree::Price.update_all(amount: nil) } 27 | end 28 | 29 | it 'does not return them in autocomplete' do 30 | keyword = product.name[0..6] 31 | Spree::Product.reindex 32 | expect(Spree::Product.autocomplete(keyword)).to eq([]) 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /app/assets/stylesheets/spree/frontend/spree_searchkick.css: -------------------------------------------------------------------------------- 1 | /* 2 | Placeholder manifest file. 3 | the installer will append this file to the app vendored assets here: 'vendor/assets/stylesheets/spree/frontend/all.css' 4 | */ 5 | .tt-query { 6 | -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); 7 | -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); 8 | box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); 9 | } 10 | 11 | .tt-hint { 12 | color: #999 13 | } 14 | 15 | .tt-menu { 16 | width: 100%; 17 | margin-top: 4px; 18 | padding: 4px 0; 19 | background-color: #fff; 20 | border: 1px solid #ccc; 21 | border: 1px solid rgba(0, 0, 0, 0.2); 22 | -webkit-border-radius: 4px; 23 | -moz-border-radius: 4px; 24 | border-radius: 4px; 25 | -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2); 26 | -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2); 27 | box-shadow: 0 5px 10px rgba(0,0,0,.2); 28 | } 29 | 30 | .tt-suggestion { 31 | padding: 3px 20px; 32 | line-height: 24px; 33 | } 34 | 35 | .tt-suggestion.tt-cursor { 36 | color: #fff; 37 | background-color: #0097cf; 38 | 39 | } 40 | 41 | .tt-suggestion p { 42 | margin: 0; 43 | } 44 | 45 | .twitter-typeahead { 46 | width: 100%; 47 | } -------------------------------------------------------------------------------- /spec/support/elasticsearch.rb: -------------------------------------------------------------------------------- 1 | require 'elasticsearch/extensions/test/cluster' 2 | 3 | RSpec.configure do |config| 4 | unless ENV['CI'] 5 | config.before(:suite) { start_elastic_cluster } 6 | 7 | config.after(:suite) { stop_elastic_cluster } 8 | end 9 | 10 | SEARCHABLE_MODELS = [Spree::Product].freeze 11 | 12 | # create indices for searchable models 13 | config.before do 14 | SEARCHABLE_MODELS.each do |model| 15 | model.reindex 16 | model.searchkick_index.refresh 17 | end 18 | end 19 | 20 | # delete indices for searchable models to keep clean state between tests 21 | config.after do 22 | SEARCHABLE_MODELS.each do |model| 23 | model.searchkick_index.delete 24 | end 25 | end 26 | end 27 | 28 | def start_elastic_cluster 29 | ENV['TEST_CLUSTER_PORT'] = '9250' 30 | ENV['TEST_CLUSTER_NODES'] = '1' 31 | ENV['TEST_CLUSTER_NAME'] = 'spree_searchkick_test' 32 | 33 | ENV['ELASTICSEARCH_URL'] = "http://localhost:#{ENV['TEST_CLUSTER_PORT']}" 34 | 35 | return if Elasticsearch::Extensions::Test::Cluster.running? 36 | Elasticsearch::Extensions::Test::Cluster.start(timeout: 30) 37 | end 38 | 39 | def stop_elastic_cluster 40 | return unless Elasticsearch::Extensions::Test::Cluster.running? 41 | Elasticsearch::Extensions::Test::Cluster.stop 42 | end 43 | -------------------------------------------------------------------------------- /lib/generators/spree_searchkick/install/install_generator.rb: -------------------------------------------------------------------------------- 1 | module SpreeSearchkick 2 | module Generators 3 | class InstallGenerator < Rails::Generators::Base 4 | class_option :auto_run_migrations, type: :boolean, default: false 5 | 6 | def add_javascripts 7 | append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/spree_searchkick\n" 8 | append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/spree_searchkick\n" 9 | end 10 | 11 | def add_stylesheets 12 | inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/spree_searchkick\n", before: /\*\//, verbose: true 13 | inject_into_file 'vendor/assets/stylesheets/spree/backend/all.css', " *= require spree/backend/spree_searchkick\n", before: /\*\//, verbose: true 14 | end 15 | 16 | def add_migrations 17 | run 'bundle exec rake railties:install:migrations FROM=spree_searchkick' 18 | end 19 | 20 | def run_migrations 21 | run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask('Would you like to run the migrations now? [Y/n]')) 22 | if run_migrations 23 | run 'bundle exec rake db:migrate' 24 | else 25 | puts 'Skipping rake db:migrate, don\'t forget to run it!' 26 | end 27 | end 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/controllers/spree/products_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | require 'pry' 3 | 4 | RSpec.describe Spree::ProductsController, type: :controller do 5 | describe 'GET best_selling' do 6 | let(:order) { create(:completed_order_with_totals) } 7 | 8 | context 'when empty taxon' do 9 | it 'get from all products sort by conversions desc' do 10 | order.reindex_order_products 11 | spree_get :best_selling 12 | expect(assigns(:products)).to be_a(Searchkick::Results) 13 | end 14 | end 15 | 16 | context 'when best by taxon' do 17 | let(:taxon) { create(:taxon) } 18 | let(:regular_product) { create(:product, name: 'regular', taxons: [taxon]) } 19 | 20 | before(:each) do 21 | @product = order.products.sample 22 | regular_product.reindex 23 | taxon.products << @product 24 | Spree::Product.reindex 25 | end 26 | 27 | it 'sort by conversions desc' do 28 | order.reindex_order_products 29 | spree_get :best_selling, id: taxon 30 | 31 | expect(assigns(:products).map(&:name)).to eq [@product.name, 'regular'] 32 | end 33 | 34 | it 'get same products qty' do 35 | spree_get :best_selling, id: taxon 36 | 37 | expect(assigns(:products).count).to eq(2) 38 | end 39 | 40 | it 'return a Searchkick::Results' do 41 | spree_get :best_selling, id: taxon 42 | 43 | expect(assigns(:products)).to be_a(Searchkick::Results) 44 | end 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /spree_searchkick.gemspec: -------------------------------------------------------------------------------- 1 | 2 | require File.expand_path('../lib/spree_searchkick/version', __FILE__) 3 | 4 | Gem::Specification.new do |s| 5 | s.platform = Gem::Platform::RUBY 6 | s.name = 'spree_searchkick' 7 | s.version = SpreeSearchkick::VERSION 8 | s.summary = 'Add searchkick to spree' 9 | s.description = 'Filters, suggests, autocompletes, sortings, searches' 10 | s.required_ruby_version = '>= 2.0.0' 11 | 12 | s.author = 'Gonzalo Moreno' 13 | s.email = 'gmoreno@acid.cl' 14 | s.homepage = 'http://www.acid.cl' 15 | 16 | # s.files = `git ls-files`.split("\n") 17 | # s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") 18 | s.require_path = 'lib' 19 | s.requirements << 'none' 20 | 21 | s.add_dependency 'searchkick' 22 | s.add_dependency 'spree_core', '>= 3.1.0', '< 4.0' 23 | 24 | s.add_development_dependency 'better_errors' 25 | s.add_development_dependency 'binding_of_caller' 26 | s.add_development_dependency 'capybara' 27 | s.add_development_dependency 'coffee-rails' 28 | s.add_development_dependency 'database_cleaner' 29 | s.add_development_dependency 'elasticsearch-extensions' 30 | s.add_development_dependency 'factory_bot' 31 | s.add_development_dependency 'ffaker' 32 | s.add_development_dependency 'pry' 33 | s.add_development_dependency 'rspec-rails' 34 | s.add_development_dependency 'sass-rails' 35 | s.add_development_dependency 'selenium-webdriver' 36 | s.add_development_dependency 'simplecov' 37 | s.add_development_dependency 'sqlite3' 38 | end 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 [name of plugin creator] 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | * Neither the name Spree nor the names of its contributors may be used to 13 | endorse or promote products derived from this software without specific 14 | prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 20 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | -------------------------------------------------------------------------------- /lib/spree/core/searchkick_filters.rb: -------------------------------------------------------------------------------- 1 | module Spree 2 | module Core 3 | module SearchkickFilters 4 | def self.applicable_filters(aggregations) 5 | es_filters = [] 6 | Spree::Taxonomy.filterable.each do |taxonomy| 7 | es_filters << process_filter(taxonomy.filter_name, :taxon, aggregations[taxonomy.filter_name]) 8 | end 9 | 10 | Spree::Property.filterable.each do |property| 11 | es_filters << process_filter(property.filter_name, :property, aggregations[property.filter_name]) 12 | end 13 | 14 | es_filters.uniq 15 | end 16 | 17 | def self.process_filter(name, type, filter) 18 | options = [] 19 | case type 20 | when :price 21 | min = filter['buckets'].min_by { |a| a['key'] } 22 | max = filter['buckets'].max_by { |a| a['key'] } 23 | options = if min && max 24 | { min: min['key'].to_i, max: max['key'].to_i, step: 100 } 25 | else 26 | {} 27 | end 28 | when :taxon 29 | ids = filter['buckets'].map { |h| h['key'] } 30 | taxons = Spree::Taxon.where(id: ids).order(name: :asc) 31 | taxons.each { |t| options << { label: t.name, value: t.id } } 32 | when :property 33 | values = filter['buckets'].map { |h| h['key'] } 34 | values.each { |t| options << { label: t, value: t } } 35 | end 36 | 37 | { 38 | name: name, 39 | type: type, 40 | options: options 41 | } 42 | end 43 | 44 | def self.aggregation_term(aggregation) 45 | aggregation['buckets'].sort_by { |hsh| hsh['key'] } 46 | end 47 | end 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /lib/spree/search/searchkick.rb: -------------------------------------------------------------------------------- 1 | module Spree 2 | module Search 3 | class Searchkick < Spree::Core::Search::Base 4 | def retrieve_products 5 | @products = base_elasticsearch 6 | end 7 | 8 | def base_elasticsearch 9 | curr_page = page || 1 10 | Spree::Product.search( 11 | keyword_query, 12 | fields: Spree::Product.search_fields, 13 | where: where_query, 14 | aggs: aggregations, 15 | smart_aggs: true, 16 | order: sorted, 17 | page: curr_page, 18 | per_page: per_page 19 | ) 20 | end 21 | 22 | def where_query 23 | where_query = { 24 | active: true, 25 | currency: current_currency, 26 | price: { not: nil } 27 | } 28 | where_query[:taxon_ids] = taxon.id if taxon 29 | add_search_filters(where_query) 30 | end 31 | 32 | def keyword_query 33 | keywords.nil? || keywords.empty? ? '*' : keywords 34 | end 35 | 36 | def sorted 37 | order_params = {} 38 | order_params[:conversions] = :desc if conversions 39 | order_params 40 | end 41 | 42 | def aggregations 43 | fs = [] 44 | Spree::Taxonomy.filterable.each do |taxonomy| 45 | fs << taxonomy.filter_name.to_sym 46 | end 47 | Spree::Property.filterable.each do |property| 48 | fs << property.filter_name.to_sym 49 | end 50 | fs 51 | end 52 | 53 | def add_search_filters(query) 54 | return query unless search 55 | search.each do |name, scope_attribute| 56 | query.merge!(Hash[name, scope_attribute]) 57 | end 58 | query 59 | end 60 | 61 | def prepare(params) 62 | super 63 | @properties[:conversions] = params[:conversions] 64 | end 65 | end 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /app/models/spree/product_decorator.rb: -------------------------------------------------------------------------------- 1 | Spree::Product.class_eval do 2 | searchkick word_start: [:name], settings: { number_of_replicas: 0 } unless respond_to?(:searchkick_index) 3 | 4 | def self.autocomplete_fields 5 | [:name] 6 | end 7 | 8 | def self.search_fields 9 | [:name] 10 | end 11 | 12 | def search_data 13 | json = { 14 | name: name, 15 | description: description, 16 | active: available?, 17 | created_at: created_at, 18 | updated_at: updated_at, 19 | price: price, 20 | currency: currency, 21 | conversions: orders.complete.count, 22 | taxon_ids: taxon_and_ancestors.map(&:id), 23 | taxon_names: taxon_and_ancestors.map(&:name) 24 | } 25 | 26 | Spree::Property.all.each do |prop| 27 | json.merge!(Hash[prop.name.downcase, property(prop.name)]) 28 | end 29 | 30 | Spree::Taxonomy.all.each do |taxonomy| 31 | json.merge!(Hash["#{taxonomy.name.downcase}_ids", taxon_by_taxonomy(taxonomy.id).map(&:id)]) 32 | end 33 | 34 | json 35 | end 36 | 37 | def taxon_by_taxonomy(taxonomy_id) 38 | taxons.joins(:taxonomy).where(spree_taxonomies: { id: taxonomy_id }) 39 | end 40 | 41 | def self.autocomplete(keywords) 42 | if keywords 43 | Spree::Product.search( 44 | keywords, 45 | fields: autocomplete_fields, 46 | match: :word_start, 47 | limit: 10, 48 | load: false, 49 | misspellings: { below: 3 }, 50 | where: search_where 51 | ).map(&:name).map(&:strip).uniq 52 | else 53 | Spree::Product.search( 54 | '*', 55 | fields: autocomplete_fields, 56 | load: false, 57 | misspellings: { below: 3 }, 58 | where: search_where 59 | ).map(&:name).map(&:strip) 60 | end 61 | end 62 | 63 | def self.search_where 64 | { 65 | active: true, 66 | price: { not: nil } 67 | } 68 | end 69 | end 70 | -------------------------------------------------------------------------------- /spec/lib/spree/search/searchkick_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | describe Spree::Search::Searchkick do 3 | let(:product) { create(:product) } 4 | 5 | before do 6 | product.reindex 7 | Spree::Product.reindex 8 | end 9 | 10 | describe '#retrieve_products' do 11 | context 'when search by keyword' do 12 | subject(:products) { Spree::Search::Searchkick.new(keywords: keywords).retrieve_products } 13 | 14 | let(:keywords) { product.name } 15 | 16 | it { expect(products.count).to eq(1) } 17 | 18 | context 'when product searchable by description' do 19 | let(:keywords) { product.description } 20 | 21 | before { allow(Spree::Product).to receive(:search_fields).and_return([:description]) } 22 | 23 | it { expect(products.count).to eq(1) } 24 | end 25 | end 26 | 27 | it 'returns matching products' do 28 | products = Spree::Search::Searchkick.new({}).retrieve_products 29 | expect(products.count).to eq 1 30 | end 31 | 32 | describe 'aggregations' do 33 | let(:taxonomy) { Spree::Taxonomy.where(id: 1, name: 'Category').first_or_create } 34 | 35 | before do 36 | product.taxons << taxonomy.root 37 | product.reindex 38 | Spree::Product.reindex 39 | end 40 | 41 | it 'has no aggregations by default' do 42 | products = Spree::Search::Searchkick.new({}).retrieve_products 43 | expect(products.aggs).to be_nil 44 | end 45 | 46 | context 'with a filterable taxonomy' do 47 | let(:taxonomy) { Spree::Taxonomy.where(id: 1, name: 'Category', filterable: true).first_or_create } 48 | 49 | it 'retrieves aggregations' do 50 | products = Spree::Search::Searchkick.new({}).retrieve_products 51 | 52 | expect(products.count).to eq 1 53 | expect(products.aggs['category_ids']).to include('doc_count' => 1) 54 | expect(products.aggs['category_ids']['buckets']).to be_a Array 55 | end 56 | end 57 | end 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Spree + Searchkick 2 | =============== 3 | 4 | [![Build Status](https://travis-ci.org/ronzalo/spree_searchkick.svg?branch=master)](https://travis-ci.org/ronzalo/spree_searchkick) 5 | 6 | Add [Elasticsearch](http://elastic.co) goodies to Spree, powered by [searchkick](http://searchkick.org) 7 | 8 | Features 9 | -------- 10 | 11 | * Full search (keyword, in_taxon) 12 | * Taxons Aggregations (aggs) 13 | * Search Autocomplete ([Typeahead](https://twitter.github.io/typeahead.js/)) 14 | * Added `/best` route, where best selling products are boosted in first page 15 | 16 | 17 | Installation 18 | ------------ 19 | 20 | Add searchkick and spree_searchkick to your Gemfile: 21 | 22 | ```ruby 23 | gem 'searchkick' 24 | gem 'spree_searchkick', github: 'ronzalo/spree_searchkick', branch: '3-1-stable' 25 | ``` 26 | 27 | Bundle your dependencies and run the installation generator: 28 | 29 | ```shell 30 | bundle 31 | bundle exec rails g spree_searchkick:install 32 | bundle exec rails searchkick:reindex:all 33 | ``` 34 | 35 | [Install elasticsearch](https://www.elastic.co/downloads/elasticsearch) 36 | 37 | Documentation 38 | ------------- 39 | 40 | By default, only the `Spree::Product` class is indexed and to control what data is indexed, override `Spree::Product#search_data` method. Call `Spree::Product.reindex` after changing this method. 41 | 42 | To enable or disable taxons filters, go to taxonomy form and change `filterable` boolean. 43 | 44 | Testing 45 | ------- 46 | 47 | First bundle your dependencies, then run `rake`. `rake` will default to building the dummy app if it does not exist, then it will run specs. The dummy app can be regenerated by using `rake test_app`. 48 | 49 | ```shell 50 | bundle 51 | bundle exec rake 52 | ``` 53 | 54 | When testing your applications integration with this extension you may use it's factories. 55 | Simply add this require statement to your spec_helper: 56 | 57 | ```ruby 58 | require 'spree_searchkick/factories' 59 | ``` 60 | 61 | Copyright (c) 2015 Gonzalo Moreno, released under the New BSD License 62 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # Run Coverage report 2 | require 'simplecov' 3 | SimpleCov.start do 4 | add_filter 'spec/dummy' 5 | add_group 'Controllers', 'app/controllers' 6 | add_group 'Helpers', 'app/helpers' 7 | add_group 'Mailers', 'app/mailers' 8 | add_group 'Models', 'app/models' 9 | add_group 'Views', 'app/views' 10 | add_group 'Libraries', 'lib' 11 | end 12 | 13 | # Configure Rails Environment 14 | ENV['RAILS_ENV'] = 'test' 15 | 16 | require File.expand_path('../dummy/config/environment.rb', __FILE__) 17 | 18 | require 'rspec/rails' 19 | require 'database_cleaner' 20 | require 'ffaker' 21 | 22 | # Requires supporting ruby files with custom matchers and macros, etc, 23 | # in spec/support/ and its subdirectories. 24 | Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f } 25 | 26 | # Requires factories and other useful helpers defined in spree_core. 27 | require 'spree/testing_support/authorization_helpers' 28 | require 'spree/testing_support/capybara_ext' 29 | require 'spree/testing_support/controller_requests' 30 | require 'spree/testing_support/factories' 31 | require 'spree/testing_support/url_helpers' 32 | 33 | # Requires factories defined in lib/spree_searchkick/factories.rb 34 | require 'spree_searchkick/factories' 35 | 36 | RSpec.configure do |config| 37 | config.include FactoryBot::Syntax::Methods 38 | config.include Devise::Test::ControllerHelpers, type: :controller 39 | # Infer an example group's spec type from the file location. 40 | config.infer_spec_type_from_file_location! 41 | 42 | # == URL Helpers 43 | # 44 | # Allows access to Spree's routes in specs: 45 | # 46 | # visit spree.admin_path 47 | # current_path.should eql(spree.products_path) 48 | config.include Spree::TestingSupport::ControllerRequests, type: :controller 49 | config.include Spree::TestingSupport::UrlHelpers 50 | config.include Spree::TestingSupport::AuthorizationHelpers 51 | 52 | # == Mock Framework 53 | # 54 | # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: 55 | # 56 | # config.mock_with :mocha 57 | # config.mock_with :flexmock 58 | # config.mock_with :rr 59 | config.mock_with :rspec 60 | config.color = true 61 | 62 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 63 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 64 | 65 | # Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner 66 | # to cleanup after each test instead. Without transactional fixtures set to false the records created 67 | # to setup a test will be unavailable to the browser, which runs under a separate server instance. 68 | config.use_transactional_fixtures = false 69 | 70 | # Ensure Suite is set to use transactions for speed. 71 | config.before :suite do 72 | DatabaseCleaner.strategy = :transaction 73 | DatabaseCleaner.clean_with :truncation 74 | end 75 | 76 | # Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary. 77 | config.before :each do 78 | DatabaseCleaner.strategy = RSpec.current_example.metadata[:js] ? :truncation : :transaction 79 | DatabaseCleaner.start 80 | end 81 | 82 | # After each spec clean the database. 83 | config.after :each do 84 | DatabaseCleaner.clean 85 | end 86 | 87 | config.fail_fast = ENV['FAIL_FAST'] || false 88 | config.order = 'random' 89 | end 90 | -------------------------------------------------------------------------------- /app/assets/javascripts/spree/frontend/typeahead.bundle.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * typeahead.js 1.1.1 3 | * https://github.com/twitter/typeahead.js 4 | * Copyright 2013-2017 Twitter, Inc. and other contributors; Licensed MIT 5 | */ 6 | 7 | 8 | (function(root, factory) { 9 | if (typeof define === "function" && define.amd) { 10 | define([ "jquery" ], function(a0) { 11 | return root["Bloodhound"] = factory(a0); 12 | }); 13 | } else if (typeof module === "object" && module.exports) { 14 | module.exports = factory(require("jquery")); 15 | } else { 16 | root["Bloodhound"] = factory(root["jQuery"]); 17 | } 18 | })(this, function($) { 19 | var _ = function() { 20 | "use strict"; 21 | return { 22 | isMsie: function() { 23 | return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; 24 | }, 25 | isBlankString: function(str) { 26 | return !str || /^\s*$/.test(str); 27 | }, 28 | escapeRegExChars: function(str) { 29 | return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 30 | }, 31 | isString: function(obj) { 32 | return typeof obj === "string"; 33 | }, 34 | isNumber: function(obj) { 35 | return typeof obj === "number"; 36 | }, 37 | isArray: $.isArray, 38 | isFunction: $.isFunction, 39 | isObject: $.isPlainObject, 40 | isUndefined: function(obj) { 41 | return typeof obj === "undefined"; 42 | }, 43 | isElement: function(obj) { 44 | return !!(obj && obj.nodeType === 1); 45 | }, 46 | isJQuery: function(obj) { 47 | return obj instanceof $; 48 | }, 49 | toStr: function toStr(s) { 50 | return _.isUndefined(s) || s === null ? "" : s + ""; 51 | }, 52 | bind: $.proxy, 53 | each: function(collection, cb) { 54 | $.each(collection, reverseArgs); 55 | function reverseArgs(index, value) { 56 | return cb(value, index); 57 | } 58 | }, 59 | map: $.map, 60 | filter: $.grep, 61 | every: function(obj, test) { 62 | var result = true; 63 | if (!obj) { 64 | return result; 65 | } 66 | $.each(obj, function(key, val) { 67 | if (!(result = test.call(null, val, key, obj))) { 68 | return false; 69 | } 70 | }); 71 | return !!result; 72 | }, 73 | some: function(obj, test) { 74 | var result = false; 75 | if (!obj) { 76 | return result; 77 | } 78 | $.each(obj, function(key, val) { 79 | if (result = test.call(null, val, key, obj)) { 80 | return false; 81 | } 82 | }); 83 | return !!result; 84 | }, 85 | mixin: $.extend, 86 | identity: function(x) { 87 | return x; 88 | }, 89 | clone: function(obj) { 90 | return $.extend(true, {}, obj); 91 | }, 92 | getIdGenerator: function() { 93 | var counter = 0; 94 | return function() { 95 | return counter++; 96 | }; 97 | }, 98 | templatify: function templatify(obj) { 99 | return $.isFunction(obj) ? obj : template; 100 | function template() { 101 | return String(obj); 102 | } 103 | }, 104 | defer: function(fn) { 105 | setTimeout(fn, 0); 106 | }, 107 | debounce: function(func, wait, immediate) { 108 | var timeout, result; 109 | return function() { 110 | var context = this, args = arguments, later, callNow; 111 | later = function() { 112 | timeout = null; 113 | if (!immediate) { 114 | result = func.apply(context, args); 115 | } 116 | }; 117 | callNow = immediate && !timeout; 118 | clearTimeout(timeout); 119 | timeout = setTimeout(later, wait); 120 | if (callNow) { 121 | result = func.apply(context, args); 122 | } 123 | return result; 124 | }; 125 | }, 126 | throttle: function(func, wait) { 127 | var context, args, timeout, result, previous, later; 128 | previous = 0; 129 | later = function() { 130 | previous = new Date(); 131 | timeout = null; 132 | result = func.apply(context, args); 133 | }; 134 | return function() { 135 | var now = new Date(), remaining = wait - (now - previous); 136 | context = this; 137 | args = arguments; 138 | if (remaining <= 0) { 139 | clearTimeout(timeout); 140 | timeout = null; 141 | previous = now; 142 | result = func.apply(context, args); 143 | } else if (!timeout) { 144 | timeout = setTimeout(later, remaining); 145 | } 146 | return result; 147 | }; 148 | }, 149 | stringify: function(val) { 150 | return _.isString(val) ? val : JSON.stringify(val); 151 | }, 152 | guid: function() { 153 | function _p8(s) { 154 | var p = (Math.random().toString(16) + "000000000").substr(2, 8); 155 | return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p; 156 | } 157 | return "tt-" + _p8() + _p8(true) + _p8(true) + _p8(); 158 | }, 159 | noop: function() {} 160 | }; 161 | }(); 162 | var VERSION = "1.1.1"; 163 | var tokenizers = function() { 164 | "use strict"; 165 | return { 166 | nonword: nonword, 167 | whitespace: whitespace, 168 | ngram: ngram, 169 | obj: { 170 | nonword: getObjTokenizer(nonword), 171 | whitespace: getObjTokenizer(whitespace), 172 | ngram: getObjTokenizer(ngram) 173 | } 174 | }; 175 | function whitespace(str) { 176 | str = _.toStr(str); 177 | return str ? str.split(/\s+/) : []; 178 | } 179 | function nonword(str) { 180 | str = _.toStr(str); 181 | return str ? str.split(/\W+/) : []; 182 | } 183 | function ngram(str) { 184 | str = _.toStr(str); 185 | var tokens = [], word = ""; 186 | _.each(str.split(""), function(char) { 187 | if (char.match(/\s+/)) { 188 | word = ""; 189 | } else { 190 | tokens.push(word + char); 191 | word += char; 192 | } 193 | }); 194 | return tokens; 195 | } 196 | function getObjTokenizer(tokenizer) { 197 | return function setKey(keys) { 198 | keys = _.isArray(keys) ? keys : [].slice.call(arguments, 0); 199 | return function tokenize(o) { 200 | var tokens = []; 201 | _.each(keys, function(k) { 202 | tokens = tokens.concat(tokenizer(_.toStr(o[k]))); 203 | }); 204 | return tokens; 205 | }; 206 | }; 207 | } 208 | }(); 209 | var LruCache = function() { 210 | "use strict"; 211 | function LruCache(maxSize) { 212 | this.maxSize = _.isNumber(maxSize) ? maxSize : 100; 213 | this.reset(); 214 | if (this.maxSize <= 0) { 215 | this.set = this.get = $.noop; 216 | } 217 | } 218 | _.mixin(LruCache.prototype, { 219 | set: function set(key, val) { 220 | var tailItem = this.list.tail, node; 221 | if (this.size >= this.maxSize) { 222 | this.list.remove(tailItem); 223 | delete this.hash[tailItem.key]; 224 | this.size--; 225 | } 226 | if (node = this.hash[key]) { 227 | node.val = val; 228 | this.list.moveToFront(node); 229 | } else { 230 | node = new Node(key, val); 231 | this.list.add(node); 232 | this.hash[key] = node; 233 | this.size++; 234 | } 235 | }, 236 | get: function get(key) { 237 | var node = this.hash[key]; 238 | if (node) { 239 | this.list.moveToFront(node); 240 | return node.val; 241 | } 242 | }, 243 | reset: function reset() { 244 | this.size = 0; 245 | this.hash = {}; 246 | this.list = new List(); 247 | } 248 | }); 249 | function List() { 250 | this.head = this.tail = null; 251 | } 252 | _.mixin(List.prototype, { 253 | add: function add(node) { 254 | if (this.head) { 255 | node.next = this.head; 256 | this.head.prev = node; 257 | } 258 | this.head = node; 259 | this.tail = this.tail || node; 260 | }, 261 | remove: function remove(node) { 262 | node.prev ? node.prev.next = node.next : this.head = node.next; 263 | node.next ? node.next.prev = node.prev : this.tail = node.prev; 264 | }, 265 | moveToFront: function(node) { 266 | this.remove(node); 267 | this.add(node); 268 | } 269 | }); 270 | function Node(key, val) { 271 | this.key = key; 272 | this.val = val; 273 | this.prev = this.next = null; 274 | } 275 | return LruCache; 276 | }(); 277 | var PersistentStorage = function() { 278 | "use strict"; 279 | var LOCAL_STORAGE; 280 | try { 281 | LOCAL_STORAGE = window.localStorage; 282 | LOCAL_STORAGE.setItem("~~~", "!"); 283 | LOCAL_STORAGE.removeItem("~~~"); 284 | } catch (err) { 285 | LOCAL_STORAGE = null; 286 | } 287 | function PersistentStorage(namespace, override) { 288 | this.prefix = [ "__", namespace, "__" ].join(""); 289 | this.ttlKey = "__ttl__"; 290 | this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix)); 291 | this.ls = override || LOCAL_STORAGE; 292 | !this.ls && this._noop(); 293 | } 294 | _.mixin(PersistentStorage.prototype, { 295 | _prefix: function(key) { 296 | return this.prefix + key; 297 | }, 298 | _ttlKey: function(key) { 299 | return this._prefix(key) + this.ttlKey; 300 | }, 301 | _noop: function() { 302 | this.get = this.set = this.remove = this.clear = this.isExpired = _.noop; 303 | }, 304 | _safeSet: function(key, val) { 305 | try { 306 | this.ls.setItem(key, val); 307 | } catch (err) { 308 | if (err.name === "QuotaExceededError") { 309 | this.clear(); 310 | this._noop(); 311 | } 312 | } 313 | }, 314 | get: function(key) { 315 | if (this.isExpired(key)) { 316 | this.remove(key); 317 | } 318 | return decode(this.ls.getItem(this._prefix(key))); 319 | }, 320 | set: function(key, val, ttl) { 321 | if (_.isNumber(ttl)) { 322 | this._safeSet(this._ttlKey(key), encode(now() + ttl)); 323 | } else { 324 | this.ls.removeItem(this._ttlKey(key)); 325 | } 326 | return this._safeSet(this._prefix(key), encode(val)); 327 | }, 328 | remove: function(key) { 329 | this.ls.removeItem(this._ttlKey(key)); 330 | this.ls.removeItem(this._prefix(key)); 331 | return this; 332 | }, 333 | clear: function() { 334 | var i, keys = gatherMatchingKeys(this.keyMatcher); 335 | for (i = keys.length; i--; ) { 336 | this.remove(keys[i]); 337 | } 338 | return this; 339 | }, 340 | isExpired: function(key) { 341 | var ttl = decode(this.ls.getItem(this._ttlKey(key))); 342 | return _.isNumber(ttl) && now() > ttl ? true : false; 343 | } 344 | }); 345 | return PersistentStorage; 346 | function now() { 347 | return new Date().getTime(); 348 | } 349 | function encode(val) { 350 | return JSON.stringify(_.isUndefined(val) ? null : val); 351 | } 352 | function decode(val) { 353 | return $.parseJSON(val); 354 | } 355 | function gatherMatchingKeys(keyMatcher) { 356 | var i, key, keys = [], len = LOCAL_STORAGE.length; 357 | for (i = 0; i < len; i++) { 358 | if ((key = LOCAL_STORAGE.key(i)).match(keyMatcher)) { 359 | keys.push(key.replace(keyMatcher, "")); 360 | } 361 | } 362 | return keys; 363 | } 364 | }(); 365 | var Transport = function() { 366 | "use strict"; 367 | var pendingRequestsCount = 0, pendingRequests = {}, sharedCache = new LruCache(10); 368 | function Transport(o) { 369 | o = o || {}; 370 | this.maxPendingRequests = o.maxPendingRequests || 6; 371 | this.cancelled = false; 372 | this.lastReq = null; 373 | this._send = o.transport; 374 | this._get = o.limiter ? o.limiter(this._get) : this._get; 375 | this._cache = o.cache === false ? new LruCache(0) : sharedCache; 376 | } 377 | Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { 378 | this.maxPendingRequests = num; 379 | }; 380 | Transport.resetCache = function resetCache() { 381 | sharedCache.reset(); 382 | }; 383 | _.mixin(Transport.prototype, { 384 | _fingerprint: function fingerprint(o) { 385 | o = o || {}; 386 | return o.url + o.type + $.param(o.data || {}); 387 | }, 388 | _get: function(o, cb) { 389 | var that = this, fingerprint, jqXhr; 390 | fingerprint = this._fingerprint(o); 391 | if (this.cancelled || fingerprint !== this.lastReq) { 392 | return; 393 | } 394 | if (jqXhr = pendingRequests[fingerprint]) { 395 | jqXhr.done(done).fail(fail); 396 | } else if (pendingRequestsCount < this.maxPendingRequests) { 397 | pendingRequestsCount++; 398 | pendingRequests[fingerprint] = this._send(o).done(done).fail(fail).always(always); 399 | } else { 400 | this.onDeckRequestArgs = [].slice.call(arguments, 0); 401 | } 402 | function done(resp) { 403 | cb(null, resp); 404 | that._cache.set(fingerprint, resp); 405 | } 406 | function fail() { 407 | cb(true); 408 | } 409 | function always() { 410 | pendingRequestsCount--; 411 | delete pendingRequests[fingerprint]; 412 | if (that.onDeckRequestArgs) { 413 | that._get.apply(that, that.onDeckRequestArgs); 414 | that.onDeckRequestArgs = null; 415 | } 416 | } 417 | }, 418 | get: function(o, cb) { 419 | var resp, fingerprint; 420 | cb = cb || $.noop; 421 | o = _.isString(o) ? { 422 | url: o 423 | } : o || {}; 424 | fingerprint = this._fingerprint(o); 425 | this.cancelled = false; 426 | this.lastReq = fingerprint; 427 | if (resp = this._cache.get(fingerprint)) { 428 | cb(null, resp); 429 | } else { 430 | this._get(o, cb); 431 | } 432 | }, 433 | cancel: function() { 434 | this.cancelled = true; 435 | } 436 | }); 437 | return Transport; 438 | }(); 439 | var SearchIndex = window.SearchIndex = function() { 440 | "use strict"; 441 | var CHILDREN = "c", IDS = "i"; 442 | function SearchIndex(o) { 443 | o = o || {}; 444 | if (!o.datumTokenizer || !o.queryTokenizer) { 445 | $.error("datumTokenizer and queryTokenizer are both required"); 446 | } 447 | this.identify = o.identify || _.stringify; 448 | this.datumTokenizer = o.datumTokenizer; 449 | this.queryTokenizer = o.queryTokenizer; 450 | this.matchAnyQueryToken = o.matchAnyQueryToken; 451 | this.reset(); 452 | } 453 | _.mixin(SearchIndex.prototype, { 454 | bootstrap: function bootstrap(o) { 455 | this.datums = o.datums; 456 | this.trie = o.trie; 457 | }, 458 | add: function(data) { 459 | var that = this; 460 | data = _.isArray(data) ? data : [ data ]; 461 | _.each(data, function(datum) { 462 | var id, tokens; 463 | that.datums[id = that.identify(datum)] = datum; 464 | tokens = normalizeTokens(that.datumTokenizer(datum)); 465 | _.each(tokens, function(token) { 466 | var node, chars, ch; 467 | node = that.trie; 468 | chars = token.split(""); 469 | while (ch = chars.shift()) { 470 | node = node[CHILDREN][ch] || (node[CHILDREN][ch] = newNode()); 471 | node[IDS].push(id); 472 | } 473 | }); 474 | }); 475 | }, 476 | get: function get(ids) { 477 | var that = this; 478 | return _.map(ids, function(id) { 479 | return that.datums[id]; 480 | }); 481 | }, 482 | search: function search(query) { 483 | var that = this, tokens, matches; 484 | tokens = normalizeTokens(this.queryTokenizer(query)); 485 | _.each(tokens, function(token) { 486 | var node, chars, ch, ids; 487 | if (matches && matches.length === 0 && !that.matchAnyQueryToken) { 488 | return false; 489 | } 490 | node = that.trie; 491 | chars = token.split(""); 492 | while (node && (ch = chars.shift())) { 493 | node = node[CHILDREN][ch]; 494 | } 495 | if (node && chars.length === 0) { 496 | ids = node[IDS].slice(0); 497 | matches = matches ? getIntersection(matches, ids) : ids; 498 | } else { 499 | if (!that.matchAnyQueryToken) { 500 | matches = []; 501 | return false; 502 | } 503 | } 504 | }); 505 | return matches ? _.map(unique(matches), function(id) { 506 | return that.datums[id]; 507 | }) : []; 508 | }, 509 | all: function all() { 510 | var values = []; 511 | for (var key in this.datums) { 512 | values.push(this.datums[key]); 513 | } 514 | return values; 515 | }, 516 | reset: function reset() { 517 | this.datums = {}; 518 | this.trie = newNode(); 519 | }, 520 | serialize: function serialize() { 521 | return { 522 | datums: this.datums, 523 | trie: this.trie 524 | }; 525 | } 526 | }); 527 | return SearchIndex; 528 | function normalizeTokens(tokens) { 529 | tokens = _.filter(tokens, function(token) { 530 | return !!token; 531 | }); 532 | tokens = _.map(tokens, function(token) { 533 | return token.toLowerCase(); 534 | }); 535 | return tokens; 536 | } 537 | function newNode() { 538 | var node = {}; 539 | node[IDS] = []; 540 | node[CHILDREN] = {}; 541 | return node; 542 | } 543 | function unique(array) { 544 | var seen = {}, uniques = []; 545 | for (var i = 0, len = array.length; i < len; i++) { 546 | if (!seen[array[i]]) { 547 | seen[array[i]] = true; 548 | uniques.push(array[i]); 549 | } 550 | } 551 | return uniques; 552 | } 553 | function getIntersection(arrayA, arrayB) { 554 | var ai = 0, bi = 0, intersection = []; 555 | arrayA = arrayA.sort(); 556 | arrayB = arrayB.sort(); 557 | var lenArrayA = arrayA.length, lenArrayB = arrayB.length; 558 | while (ai < lenArrayA && bi < lenArrayB) { 559 | if (arrayA[ai] < arrayB[bi]) { 560 | ai++; 561 | } else if (arrayA[ai] > arrayB[bi]) { 562 | bi++; 563 | } else { 564 | intersection.push(arrayA[ai]); 565 | ai++; 566 | bi++; 567 | } 568 | } 569 | return intersection; 570 | } 571 | }(); 572 | var Prefetch = function() { 573 | "use strict"; 574 | var keys; 575 | keys = { 576 | data: "data", 577 | protocol: "protocol", 578 | thumbprint: "thumbprint" 579 | }; 580 | function Prefetch(o) { 581 | this.url = o.url; 582 | this.ttl = o.ttl; 583 | this.cache = o.cache; 584 | this.prepare = o.prepare; 585 | this.transform = o.transform; 586 | this.transport = o.transport; 587 | this.thumbprint = o.thumbprint; 588 | this.storage = new PersistentStorage(o.cacheKey); 589 | } 590 | _.mixin(Prefetch.prototype, { 591 | _settings: function settings() { 592 | return { 593 | url: this.url, 594 | type: "GET", 595 | dataType: "json" 596 | }; 597 | }, 598 | store: function store(data) { 599 | if (!this.cache) { 600 | return; 601 | } 602 | this.storage.set(keys.data, data, this.ttl); 603 | this.storage.set(keys.protocol, location.protocol, this.ttl); 604 | this.storage.set(keys.thumbprint, this.thumbprint, this.ttl); 605 | }, 606 | fromCache: function fromCache() { 607 | var stored = {}, isExpired; 608 | if (!this.cache) { 609 | return null; 610 | } 611 | stored.data = this.storage.get(keys.data); 612 | stored.protocol = this.storage.get(keys.protocol); 613 | stored.thumbprint = this.storage.get(keys.thumbprint); 614 | isExpired = stored.thumbprint !== this.thumbprint || stored.protocol !== location.protocol; 615 | return stored.data && !isExpired ? stored.data : null; 616 | }, 617 | fromNetwork: function(cb) { 618 | var that = this, settings; 619 | if (!cb) { 620 | return; 621 | } 622 | settings = this.prepare(this._settings()); 623 | this.transport(settings).fail(onError).done(onResponse); 624 | function onError() { 625 | cb(true); 626 | } 627 | function onResponse(resp) { 628 | cb(null, that.transform(resp)); 629 | } 630 | }, 631 | clear: function clear() { 632 | this.storage.clear(); 633 | return this; 634 | } 635 | }); 636 | return Prefetch; 637 | }(); 638 | var Remote = function() { 639 | "use strict"; 640 | function Remote(o) { 641 | this.url = o.url; 642 | this.prepare = o.prepare; 643 | this.transform = o.transform; 644 | this.indexResponse = o.indexResponse; 645 | this.transport = new Transport({ 646 | cache: o.cache, 647 | limiter: o.limiter, 648 | transport: o.transport, 649 | maxPendingRequests: o.maxPendingRequests 650 | }); 651 | } 652 | _.mixin(Remote.prototype, { 653 | _settings: function settings() { 654 | return { 655 | url: this.url, 656 | type: "GET", 657 | dataType: "json" 658 | }; 659 | }, 660 | get: function get(query, cb) { 661 | var that = this, settings; 662 | if (!cb) { 663 | return; 664 | } 665 | query = query || ""; 666 | settings = this.prepare(query, this._settings()); 667 | return this.transport.get(settings, onResponse); 668 | function onResponse(err, resp) { 669 | err ? cb([]) : cb(that.transform(resp)); 670 | } 671 | }, 672 | cancelLastRequest: function cancelLastRequest() { 673 | this.transport.cancel(); 674 | } 675 | }); 676 | return Remote; 677 | }(); 678 | var oParser = function() { 679 | "use strict"; 680 | return function parse(o) { 681 | var defaults, sorter; 682 | defaults = { 683 | initialize: true, 684 | identify: _.stringify, 685 | datumTokenizer: null, 686 | queryTokenizer: null, 687 | matchAnyQueryToken: false, 688 | sufficient: 5, 689 | indexRemote: false, 690 | sorter: null, 691 | local: [], 692 | prefetch: null, 693 | remote: null 694 | }; 695 | o = _.mixin(defaults, o || {}); 696 | !o.datumTokenizer && $.error("datumTokenizer is required"); 697 | !o.queryTokenizer && $.error("queryTokenizer is required"); 698 | sorter = o.sorter; 699 | o.sorter = sorter ? function(x) { 700 | return x.sort(sorter); 701 | } : _.identity; 702 | o.local = _.isFunction(o.local) ? o.local() : o.local; 703 | o.prefetch = parsePrefetch(o.prefetch); 704 | o.remote = parseRemote(o.remote); 705 | return o; 706 | }; 707 | function parsePrefetch(o) { 708 | var defaults; 709 | if (!o) { 710 | return null; 711 | } 712 | defaults = { 713 | url: null, 714 | ttl: 24 * 60 * 60 * 1e3, 715 | cache: true, 716 | cacheKey: null, 717 | thumbprint: "", 718 | prepare: _.identity, 719 | transform: _.identity, 720 | transport: null 721 | }; 722 | o = _.isString(o) ? { 723 | url: o 724 | } : o; 725 | o = _.mixin(defaults, o); 726 | !o.url && $.error("prefetch requires url to be set"); 727 | o.transform = o.filter || o.transform; 728 | o.cacheKey = o.cacheKey || o.url; 729 | o.thumbprint = VERSION + o.thumbprint; 730 | o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; 731 | return o; 732 | } 733 | function parseRemote(o) { 734 | var defaults; 735 | if (!o) { 736 | return; 737 | } 738 | defaults = { 739 | url: null, 740 | cache: true, 741 | prepare: null, 742 | replace: null, 743 | wildcard: null, 744 | limiter: null, 745 | rateLimitBy: "debounce", 746 | rateLimitWait: 300, 747 | transform: _.identity, 748 | transport: null 749 | }; 750 | o = _.isString(o) ? { 751 | url: o 752 | } : o; 753 | o = _.mixin(defaults, o); 754 | !o.url && $.error("remote requires url to be set"); 755 | o.transform = o.filter || o.transform; 756 | o.prepare = toRemotePrepare(o); 757 | o.limiter = toLimiter(o); 758 | o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; 759 | delete o.replace; 760 | delete o.wildcard; 761 | delete o.rateLimitBy; 762 | delete o.rateLimitWait; 763 | return o; 764 | } 765 | function toRemotePrepare(o) { 766 | var prepare, replace, wildcard; 767 | prepare = o.prepare; 768 | replace = o.replace; 769 | wildcard = o.wildcard; 770 | if (prepare) { 771 | return prepare; 772 | } 773 | if (replace) { 774 | prepare = prepareByReplace; 775 | } else if (o.wildcard) { 776 | prepare = prepareByWildcard; 777 | } else { 778 | prepare = identityPrepare; 779 | } 780 | return prepare; 781 | function prepareByReplace(query, settings) { 782 | settings.url = replace(settings.url, query); 783 | return settings; 784 | } 785 | function prepareByWildcard(query, settings) { 786 | settings.url = settings.url.replace(wildcard, encodeURIComponent(query)); 787 | return settings; 788 | } 789 | function identityPrepare(query, settings) { 790 | return settings; 791 | } 792 | } 793 | function toLimiter(o) { 794 | var limiter, method, wait; 795 | limiter = o.limiter; 796 | method = o.rateLimitBy; 797 | wait = o.rateLimitWait; 798 | if (!limiter) { 799 | limiter = /^throttle$/i.test(method) ? throttle(wait) : debounce(wait); 800 | } 801 | return limiter; 802 | function debounce(wait) { 803 | return function debounce(fn) { 804 | return _.debounce(fn, wait); 805 | }; 806 | } 807 | function throttle(wait) { 808 | return function throttle(fn) { 809 | return _.throttle(fn, wait); 810 | }; 811 | } 812 | } 813 | function callbackToDeferred(fn) { 814 | return function wrapper(o) { 815 | var deferred = $.Deferred(); 816 | fn(o, onSuccess, onError); 817 | return deferred; 818 | function onSuccess(resp) { 819 | _.defer(function() { 820 | deferred.resolve(resp); 821 | }); 822 | } 823 | function onError(err) { 824 | _.defer(function() { 825 | deferred.reject(err); 826 | }); 827 | } 828 | }; 829 | } 830 | }(); 831 | var Bloodhound = function() { 832 | "use strict"; 833 | var old; 834 | old = window && window.Bloodhound; 835 | function Bloodhound(o) { 836 | o = oParser(o); 837 | this.sorter = o.sorter; 838 | this.identify = o.identify; 839 | this.sufficient = o.sufficient; 840 | this.indexRemote = o.indexRemote; 841 | this.local = o.local; 842 | this.remote = o.remote ? new Remote(o.remote) : null; 843 | this.prefetch = o.prefetch ? new Prefetch(o.prefetch) : null; 844 | this.index = new SearchIndex({ 845 | identify: this.identify, 846 | datumTokenizer: o.datumTokenizer, 847 | queryTokenizer: o.queryTokenizer 848 | }); 849 | o.initialize !== false && this.initialize(); 850 | } 851 | Bloodhound.noConflict = function noConflict() { 852 | window && (window.Bloodhound = old); 853 | return Bloodhound; 854 | }; 855 | Bloodhound.tokenizers = tokenizers; 856 | _.mixin(Bloodhound.prototype, { 857 | __ttAdapter: function ttAdapter() { 858 | var that = this; 859 | return this.remote ? withAsync : withoutAsync; 860 | function withAsync(query, sync, async) { 861 | return that.search(query, sync, async); 862 | } 863 | function withoutAsync(query, sync) { 864 | return that.search(query, sync); 865 | } 866 | }, 867 | _loadPrefetch: function loadPrefetch() { 868 | var that = this, deferred, serialized; 869 | deferred = $.Deferred(); 870 | if (!this.prefetch) { 871 | deferred.resolve(); 872 | } else if (serialized = this.prefetch.fromCache()) { 873 | this.index.bootstrap(serialized); 874 | deferred.resolve(); 875 | } else { 876 | this.prefetch.fromNetwork(done); 877 | } 878 | return deferred.promise(); 879 | function done(err, data) { 880 | if (err) { 881 | return deferred.reject(); 882 | } 883 | that.add(data); 884 | that.prefetch.store(that.index.serialize()); 885 | deferred.resolve(); 886 | } 887 | }, 888 | _initialize: function initialize() { 889 | var that = this, deferred; 890 | this.clear(); 891 | (this.initPromise = this._loadPrefetch()).done(addLocalToIndex); 892 | return this.initPromise; 893 | function addLocalToIndex() { 894 | that.add(that.local); 895 | } 896 | }, 897 | initialize: function initialize(force) { 898 | return !this.initPromise || force ? this._initialize() : this.initPromise; 899 | }, 900 | add: function add(data) { 901 | this.index.add(data); 902 | return this; 903 | }, 904 | get: function get(ids) { 905 | ids = _.isArray(ids) ? ids : [].slice.call(arguments); 906 | return this.index.get(ids); 907 | }, 908 | search: function search(query, sync, async) { 909 | var that = this, local; 910 | sync = sync || _.noop; 911 | async = async || _.noop; 912 | local = this.sorter(this.index.search(query)); 913 | sync(this.remote ? local.slice() : local); 914 | if (this.remote && local.length < this.sufficient) { 915 | this.remote.get(query, processRemote); 916 | } else if (this.remote) { 917 | this.remote.cancelLastRequest(); 918 | } 919 | return this; 920 | function processRemote(remote) { 921 | var nonDuplicates = []; 922 | _.each(remote, function(r) { 923 | !_.some(local, function(l) { 924 | return that.identify(r) === that.identify(l); 925 | }) && nonDuplicates.push(r); 926 | }); 927 | that.indexRemote && that.add(nonDuplicates); 928 | async(nonDuplicates); 929 | } 930 | }, 931 | all: function all() { 932 | return this.index.all(); 933 | }, 934 | clear: function clear() { 935 | this.index.reset(); 936 | return this; 937 | }, 938 | clearPrefetchCache: function clearPrefetchCache() { 939 | this.prefetch && this.prefetch.clear(); 940 | return this; 941 | }, 942 | clearRemoteCache: function clearRemoteCache() { 943 | Transport.resetCache(); 944 | return this; 945 | }, 946 | ttAdapter: function ttAdapter() { 947 | return this.__ttAdapter(); 948 | } 949 | }); 950 | return Bloodhound; 951 | }(); 952 | return Bloodhound; 953 | }); 954 | 955 | (function(root, factory) { 956 | if (typeof define === "function" && define.amd) { 957 | define([ "jquery" ], function(a0) { 958 | return factory(a0); 959 | }); 960 | } else if (typeof module === "object" && module.exports) { 961 | module.exports = factory(require("jquery")); 962 | } else { 963 | factory(root["jQuery"]); 964 | } 965 | })(this, function($) { 966 | var _ = function() { 967 | "use strict"; 968 | return { 969 | isMsie: function() { 970 | return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; 971 | }, 972 | isBlankString: function(str) { 973 | return !str || /^\s*$/.test(str); 974 | }, 975 | escapeRegExChars: function(str) { 976 | return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 977 | }, 978 | isString: function(obj) { 979 | return typeof obj === "string"; 980 | }, 981 | isNumber: function(obj) { 982 | return typeof obj === "number"; 983 | }, 984 | isArray: $.isArray, 985 | isFunction: $.isFunction, 986 | isObject: $.isPlainObject, 987 | isUndefined: function(obj) { 988 | return typeof obj === "undefined"; 989 | }, 990 | isElement: function(obj) { 991 | return !!(obj && obj.nodeType === 1); 992 | }, 993 | isJQuery: function(obj) { 994 | return obj instanceof $; 995 | }, 996 | toStr: function toStr(s) { 997 | return _.isUndefined(s) || s === null ? "" : s + ""; 998 | }, 999 | bind: $.proxy, 1000 | each: function(collection, cb) { 1001 | $.each(collection, reverseArgs); 1002 | function reverseArgs(index, value) { 1003 | return cb(value, index); 1004 | } 1005 | }, 1006 | map: $.map, 1007 | filter: $.grep, 1008 | every: function(obj, test) { 1009 | var result = true; 1010 | if (!obj) { 1011 | return result; 1012 | } 1013 | $.each(obj, function(key, val) { 1014 | if (!(result = test.call(null, val, key, obj))) { 1015 | return false; 1016 | } 1017 | }); 1018 | return !!result; 1019 | }, 1020 | some: function(obj, test) { 1021 | var result = false; 1022 | if (!obj) { 1023 | return result; 1024 | } 1025 | $.each(obj, function(key, val) { 1026 | if (result = test.call(null, val, key, obj)) { 1027 | return false; 1028 | } 1029 | }); 1030 | return !!result; 1031 | }, 1032 | mixin: $.extend, 1033 | identity: function(x) { 1034 | return x; 1035 | }, 1036 | clone: function(obj) { 1037 | return $.extend(true, {}, obj); 1038 | }, 1039 | getIdGenerator: function() { 1040 | var counter = 0; 1041 | return function() { 1042 | return counter++; 1043 | }; 1044 | }, 1045 | templatify: function templatify(obj) { 1046 | return $.isFunction(obj) ? obj : template; 1047 | function template() { 1048 | return String(obj); 1049 | } 1050 | }, 1051 | defer: function(fn) { 1052 | setTimeout(fn, 0); 1053 | }, 1054 | debounce: function(func, wait, immediate) { 1055 | var timeout, result; 1056 | return function() { 1057 | var context = this, args = arguments, later, callNow; 1058 | later = function() { 1059 | timeout = null; 1060 | if (!immediate) { 1061 | result = func.apply(context, args); 1062 | } 1063 | }; 1064 | callNow = immediate && !timeout; 1065 | clearTimeout(timeout); 1066 | timeout = setTimeout(later, wait); 1067 | if (callNow) { 1068 | result = func.apply(context, args); 1069 | } 1070 | return result; 1071 | }; 1072 | }, 1073 | throttle: function(func, wait) { 1074 | var context, args, timeout, result, previous, later; 1075 | previous = 0; 1076 | later = function() { 1077 | previous = new Date(); 1078 | timeout = null; 1079 | result = func.apply(context, args); 1080 | }; 1081 | return function() { 1082 | var now = new Date(), remaining = wait - (now - previous); 1083 | context = this; 1084 | args = arguments; 1085 | if (remaining <= 0) { 1086 | clearTimeout(timeout); 1087 | timeout = null; 1088 | previous = now; 1089 | result = func.apply(context, args); 1090 | } else if (!timeout) { 1091 | timeout = setTimeout(later, remaining); 1092 | } 1093 | return result; 1094 | }; 1095 | }, 1096 | stringify: function(val) { 1097 | return _.isString(val) ? val : JSON.stringify(val); 1098 | }, 1099 | guid: function() { 1100 | function _p8(s) { 1101 | var p = (Math.random().toString(16) + "000000000").substr(2, 8); 1102 | return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p; 1103 | } 1104 | return "tt-" + _p8() + _p8(true) + _p8(true) + _p8(); 1105 | }, 1106 | noop: function() {} 1107 | }; 1108 | }(); 1109 | var WWW = function() { 1110 | "use strict"; 1111 | var defaultClassNames = { 1112 | wrapper: "twitter-typeahead", 1113 | input: "tt-input", 1114 | hint: "tt-hint", 1115 | menu: "tt-menu", 1116 | dataset: "tt-dataset", 1117 | suggestion: "tt-suggestion", 1118 | selectable: "tt-selectable", 1119 | empty: "tt-empty", 1120 | open: "tt-open", 1121 | cursor: "tt-cursor", 1122 | highlight: "tt-highlight" 1123 | }; 1124 | return build; 1125 | function build(o) { 1126 | var www, classes; 1127 | classes = _.mixin({}, defaultClassNames, o); 1128 | www = { 1129 | css: buildCss(), 1130 | classes: classes, 1131 | html: buildHtml(classes), 1132 | selectors: buildSelectors(classes) 1133 | }; 1134 | return { 1135 | css: www.css, 1136 | html: www.html, 1137 | classes: www.classes, 1138 | selectors: www.selectors, 1139 | mixin: function(o) { 1140 | _.mixin(o, www); 1141 | } 1142 | }; 1143 | } 1144 | function buildHtml(c) { 1145 | return { 1146 | wrapper: '', 1147 | menu: '
' 1148 | }; 1149 | } 1150 | function buildSelectors(classes) { 1151 | var selectors = {}; 1152 | _.each(classes, function(v, k) { 1153 | selectors[k] = "." + v; 1154 | }); 1155 | return selectors; 1156 | } 1157 | function buildCss() { 1158 | var css = { 1159 | wrapper: { 1160 | position: "relative", 1161 | display: "inline-block" 1162 | }, 1163 | hint: { 1164 | position: "absolute", 1165 | top: "0", 1166 | left: "0", 1167 | borderColor: "transparent", 1168 | boxShadow: "none", 1169 | opacity: "1" 1170 | }, 1171 | input: { 1172 | position: "relative", 1173 | verticalAlign: "top", 1174 | backgroundColor: "transparent" 1175 | }, 1176 | inputWithNoHint: { 1177 | position: "relative", 1178 | verticalAlign: "top" 1179 | }, 1180 | menu: { 1181 | position: "absolute", 1182 | top: "100%", 1183 | left: "0", 1184 | zIndex: "100", 1185 | display: "none" 1186 | }, 1187 | ltr: { 1188 | left: "0", 1189 | right: "auto" 1190 | }, 1191 | rtl: { 1192 | left: "auto", 1193 | right: " 0" 1194 | } 1195 | }; 1196 | if (_.isMsie()) { 1197 | _.mixin(css.input, { 1198 | backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" 1199 | }); 1200 | } 1201 | return css; 1202 | } 1203 | }(); 1204 | var EventBus = function() { 1205 | "use strict"; 1206 | var namespace, deprecationMap; 1207 | namespace = "typeahead:"; 1208 | deprecationMap = { 1209 | render: "rendered", 1210 | cursorchange: "cursorchanged", 1211 | select: "selected", 1212 | autocomplete: "autocompleted" 1213 | }; 1214 | function EventBus(o) { 1215 | if (!o || !o.el) { 1216 | $.error("EventBus initialized without el"); 1217 | } 1218 | this.$el = $(o.el); 1219 | } 1220 | _.mixin(EventBus.prototype, { 1221 | _trigger: function(type, args) { 1222 | var $e = $.Event(namespace + type); 1223 | this.$el.trigger.call(this.$el, $e, args || []); 1224 | return $e; 1225 | }, 1226 | before: function(type) { 1227 | var args, $e; 1228 | args = [].slice.call(arguments, 1); 1229 | $e = this._trigger("before" + type, args); 1230 | return $e.isDefaultPrevented(); 1231 | }, 1232 | trigger: function(type) { 1233 | var deprecatedType; 1234 | this._trigger(type, [].slice.call(arguments, 1)); 1235 | if (deprecatedType = deprecationMap[type]) { 1236 | this._trigger(deprecatedType, [].slice.call(arguments, 1)); 1237 | } 1238 | } 1239 | }); 1240 | return EventBus; 1241 | }(); 1242 | var EventEmitter = function() { 1243 | "use strict"; 1244 | var splitter = /\s+/, nextTick = getNextTick(); 1245 | return { 1246 | onSync: onSync, 1247 | onAsync: onAsync, 1248 | off: off, 1249 | trigger: trigger 1250 | }; 1251 | function on(method, types, cb, context) { 1252 | var type; 1253 | if (!cb) { 1254 | return this; 1255 | } 1256 | types = types.split(splitter); 1257 | cb = context ? bindContext(cb, context) : cb; 1258 | this._callbacks = this._callbacks || {}; 1259 | while (type = types.shift()) { 1260 | this._callbacks[type] = this._callbacks[type] || { 1261 | sync: [], 1262 | async: [] 1263 | }; 1264 | this._callbacks[type][method].push(cb); 1265 | } 1266 | return this; 1267 | } 1268 | function onAsync(types, cb, context) { 1269 | return on.call(this, "async", types, cb, context); 1270 | } 1271 | function onSync(types, cb, context) { 1272 | return on.call(this, "sync", types, cb, context); 1273 | } 1274 | function off(types) { 1275 | var type; 1276 | if (!this._callbacks) { 1277 | return this; 1278 | } 1279 | types = types.split(splitter); 1280 | while (type = types.shift()) { 1281 | delete this._callbacks[type]; 1282 | } 1283 | return this; 1284 | } 1285 | function trigger(types) { 1286 | var type, callbacks, args, syncFlush, asyncFlush; 1287 | if (!this._callbacks) { 1288 | return this; 1289 | } 1290 | types = types.split(splitter); 1291 | args = [].slice.call(arguments, 1); 1292 | while ((type = types.shift()) && (callbacks = this._callbacks[type])) { 1293 | syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); 1294 | asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); 1295 | syncFlush() && nextTick(asyncFlush); 1296 | } 1297 | return this; 1298 | } 1299 | function getFlush(callbacks, context, args) { 1300 | return flush; 1301 | function flush() { 1302 | var cancelled; 1303 | for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { 1304 | cancelled = callbacks[i].apply(context, args) === false; 1305 | } 1306 | return !cancelled; 1307 | } 1308 | } 1309 | function getNextTick() { 1310 | var nextTickFn; 1311 | if (window.setImmediate) { 1312 | nextTickFn = function nextTickSetImmediate(fn) { 1313 | setImmediate(function() { 1314 | fn(); 1315 | }); 1316 | }; 1317 | } else { 1318 | nextTickFn = function nextTickSetTimeout(fn) { 1319 | setTimeout(function() { 1320 | fn(); 1321 | }, 0); 1322 | }; 1323 | } 1324 | return nextTickFn; 1325 | } 1326 | function bindContext(fn, context) { 1327 | return fn.bind ? fn.bind(context) : function() { 1328 | fn.apply(context, [].slice.call(arguments, 0)); 1329 | }; 1330 | } 1331 | }(); 1332 | var highlight = function(doc) { 1333 | "use strict"; 1334 | var defaults = { 1335 | node: null, 1336 | pattern: null, 1337 | tagName: "strong", 1338 | className: null, 1339 | wordsOnly: false, 1340 | caseSensitive: false, 1341 | diacriticInsensitive: false 1342 | }; 1343 | var accented = { 1344 | A: "[AaªÀ-Åà-åĀ-ąǍǎȀ-ȃȦȧᴬᵃḀḁẚẠ-ảₐ℀℁℻⒜Ⓐⓐ㍱-㍴㎀-㎄㎈㎉㎩-㎯㏂㏊㏟㏿Aa]", 1345 | B: "[BbᴮᵇḂ-ḇℬ⒝Ⓑⓑ㍴㎅-㎇㏃㏈㏔㏝Bb]", 1346 | C: "[CcÇçĆ-čᶜ℀ℂ℃℅℆ℭⅭⅽ⒞Ⓒⓒ㍶㎈㎉㎝㎠㎤㏄-㏇Cc]", 1347 | D: "[DdĎďDŽ-džDZ-dzᴰᵈḊ-ḓⅅⅆⅮⅾ⒟Ⓓⓓ㋏㍲㍷-㍹㎗㎭-㎯㏅㏈Dd]", 1348 | E: "[EeÈ-Ëè-ëĒ-ěȄ-ȇȨȩᴱᵉḘ-ḛẸ-ẽₑ℡ℯℰⅇ⒠Ⓔⓔ㉐㋍㋎Ee]", 1349 | F: "[FfᶠḞḟ℉ℱ℻⒡Ⓕⓕ㎊-㎌㎙ff-fflFf]", 1350 | G: "[GgĜ-ģǦǧǴǵᴳᵍḠḡℊ⒢Ⓖⓖ㋌㋍㎇㎍-㎏㎓㎬㏆㏉㏒㏿Gg]", 1351 | H: "[HhĤĥȞȟʰᴴḢ-ḫẖℋ-ℎ⒣Ⓗⓗ㋌㍱㎐-㎔㏊㏋㏗Hh]", 1352 | I: "[IiÌ-Ïì-ïĨ-İIJijǏǐȈ-ȋᴵᵢḬḭỈ-ịⁱℐℑℹⅈⅠ-ⅣⅥ-ⅨⅪⅫⅰ-ⅳⅵ-ⅸⅺⅻ⒤Ⓘⓘ㍺㏌㏕fiffiIi]", 1353 | J: "[JjIJ-ĵLJ-njǰʲᴶⅉ⒥ⒿⓙⱼJj]", 1354 | K: "[KkĶķǨǩᴷᵏḰ-ḵK⒦Ⓚⓚ㎄㎅㎉㎏㎑㎘㎞㎢㎦㎪㎸㎾㏀㏆㏍-㏏Kk]", 1355 | L: "[LlĹ-ŀLJ-ljˡᴸḶḷḺ-ḽℒℓ℡Ⅼⅼ⒧Ⓛⓛ㋏㎈㎉㏐-㏓㏕㏖㏿flfflLl]", 1356 | M: "[MmᴹᵐḾ-ṃ℠™ℳⅯⅿ⒨Ⓜⓜ㍷-㍹㎃㎆㎎㎒㎖㎙-㎨㎫㎳㎷㎹㎽㎿㏁㏂㏎㏐㏔-㏖㏘㏙㏞㏟Mm]", 1357 | N: "[NnÑñŃ-ʼnNJ-njǸǹᴺṄ-ṋⁿℕ№⒩Ⓝⓝ㎁㎋㎚㎱㎵㎻㏌㏑Nn]", 1358 | O: "[OoºÒ-Öò-öŌ-őƠơǑǒǪǫȌ-ȏȮȯᴼᵒỌ-ỏₒ℅№ℴ⒪Ⓞⓞ㍵㏇㏒㏖Oo]", 1359 | P: "[PpᴾᵖṔ-ṗℙ⒫Ⓟⓟ㉐㍱㍶㎀㎊㎩-㎬㎰㎴㎺㏋㏗-㏚Pp]", 1360 | Q: "[Qqℚ⒬Ⓠⓠ㏃Qq]", 1361 | R: "[RrŔ-řȐ-ȓʳᴿᵣṘ-ṛṞṟ₨ℛ-ℝ⒭Ⓡⓡ㋍㍴㎭-㎯㏚㏛Rr]", 1362 | S: "[SsŚ-šſȘșˢṠ-ṣ₨℁℠⒮Ⓢⓢ㎧㎨㎮-㎳㏛㏜stSs]", 1363 | T: "[TtŢ-ťȚțᵀᵗṪ-ṱẗ℡™⒯Ⓣⓣ㉐㋏㎔㏏ſtstTt]", 1364 | U: "[UuÙ-Üù-üŨ-ųƯưǓǔȔ-ȗᵁᵘᵤṲ-ṷỤ-ủ℆⒰Ⓤⓤ㍳㍺Uu]", 1365 | V: "[VvᵛᵥṼ-ṿⅣ-Ⅷⅳ-ⅷ⒱Ⓥⓥⱽ㋎㍵㎴-㎹㏜㏞Vv]", 1366 | W: "[WwŴŵʷᵂẀ-ẉẘ⒲Ⓦⓦ㎺-㎿㏝Ww]", 1367 | X: "[XxˣẊ-ẍₓ℻Ⅸ-Ⅻⅸ-ⅻ⒳Ⓧⓧ㏓Xx]", 1368 | Y: "[YyÝýÿŶ-ŸȲȳʸẎẏẙỲ-ỹ⒴Ⓨⓨ㏉Yy]", 1369 | Z: "[ZzŹ-žDZ-dzᶻẐ-ẕℤℨ⒵Ⓩⓩ㎐-㎔Zz]" 1370 | }; 1371 | return function hightlight(o) { 1372 | var regex; 1373 | o = _.mixin({}, defaults, o); 1374 | if (!o.node || !o.pattern) { 1375 | return; 1376 | } 1377 | o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; 1378 | regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly, o.diacriticInsensitive); 1379 | traverse(o.node, hightlightTextNode); 1380 | function hightlightTextNode(textNode) { 1381 | var match, patternNode, wrapperNode; 1382 | if (match = regex.exec(textNode.data)) { 1383 | wrapperNode = doc.createElement(o.tagName); 1384 | o.className && (wrapperNode.className = o.className); 1385 | patternNode = textNode.splitText(match.index); 1386 | patternNode.splitText(match[0].length); 1387 | wrapperNode.appendChild(patternNode.cloneNode(true)); 1388 | textNode.parentNode.replaceChild(wrapperNode, patternNode); 1389 | } 1390 | return !!match; 1391 | } 1392 | function traverse(el, hightlightTextNode) { 1393 | var childNode, TEXT_NODE_TYPE = 3; 1394 | for (var i = 0; i < el.childNodes.length; i++) { 1395 | childNode = el.childNodes[i]; 1396 | if (childNode.nodeType === TEXT_NODE_TYPE) { 1397 | i += hightlightTextNode(childNode) ? 1 : 0; 1398 | } else { 1399 | traverse(childNode, hightlightTextNode); 1400 | } 1401 | } 1402 | } 1403 | }; 1404 | function accent_replacer(chr) { 1405 | return accented[chr.toUpperCase()] || chr; 1406 | } 1407 | function getRegex(patterns, caseSensitive, wordsOnly, diacriticInsensitive) { 1408 | var escapedPatterns = [], regexStr; 1409 | for (var i = 0, len = patterns.length; i < len; i++) { 1410 | var escapedWord = _.escapeRegExChars(patterns[i]); 1411 | if (diacriticInsensitive) { 1412 | escapedWord = escapedWord.replace(/\S/g, accent_replacer); 1413 | } 1414 | escapedPatterns.push(escapedWord); 1415 | } 1416 | regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; 1417 | return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); 1418 | } 1419 | }(window.document); 1420 | var Input = function() { 1421 | "use strict"; 1422 | var specialKeyCodeMap; 1423 | specialKeyCodeMap = { 1424 | 9: "tab", 1425 | 27: "esc", 1426 | 37: "left", 1427 | 39: "right", 1428 | 13: "enter", 1429 | 38: "up", 1430 | 40: "down" 1431 | }; 1432 | function Input(o, www) { 1433 | o = o || {}; 1434 | if (!o.input) { 1435 | $.error("input is missing"); 1436 | } 1437 | www.mixin(this); 1438 | this.$hint = $(o.hint); 1439 | this.$input = $(o.input); 1440 | this.$input.attr({ 1441 | "aria-activedescendant": "", 1442 | "aria-owns": this.$input.attr("id") + "_listbox", 1443 | role: "combobox", 1444 | "aria-readonly": "true", 1445 | "aria-autocomplete": "list" 1446 | }); 1447 | $(www.menu).attr("id", this.$input.attr("id") + "_listbox"); 1448 | this.query = this.$input.val(); 1449 | this.queryWhenFocused = this.hasFocus() ? this.query : null; 1450 | this.$overflowHelper = buildOverflowHelper(this.$input); 1451 | this._checkLanguageDirection(); 1452 | if (this.$hint.length === 0) { 1453 | this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; 1454 | } 1455 | this.onSync("cursorchange", this._updateDescendent); 1456 | } 1457 | Input.normalizeQuery = function(str) { 1458 | return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " "); 1459 | }; 1460 | _.mixin(Input.prototype, EventEmitter, { 1461 | _onBlur: function onBlur() { 1462 | this.resetInputValue(); 1463 | this.trigger("blurred"); 1464 | }, 1465 | _onFocus: function onFocus() { 1466 | this.queryWhenFocused = this.query; 1467 | this.trigger("focused"); 1468 | }, 1469 | _onKeydown: function onKeydown($e) { 1470 | var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; 1471 | this._managePreventDefault(keyName, $e); 1472 | if (keyName && this._shouldTrigger(keyName, $e)) { 1473 | this.trigger(keyName + "Keyed", $e); 1474 | } 1475 | }, 1476 | _onInput: function onInput() { 1477 | this._setQuery(this.getInputValue()); 1478 | this.clearHintIfInvalid(); 1479 | this._checkLanguageDirection(); 1480 | }, 1481 | _managePreventDefault: function managePreventDefault(keyName, $e) { 1482 | var preventDefault; 1483 | switch (keyName) { 1484 | case "up": 1485 | case "down": 1486 | preventDefault = !withModifier($e); 1487 | break; 1488 | 1489 | default: 1490 | preventDefault = false; 1491 | } 1492 | preventDefault && $e.preventDefault(); 1493 | }, 1494 | _shouldTrigger: function shouldTrigger(keyName, $e) { 1495 | var trigger; 1496 | switch (keyName) { 1497 | case "tab": 1498 | trigger = !withModifier($e); 1499 | break; 1500 | 1501 | default: 1502 | trigger = true; 1503 | } 1504 | return trigger; 1505 | }, 1506 | _checkLanguageDirection: function checkLanguageDirection() { 1507 | var dir = (this.$input.css("direction") || "ltr").toLowerCase(); 1508 | if (this.dir !== dir) { 1509 | this.dir = dir; 1510 | this.$hint.attr("dir", dir); 1511 | this.trigger("langDirChanged", dir); 1512 | } 1513 | }, 1514 | _setQuery: function setQuery(val, silent) { 1515 | var areEquivalent, hasDifferentWhitespace; 1516 | areEquivalent = areQueriesEquivalent(val, this.query); 1517 | hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false; 1518 | this.query = val; 1519 | if (!silent && !areEquivalent) { 1520 | this.trigger("queryChanged", this.query); 1521 | } else if (!silent && hasDifferentWhitespace) { 1522 | this.trigger("whitespaceChanged", this.query); 1523 | } 1524 | }, 1525 | _updateDescendent: function updateDescendent(event, id) { 1526 | this.$input.attr("aria-activedescendant", id); 1527 | }, 1528 | bind: function() { 1529 | var that = this, onBlur, onFocus, onKeydown, onInput; 1530 | onBlur = _.bind(this._onBlur, this); 1531 | onFocus = _.bind(this._onFocus, this); 1532 | onKeydown = _.bind(this._onKeydown, this); 1533 | onInput = _.bind(this._onInput, this); 1534 | this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); 1535 | if (!_.isMsie() || _.isMsie() > 9) { 1536 | this.$input.on("input.tt", onInput); 1537 | } else { 1538 | this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { 1539 | if (specialKeyCodeMap[$e.which || $e.keyCode]) { 1540 | return; 1541 | } 1542 | _.defer(_.bind(that._onInput, that, $e)); 1543 | }); 1544 | } 1545 | return this; 1546 | }, 1547 | focus: function focus() { 1548 | this.$input.focus(); 1549 | }, 1550 | blur: function blur() { 1551 | this.$input.blur(); 1552 | }, 1553 | getLangDir: function getLangDir() { 1554 | return this.dir; 1555 | }, 1556 | getQuery: function getQuery() { 1557 | return this.query || ""; 1558 | }, 1559 | setQuery: function setQuery(val, silent) { 1560 | this.setInputValue(val); 1561 | this._setQuery(val, silent); 1562 | }, 1563 | hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() { 1564 | return this.query !== this.queryWhenFocused; 1565 | }, 1566 | getInputValue: function getInputValue() { 1567 | return this.$input.val(); 1568 | }, 1569 | setInputValue: function setInputValue(value) { 1570 | this.$input.val(value); 1571 | this.clearHintIfInvalid(); 1572 | this._checkLanguageDirection(); 1573 | }, 1574 | resetInputValue: function resetInputValue() { 1575 | this.setInputValue(this.query); 1576 | }, 1577 | getHint: function getHint() { 1578 | return this.$hint.val(); 1579 | }, 1580 | setHint: function setHint(value) { 1581 | this.$hint.val(value); 1582 | }, 1583 | clearHint: function clearHint() { 1584 | this.setHint(""); 1585 | }, 1586 | clearHintIfInvalid: function clearHintIfInvalid() { 1587 | var val, hint, valIsPrefixOfHint, isValid; 1588 | val = this.getInputValue(); 1589 | hint = this.getHint(); 1590 | valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; 1591 | isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow(); 1592 | !isValid && this.clearHint(); 1593 | }, 1594 | hasFocus: function hasFocus() { 1595 | return this.$input.is(":focus"); 1596 | }, 1597 | hasOverflow: function hasOverflow() { 1598 | var constraint = this.$input.width() - 2; 1599 | this.$overflowHelper.text(this.getInputValue()); 1600 | return this.$overflowHelper.width() >= constraint; 1601 | }, 1602 | isCursorAtEnd: function() { 1603 | var valueLength, selectionStart, range; 1604 | valueLength = this.$input.val().length; 1605 | selectionStart = this.$input[0].selectionStart; 1606 | if (_.isNumber(selectionStart)) { 1607 | return selectionStart === valueLength; 1608 | } else if (document.selection) { 1609 | range = document.selection.createRange(); 1610 | range.moveStart("character", -valueLength); 1611 | return valueLength === range.text.length; 1612 | } 1613 | return true; 1614 | }, 1615 | destroy: function destroy() { 1616 | this.$hint.off(".tt"); 1617 | this.$input.off(".tt"); 1618 | this.$overflowHelper.remove(); 1619 | this.$hint = this.$input = this.$overflowHelper = $("
"); 1620 | } 1621 | }); 1622 | return Input; 1623 | function buildOverflowHelper($input) { 1624 | return $('').css({ 1625 | position: "absolute", 1626 | visibility: "hidden", 1627 | whiteSpace: "pre", 1628 | fontFamily: $input.css("font-family"), 1629 | fontSize: $input.css("font-size"), 1630 | fontStyle: $input.css("font-style"), 1631 | fontVariant: $input.css("font-variant"), 1632 | fontWeight: $input.css("font-weight"), 1633 | wordSpacing: $input.css("word-spacing"), 1634 | letterSpacing: $input.css("letter-spacing"), 1635 | textIndent: $input.css("text-indent"), 1636 | textRendering: $input.css("text-rendering"), 1637 | textTransform: $input.css("text-transform") 1638 | }).insertAfter($input); 1639 | } 1640 | function areQueriesEquivalent(a, b) { 1641 | return Input.normalizeQuery(a) === Input.normalizeQuery(b); 1642 | } 1643 | function withModifier($e) { 1644 | return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; 1645 | } 1646 | }(); 1647 | var Dataset = function() { 1648 | "use strict"; 1649 | var keys, nameGenerator; 1650 | keys = { 1651 | dataset: "tt-selectable-dataset", 1652 | val: "tt-selectable-display", 1653 | obj: "tt-selectable-object" 1654 | }; 1655 | nameGenerator = _.getIdGenerator(); 1656 | function Dataset(o, www) { 1657 | o = o || {}; 1658 | o.templates = o.templates || {}; 1659 | o.templates.notFound = o.templates.notFound || o.templates.empty; 1660 | if (!o.source) { 1661 | $.error("missing source"); 1662 | } 1663 | if (!o.node) { 1664 | $.error("missing node"); 1665 | } 1666 | if (o.name && !isValidName(o.name)) { 1667 | $.error("invalid dataset name: " + o.name); 1668 | } 1669 | www.mixin(this); 1670 | this.highlight = !!o.highlight; 1671 | this.name = _.toStr(o.name || nameGenerator()); 1672 | this.limit = o.limit || 5; 1673 | this.displayFn = getDisplayFn(o.display || o.displayKey); 1674 | this.templates = getTemplates(o.templates, this.displayFn); 1675 | this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source; 1676 | this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async; 1677 | this._resetLastSuggestion(); 1678 | this.$el = $(o.node).attr("role", "presentation").addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name); 1679 | } 1680 | Dataset.extractData = function extractData(el) { 1681 | var $el = $(el); 1682 | if ($el.data(keys.obj)) { 1683 | return { 1684 | dataset: $el.data(keys.dataset) || "", 1685 | val: $el.data(keys.val) || "", 1686 | obj: $el.data(keys.obj) || null 1687 | }; 1688 | } 1689 | return null; 1690 | }; 1691 | _.mixin(Dataset.prototype, EventEmitter, { 1692 | _overwrite: function overwrite(query, suggestions) { 1693 | suggestions = suggestions || []; 1694 | if (suggestions.length) { 1695 | this._renderSuggestions(query, suggestions); 1696 | } else if (this.async && this.templates.pending) { 1697 | this._renderPending(query); 1698 | } else if (!this.async && this.templates.notFound) { 1699 | this._renderNotFound(query); 1700 | } else { 1701 | this._empty(); 1702 | } 1703 | this.trigger("rendered", suggestions, false, this.name); 1704 | }, 1705 | _append: function append(query, suggestions) { 1706 | suggestions = suggestions || []; 1707 | if (suggestions.length && this.$lastSuggestion.length) { 1708 | this._appendSuggestions(query, suggestions); 1709 | } else if (suggestions.length) { 1710 | this._renderSuggestions(query, suggestions); 1711 | } else if (!this.$lastSuggestion.length && this.templates.notFound) { 1712 | this._renderNotFound(query); 1713 | } 1714 | this.trigger("rendered", suggestions, true, this.name); 1715 | }, 1716 | _renderSuggestions: function renderSuggestions(query, suggestions) { 1717 | var $fragment; 1718 | $fragment = this._getSuggestionsFragment(query, suggestions); 1719 | this.$lastSuggestion = $fragment.children().last(); 1720 | this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions)); 1721 | }, 1722 | _appendSuggestions: function appendSuggestions(query, suggestions) { 1723 | var $fragment, $lastSuggestion; 1724 | $fragment = this._getSuggestionsFragment(query, suggestions); 1725 | $lastSuggestion = $fragment.children().last(); 1726 | this.$lastSuggestion.after($fragment); 1727 | this.$lastSuggestion = $lastSuggestion; 1728 | }, 1729 | _renderPending: function renderPending(query) { 1730 | var template = this.templates.pending; 1731 | this._resetLastSuggestion(); 1732 | template && this.$el.html(template({ 1733 | query: query, 1734 | dataset: this.name 1735 | })); 1736 | }, 1737 | _renderNotFound: function renderNotFound(query) { 1738 | var template = this.templates.notFound; 1739 | this._resetLastSuggestion(); 1740 | template && this.$el.html(template({ 1741 | query: query, 1742 | dataset: this.name 1743 | })); 1744 | }, 1745 | _empty: function empty() { 1746 | this.$el.empty(); 1747 | this._resetLastSuggestion(); 1748 | }, 1749 | _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) { 1750 | var that = this, fragment; 1751 | fragment = document.createDocumentFragment(); 1752 | _.each(suggestions, function getSuggestionNode(suggestion) { 1753 | var $el, context; 1754 | context = that._injectQuery(query, suggestion); 1755 | $el = $(that.templates.suggestion(context)).data(keys.dataset, that.name).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable); 1756 | fragment.appendChild($el[0]); 1757 | }); 1758 | this.highlight && highlight({ 1759 | className: this.classes.highlight, 1760 | node: fragment, 1761 | pattern: query 1762 | }); 1763 | return $(fragment); 1764 | }, 1765 | _getFooter: function getFooter(query, suggestions) { 1766 | return this.templates.footer ? this.templates.footer({ 1767 | query: query, 1768 | suggestions: suggestions, 1769 | dataset: this.name 1770 | }) : null; 1771 | }, 1772 | _getHeader: function getHeader(query, suggestions) { 1773 | return this.templates.header ? this.templates.header({ 1774 | query: query, 1775 | suggestions: suggestions, 1776 | dataset: this.name 1777 | }) : null; 1778 | }, 1779 | _resetLastSuggestion: function resetLastSuggestion() { 1780 | this.$lastSuggestion = $(); 1781 | }, 1782 | _injectQuery: function injectQuery(query, obj) { 1783 | return _.isObject(obj) ? _.mixin({ 1784 | _query: query 1785 | }, obj) : obj; 1786 | }, 1787 | update: function update(query) { 1788 | var that = this, canceled = false, syncCalled = false, rendered = 0; 1789 | this.cancel(); 1790 | this.cancel = function cancel() { 1791 | canceled = true; 1792 | that.cancel = $.noop; 1793 | that.async && that.trigger("asyncCanceled", query, that.name); 1794 | }; 1795 | this.source(query, sync, async); 1796 | !syncCalled && sync([]); 1797 | function sync(suggestions) { 1798 | if (syncCalled) { 1799 | return; 1800 | } 1801 | syncCalled = true; 1802 | suggestions = (suggestions || []).slice(0, that.limit); 1803 | rendered = suggestions.length; 1804 | that._overwrite(query, suggestions); 1805 | if (rendered < that.limit && that.async) { 1806 | that.trigger("asyncRequested", query, that.name); 1807 | } 1808 | } 1809 | function async(suggestions) { 1810 | suggestions = suggestions || []; 1811 | if (!canceled && rendered < that.limit) { 1812 | that.cancel = $.noop; 1813 | var idx = Math.abs(rendered - that.limit); 1814 | rendered += idx; 1815 | that._append(query, suggestions.slice(0, idx)); 1816 | that.async && that.trigger("asyncReceived", query, that.name); 1817 | } 1818 | } 1819 | }, 1820 | cancel: $.noop, 1821 | clear: function clear() { 1822 | this._empty(); 1823 | this.cancel(); 1824 | this.trigger("cleared"); 1825 | }, 1826 | isEmpty: function isEmpty() { 1827 | return this.$el.is(":empty"); 1828 | }, 1829 | destroy: function destroy() { 1830 | this.$el = $("
"); 1831 | } 1832 | }); 1833 | return Dataset; 1834 | function getDisplayFn(display) { 1835 | display = display || _.stringify; 1836 | return _.isFunction(display) ? display : displayFn; 1837 | function displayFn(obj) { 1838 | return obj[display]; 1839 | } 1840 | } 1841 | function getTemplates(templates, displayFn) { 1842 | return { 1843 | notFound: templates.notFound && _.templatify(templates.notFound), 1844 | pending: templates.pending && _.templatify(templates.pending), 1845 | header: templates.header && _.templatify(templates.header), 1846 | footer: templates.footer && _.templatify(templates.footer), 1847 | suggestion: templates.suggestion || suggestionTemplate 1848 | }; 1849 | function suggestionTemplate(context) { 1850 | return $('
').attr("id", _.guid()).text(displayFn(context)); 1851 | } 1852 | } 1853 | function isValidName(str) { 1854 | return /^[_a-zA-Z0-9-]+$/.test(str); 1855 | } 1856 | }(); 1857 | var Menu = function() { 1858 | "use strict"; 1859 | function Menu(o, www) { 1860 | var that = this; 1861 | o = o || {}; 1862 | if (!o.node) { 1863 | $.error("node is required"); 1864 | } 1865 | www.mixin(this); 1866 | this.$node = $(o.node); 1867 | this.query = null; 1868 | this.datasets = _.map(o.datasets, initializeDataset); 1869 | function initializeDataset(oDataset) { 1870 | var node = that.$node.find(oDataset.node).first(); 1871 | oDataset.node = node.length ? node : $("
").appendTo(that.$node); 1872 | return new Dataset(oDataset, www); 1873 | } 1874 | } 1875 | _.mixin(Menu.prototype, EventEmitter, { 1876 | _onSelectableClick: function onSelectableClick($e) { 1877 | this.trigger("selectableClicked", $($e.currentTarget)); 1878 | }, 1879 | _onRendered: function onRendered(type, dataset, suggestions, async) { 1880 | this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); 1881 | this.trigger("datasetRendered", dataset, suggestions, async); 1882 | }, 1883 | _onCleared: function onCleared() { 1884 | this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); 1885 | this.trigger("datasetCleared"); 1886 | }, 1887 | _propagate: function propagate() { 1888 | this.trigger.apply(this, arguments); 1889 | }, 1890 | _allDatasetsEmpty: function allDatasetsEmpty() { 1891 | return _.every(this.datasets, _.bind(function isDatasetEmpty(dataset) { 1892 | var isEmpty = dataset.isEmpty(); 1893 | this.$node.attr("aria-expanded", !isEmpty); 1894 | return isEmpty; 1895 | }, this)); 1896 | }, 1897 | _getSelectables: function getSelectables() { 1898 | return this.$node.find(this.selectors.selectable); 1899 | }, 1900 | _removeCursor: function _removeCursor() { 1901 | var $selectable = this.getActiveSelectable(); 1902 | $selectable && $selectable.removeClass(this.classes.cursor); 1903 | }, 1904 | _ensureVisible: function ensureVisible($el) { 1905 | var elTop, elBottom, nodeScrollTop, nodeHeight; 1906 | elTop = $el.position().top; 1907 | elBottom = elTop + $el.outerHeight(true); 1908 | nodeScrollTop = this.$node.scrollTop(); 1909 | nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10); 1910 | if (elTop < 0) { 1911 | this.$node.scrollTop(nodeScrollTop + elTop); 1912 | } else if (nodeHeight < elBottom) { 1913 | this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight)); 1914 | } 1915 | }, 1916 | bind: function() { 1917 | var that = this, onSelectableClick; 1918 | onSelectableClick = _.bind(this._onSelectableClick, this); 1919 | this.$node.on("click.tt", this.selectors.selectable, onSelectableClick); 1920 | this.$node.on("mouseover", this.selectors.selectable, function() { 1921 | that.setCursor($(this)); 1922 | }); 1923 | this.$node.on("mouseleave", function() { 1924 | that._removeCursor(); 1925 | }); 1926 | _.each(this.datasets, function(dataset) { 1927 | dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that); 1928 | }); 1929 | return this; 1930 | }, 1931 | isOpen: function isOpen() { 1932 | return this.$node.hasClass(this.classes.open); 1933 | }, 1934 | open: function open() { 1935 | this.$node.scrollTop(0); 1936 | this.$node.addClass(this.classes.open); 1937 | }, 1938 | close: function close() { 1939 | this.$node.attr("aria-expanded", false); 1940 | this.$node.removeClass(this.classes.open); 1941 | this._removeCursor(); 1942 | }, 1943 | setLanguageDirection: function setLanguageDirection(dir) { 1944 | this.$node.attr("dir", dir); 1945 | }, 1946 | selectableRelativeToCursor: function selectableRelativeToCursor(delta) { 1947 | var $selectables, $oldCursor, oldIndex, newIndex; 1948 | $oldCursor = this.getActiveSelectable(); 1949 | $selectables = this._getSelectables(); 1950 | oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1; 1951 | newIndex = oldIndex + delta; 1952 | newIndex = (newIndex + 1) % ($selectables.length + 1) - 1; 1953 | newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex; 1954 | return newIndex === -1 ? null : $selectables.eq(newIndex); 1955 | }, 1956 | setCursor: function setCursor($selectable) { 1957 | this._removeCursor(); 1958 | if ($selectable = $selectable && $selectable.first()) { 1959 | $selectable.addClass(this.classes.cursor); 1960 | this._ensureVisible($selectable); 1961 | } 1962 | }, 1963 | getSelectableData: function getSelectableData($el) { 1964 | return $el && $el.length ? Dataset.extractData($el) : null; 1965 | }, 1966 | getActiveSelectable: function getActiveSelectable() { 1967 | var $selectable = this._getSelectables().filter(this.selectors.cursor).first(); 1968 | return $selectable.length ? $selectable : null; 1969 | }, 1970 | getTopSelectable: function getTopSelectable() { 1971 | var $selectable = this._getSelectables().first(); 1972 | return $selectable.length ? $selectable : null; 1973 | }, 1974 | update: function update(query) { 1975 | var isValidUpdate = query !== this.query; 1976 | if (isValidUpdate) { 1977 | this.query = query; 1978 | _.each(this.datasets, updateDataset); 1979 | } 1980 | return isValidUpdate; 1981 | function updateDataset(dataset) { 1982 | dataset.update(query); 1983 | } 1984 | }, 1985 | empty: function empty() { 1986 | _.each(this.datasets, clearDataset); 1987 | this.query = null; 1988 | this.$node.addClass(this.classes.empty); 1989 | function clearDataset(dataset) { 1990 | dataset.clear(); 1991 | } 1992 | }, 1993 | destroy: function destroy() { 1994 | this.$node.off(".tt"); 1995 | this.$node = $("
"); 1996 | _.each(this.datasets, destroyDataset); 1997 | function destroyDataset(dataset) { 1998 | dataset.destroy(); 1999 | } 2000 | } 2001 | }); 2002 | return Menu; 2003 | }(); 2004 | var Status = function() { 2005 | "use strict"; 2006 | function Status(options) { 2007 | this.$el = $("", { 2008 | role: "status", 2009 | "aria-live": "polite" 2010 | }).css({ 2011 | position: "absolute", 2012 | padding: "0", 2013 | border: "0", 2014 | height: "1px", 2015 | width: "1px", 2016 | "margin-bottom": "-1px", 2017 | "margin-right": "-1px", 2018 | overflow: "hidden", 2019 | clip: "rect(0 0 0 0)", 2020 | "white-space": "nowrap" 2021 | }); 2022 | options.$input.after(this.$el); 2023 | _.each(options.menu.datasets, _.bind(function(dataset) { 2024 | if (dataset.onSync) { 2025 | dataset.onSync("rendered", _.bind(this.update, this)); 2026 | dataset.onSync("cleared", _.bind(this.cleared, this)); 2027 | } 2028 | }, this)); 2029 | } 2030 | _.mixin(Status.prototype, { 2031 | update: function update(event, suggestions) { 2032 | var length = suggestions.length; 2033 | var words; 2034 | if (length === 1) { 2035 | words = { 2036 | result: "result", 2037 | is: "is" 2038 | }; 2039 | } else { 2040 | words = { 2041 | result: "results", 2042 | is: "are" 2043 | }; 2044 | } 2045 | this.$el.text(length + " " + words.result + " " + words.is + " available, use up and down arrow keys to navigate."); 2046 | }, 2047 | cleared: function() { 2048 | this.$el.text(""); 2049 | } 2050 | }); 2051 | return Status; 2052 | }(); 2053 | var DefaultMenu = function() { 2054 | "use strict"; 2055 | var s = Menu.prototype; 2056 | function DefaultMenu() { 2057 | Menu.apply(this, [].slice.call(arguments, 0)); 2058 | } 2059 | _.mixin(DefaultMenu.prototype, Menu.prototype, { 2060 | open: function open() { 2061 | !this._allDatasetsEmpty() && this._show(); 2062 | return s.open.apply(this, [].slice.call(arguments, 0)); 2063 | }, 2064 | close: function close() { 2065 | this._hide(); 2066 | return s.close.apply(this, [].slice.call(arguments, 0)); 2067 | }, 2068 | _onRendered: function onRendered() { 2069 | if (this._allDatasetsEmpty()) { 2070 | this._hide(); 2071 | } else { 2072 | this.isOpen() && this._show(); 2073 | } 2074 | return s._onRendered.apply(this, [].slice.call(arguments, 0)); 2075 | }, 2076 | _onCleared: function onCleared() { 2077 | if (this._allDatasetsEmpty()) { 2078 | this._hide(); 2079 | } else { 2080 | this.isOpen() && this._show(); 2081 | } 2082 | return s._onCleared.apply(this, [].slice.call(arguments, 0)); 2083 | }, 2084 | setLanguageDirection: function setLanguageDirection(dir) { 2085 | this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl); 2086 | return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0)); 2087 | }, 2088 | _hide: function hide() { 2089 | this.$node.hide(); 2090 | }, 2091 | _show: function show() { 2092 | this.$node.css("display", "block"); 2093 | } 2094 | }); 2095 | return DefaultMenu; 2096 | }(); 2097 | var Typeahead = function() { 2098 | "use strict"; 2099 | function Typeahead(o, www) { 2100 | var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged; 2101 | o = o || {}; 2102 | if (!o.input) { 2103 | $.error("missing input"); 2104 | } 2105 | if (!o.menu) { 2106 | $.error("missing menu"); 2107 | } 2108 | if (!o.eventBus) { 2109 | $.error("missing event bus"); 2110 | } 2111 | www.mixin(this); 2112 | this.eventBus = o.eventBus; 2113 | this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; 2114 | this.input = o.input; 2115 | this.menu = o.menu; 2116 | this.enabled = true; 2117 | this.active = false; 2118 | this.input.hasFocus() && this.activate(); 2119 | this.dir = this.input.getLangDir(); 2120 | this._hacks(); 2121 | this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this); 2122 | onFocused = c(this, "activate", "open", "_onFocused"); 2123 | onBlurred = c(this, "deactivate", "_onBlurred"); 2124 | onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed"); 2125 | onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed"); 2126 | onEscKeyed = c(this, "isActive", "_onEscKeyed"); 2127 | onUpKeyed = c(this, "isActive", "open", "_onUpKeyed"); 2128 | onDownKeyed = c(this, "isActive", "open", "_onDownKeyed"); 2129 | onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed"); 2130 | onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed"); 2131 | onQueryChanged = c(this, "_openIfActive", "_onQueryChanged"); 2132 | onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged"); 2133 | this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this); 2134 | } 2135 | _.mixin(Typeahead.prototype, { 2136 | _hacks: function hacks() { 2137 | var $input, $menu; 2138 | $input = this.input.$input || $("
"); 2139 | $menu = this.menu.$node || $("
"); 2140 | $input.on("blur.tt", function($e) { 2141 | var active, isActive, hasActive; 2142 | active = document.activeElement; 2143 | isActive = $menu.is(active); 2144 | hasActive = $menu.has(active).length > 0; 2145 | if (_.isMsie() && (isActive || hasActive)) { 2146 | $e.preventDefault(); 2147 | $e.stopImmediatePropagation(); 2148 | _.defer(function() { 2149 | $input.focus(); 2150 | }); 2151 | } 2152 | }); 2153 | $menu.on("mousedown.tt", function($e) { 2154 | $e.preventDefault(); 2155 | }); 2156 | }, 2157 | _onSelectableClicked: function onSelectableClicked(type, $el) { 2158 | this.select($el); 2159 | }, 2160 | _onDatasetCleared: function onDatasetCleared() { 2161 | this._updateHint(); 2162 | }, 2163 | _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) { 2164 | this._updateHint(); 2165 | this.eventBus.trigger("render", suggestions, async, dataset); 2166 | }, 2167 | _onAsyncRequested: function onAsyncRequested(type, dataset, query) { 2168 | this.eventBus.trigger("asyncrequest", query, dataset); 2169 | }, 2170 | _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) { 2171 | this.eventBus.trigger("asynccancel", query, dataset); 2172 | }, 2173 | _onAsyncReceived: function onAsyncReceived(type, dataset, query) { 2174 | this.eventBus.trigger("asyncreceive", query, dataset); 2175 | }, 2176 | _onFocused: function onFocused() { 2177 | this._minLengthMet() && this.menu.update(this.input.getQuery()); 2178 | }, 2179 | _onBlurred: function onBlurred() { 2180 | if (this.input.hasQueryChangedSinceLastFocus()) { 2181 | this.eventBus.trigger("change", this.input.getQuery()); 2182 | } 2183 | }, 2184 | _onEnterKeyed: function onEnterKeyed(type, $e) { 2185 | var $selectable; 2186 | if ($selectable = this.menu.getActiveSelectable()) { 2187 | if (this.select($selectable)) { 2188 | $e.preventDefault(); 2189 | $e.stopPropagation(); 2190 | } 2191 | } 2192 | }, 2193 | _onTabKeyed: function onTabKeyed(type, $e) { 2194 | var $selectable; 2195 | if ($selectable = this.menu.getActiveSelectable()) { 2196 | this.select($selectable) && $e.preventDefault(); 2197 | } else if ($selectable = this.menu.getTopSelectable()) { 2198 | this.autocomplete($selectable) && $e.preventDefault(); 2199 | } 2200 | }, 2201 | _onEscKeyed: function onEscKeyed() { 2202 | this.close(); 2203 | }, 2204 | _onUpKeyed: function onUpKeyed() { 2205 | this.moveCursor(-1); 2206 | }, 2207 | _onDownKeyed: function onDownKeyed() { 2208 | this.moveCursor(+1); 2209 | }, 2210 | _onLeftKeyed: function onLeftKeyed() { 2211 | if (this.dir === "rtl" && this.input.isCursorAtEnd()) { 2212 | this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); 2213 | } 2214 | }, 2215 | _onRightKeyed: function onRightKeyed() { 2216 | if (this.dir === "ltr" && this.input.isCursorAtEnd()) { 2217 | this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); 2218 | } 2219 | }, 2220 | _onQueryChanged: function onQueryChanged(e, query) { 2221 | this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty(); 2222 | }, 2223 | _onWhitespaceChanged: function onWhitespaceChanged() { 2224 | this._updateHint(); 2225 | }, 2226 | _onLangDirChanged: function onLangDirChanged(e, dir) { 2227 | if (this.dir !== dir) { 2228 | this.dir = dir; 2229 | this.menu.setLanguageDirection(dir); 2230 | } 2231 | }, 2232 | _openIfActive: function openIfActive() { 2233 | this.isActive() && this.open(); 2234 | }, 2235 | _minLengthMet: function minLengthMet(query) { 2236 | query = _.isString(query) ? query : this.input.getQuery() || ""; 2237 | return query.length >= this.minLength; 2238 | }, 2239 | _updateHint: function updateHint() { 2240 | var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match; 2241 | $selectable = this.menu.getTopSelectable(); 2242 | data = this.menu.getSelectableData($selectable); 2243 | val = this.input.getInputValue(); 2244 | if (data && !_.isBlankString(val) && !this.input.hasOverflow()) { 2245 | query = Input.normalizeQuery(val); 2246 | escapedQuery = _.escapeRegExChars(query); 2247 | frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i"); 2248 | match = frontMatchRegEx.exec(data.val); 2249 | match && this.input.setHint(val + match[1]); 2250 | } else { 2251 | this.input.clearHint(); 2252 | } 2253 | }, 2254 | isEnabled: function isEnabled() { 2255 | return this.enabled; 2256 | }, 2257 | enable: function enable() { 2258 | this.enabled = true; 2259 | }, 2260 | disable: function disable() { 2261 | this.enabled = false; 2262 | }, 2263 | isActive: function isActive() { 2264 | return this.active; 2265 | }, 2266 | activate: function activate() { 2267 | if (this.isActive()) { 2268 | return true; 2269 | } else if (!this.isEnabled() || this.eventBus.before("active")) { 2270 | return false; 2271 | } else { 2272 | this.active = true; 2273 | this.eventBus.trigger("active"); 2274 | return true; 2275 | } 2276 | }, 2277 | deactivate: function deactivate() { 2278 | if (!this.isActive()) { 2279 | return true; 2280 | } else if (this.eventBus.before("idle")) { 2281 | return false; 2282 | } else { 2283 | this.active = false; 2284 | this.close(); 2285 | this.eventBus.trigger("idle"); 2286 | return true; 2287 | } 2288 | }, 2289 | isOpen: function isOpen() { 2290 | return this.menu.isOpen(); 2291 | }, 2292 | open: function open() { 2293 | if (!this.isOpen() && !this.eventBus.before("open")) { 2294 | this.menu.open(); 2295 | this._updateHint(); 2296 | this.eventBus.trigger("open"); 2297 | } 2298 | return this.isOpen(); 2299 | }, 2300 | close: function close() { 2301 | if (this.isOpen() && !this.eventBus.before("close")) { 2302 | this.menu.close(); 2303 | this.input.clearHint(); 2304 | this.input.resetInputValue(); 2305 | this.eventBus.trigger("close"); 2306 | } 2307 | return !this.isOpen(); 2308 | }, 2309 | setVal: function setVal(val) { 2310 | this.input.setQuery(_.toStr(val)); 2311 | }, 2312 | getVal: function getVal() { 2313 | return this.input.getQuery(); 2314 | }, 2315 | select: function select($selectable) { 2316 | var data = this.menu.getSelectableData($selectable); 2317 | if (data && !this.eventBus.before("select", data.obj, data.dataset)) { 2318 | this.input.setQuery(data.val, true); 2319 | this.eventBus.trigger("select", data.obj, data.dataset); 2320 | this.close(); 2321 | return true; 2322 | } 2323 | return false; 2324 | }, 2325 | autocomplete: function autocomplete($selectable) { 2326 | var query, data, isValid; 2327 | query = this.input.getQuery(); 2328 | data = this.menu.getSelectableData($selectable); 2329 | isValid = data && query !== data.val; 2330 | if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) { 2331 | this.input.setQuery(data.val); 2332 | this.eventBus.trigger("autocomplete", data.obj, data.dataset); 2333 | return true; 2334 | } 2335 | return false; 2336 | }, 2337 | moveCursor: function moveCursor(delta) { 2338 | var query, $candidate, data, suggestion, datasetName, cancelMove, id; 2339 | query = this.input.getQuery(); 2340 | $candidate = this.menu.selectableRelativeToCursor(delta); 2341 | data = this.menu.getSelectableData($candidate); 2342 | suggestion = data ? data.obj : null; 2343 | datasetName = data ? data.dataset : null; 2344 | id = $candidate ? $candidate.attr("id") : null; 2345 | this.input.trigger("cursorchange", id); 2346 | cancelMove = this._minLengthMet() && this.menu.update(query); 2347 | if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) { 2348 | this.menu.setCursor($candidate); 2349 | if (data) { 2350 | this.input.setInputValue(data.val); 2351 | } else { 2352 | this.input.resetInputValue(); 2353 | this._updateHint(); 2354 | } 2355 | this.eventBus.trigger("cursorchange", suggestion, datasetName); 2356 | return true; 2357 | } 2358 | return false; 2359 | }, 2360 | destroy: function destroy() { 2361 | this.input.destroy(); 2362 | this.menu.destroy(); 2363 | } 2364 | }); 2365 | return Typeahead; 2366 | function c(ctx) { 2367 | var methods = [].slice.call(arguments, 1); 2368 | return function() { 2369 | var args = [].slice.call(arguments); 2370 | _.each(methods, function(method) { 2371 | return ctx[method].apply(ctx, args); 2372 | }); 2373 | }; 2374 | } 2375 | }(); 2376 | (function() { 2377 | "use strict"; 2378 | var old, keys, methods; 2379 | old = $.fn.typeahead; 2380 | keys = { 2381 | www: "tt-www", 2382 | attrs: "tt-attrs", 2383 | typeahead: "tt-typeahead" 2384 | }; 2385 | methods = { 2386 | initialize: function initialize(o, datasets) { 2387 | var www; 2388 | datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1); 2389 | o = o || {}; 2390 | www = WWW(o.classNames); 2391 | return this.each(attach); 2392 | function attach() { 2393 | var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, status, typeahead, MenuConstructor; 2394 | _.each(datasets, function(d) { 2395 | d.highlight = !!o.highlight; 2396 | }); 2397 | $input = $(this); 2398 | $wrapper = $(www.html.wrapper); 2399 | $hint = $elOrNull(o.hint); 2400 | $menu = $elOrNull(o.menu); 2401 | defaultHint = o.hint !== false && !$hint; 2402 | defaultMenu = o.menu !== false && !$menu; 2403 | defaultHint && ($hint = buildHintFromInput($input, www)); 2404 | defaultMenu && ($menu = $(www.html.menu).css(www.css.menu)); 2405 | $hint && $hint.val(""); 2406 | $input = prepInput($input, www); 2407 | if (defaultHint || defaultMenu) { 2408 | $wrapper.css(www.css.wrapper); 2409 | $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint); 2410 | $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null); 2411 | } 2412 | MenuConstructor = defaultMenu ? DefaultMenu : Menu; 2413 | eventBus = new EventBus({ 2414 | el: $input 2415 | }); 2416 | input = new Input({ 2417 | hint: $hint, 2418 | input: $input 2419 | }, www); 2420 | menu = new MenuConstructor({ 2421 | node: $menu, 2422 | datasets: datasets 2423 | }, www); 2424 | status = new Status({ 2425 | $input: $input, 2426 | menu: menu 2427 | }); 2428 | typeahead = new Typeahead({ 2429 | input: input, 2430 | menu: menu, 2431 | eventBus: eventBus, 2432 | minLength: o.minLength 2433 | }, www); 2434 | $input.data(keys.www, www); 2435 | $input.data(keys.typeahead, typeahead); 2436 | } 2437 | }, 2438 | isEnabled: function isEnabled() { 2439 | var enabled; 2440 | ttEach(this.first(), function(t) { 2441 | enabled = t.isEnabled(); 2442 | }); 2443 | return enabled; 2444 | }, 2445 | enable: function enable() { 2446 | ttEach(this, function(t) { 2447 | t.enable(); 2448 | }); 2449 | return this; 2450 | }, 2451 | disable: function disable() { 2452 | ttEach(this, function(t) { 2453 | t.disable(); 2454 | }); 2455 | return this; 2456 | }, 2457 | isActive: function isActive() { 2458 | var active; 2459 | ttEach(this.first(), function(t) { 2460 | active = t.isActive(); 2461 | }); 2462 | return active; 2463 | }, 2464 | activate: function activate() { 2465 | ttEach(this, function(t) { 2466 | t.activate(); 2467 | }); 2468 | return this; 2469 | }, 2470 | deactivate: function deactivate() { 2471 | ttEach(this, function(t) { 2472 | t.deactivate(); 2473 | }); 2474 | return this; 2475 | }, 2476 | isOpen: function isOpen() { 2477 | var open; 2478 | ttEach(this.first(), function(t) { 2479 | open = t.isOpen(); 2480 | }); 2481 | return open; 2482 | }, 2483 | open: function open() { 2484 | ttEach(this, function(t) { 2485 | t.open(); 2486 | }); 2487 | return this; 2488 | }, 2489 | close: function close() { 2490 | ttEach(this, function(t) { 2491 | t.close(); 2492 | }); 2493 | return this; 2494 | }, 2495 | select: function select(el) { 2496 | var success = false, $el = $(el); 2497 | ttEach(this.first(), function(t) { 2498 | success = t.select($el); 2499 | }); 2500 | return success; 2501 | }, 2502 | autocomplete: function autocomplete(el) { 2503 | var success = false, $el = $(el); 2504 | ttEach(this.first(), function(t) { 2505 | success = t.autocomplete($el); 2506 | }); 2507 | return success; 2508 | }, 2509 | moveCursor: function moveCursoe(delta) { 2510 | var success = false; 2511 | ttEach(this.first(), function(t) { 2512 | success = t.moveCursor(delta); 2513 | }); 2514 | return success; 2515 | }, 2516 | val: function val(newVal) { 2517 | var query; 2518 | if (!arguments.length) { 2519 | ttEach(this.first(), function(t) { 2520 | query = t.getVal(); 2521 | }); 2522 | return query; 2523 | } else { 2524 | ttEach(this, function(t) { 2525 | t.setVal(_.toStr(newVal)); 2526 | }); 2527 | return this; 2528 | } 2529 | }, 2530 | destroy: function destroy() { 2531 | ttEach(this, function(typeahead, $input) { 2532 | revert($input); 2533 | typeahead.destroy(); 2534 | }); 2535 | return this; 2536 | } 2537 | }; 2538 | $.fn.typeahead = function(method) { 2539 | if (methods[method]) { 2540 | return methods[method].apply(this, [].slice.call(arguments, 1)); 2541 | } else { 2542 | return methods.initialize.apply(this, arguments); 2543 | } 2544 | }; 2545 | $.fn.typeahead.noConflict = function noConflict() { 2546 | $.fn.typeahead = old; 2547 | return this; 2548 | }; 2549 | function ttEach($els, fn) { 2550 | $els.each(function() { 2551 | var $input = $(this), typeahead; 2552 | (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input); 2553 | }); 2554 | } 2555 | function buildHintFromInput($input, www) { 2556 | return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly", true).removeAttr("id name placeholder required").attr({ 2557 | spellcheck: "false", 2558 | tabindex: -1 2559 | }); 2560 | } 2561 | function prepInput($input, www) { 2562 | $input.data(keys.attrs, { 2563 | dir: $input.attr("dir"), 2564 | autocomplete: $input.attr("autocomplete"), 2565 | spellcheck: $input.attr("spellcheck"), 2566 | style: $input.attr("style") 2567 | }); 2568 | $input.addClass(www.classes.input).attr({ 2569 | spellcheck: false 2570 | }); 2571 | try { 2572 | !$input.attr("dir") && $input.attr("dir", "auto"); 2573 | } catch (e) {} 2574 | return $input; 2575 | } 2576 | function getBackgroundStyles($el) { 2577 | return { 2578 | backgroundAttachment: $el.css("background-attachment"), 2579 | backgroundClip: $el.css("background-clip"), 2580 | backgroundColor: $el.css("background-color"), 2581 | backgroundImage: $el.css("background-image"), 2582 | backgroundOrigin: $el.css("background-origin"), 2583 | backgroundPosition: $el.css("background-position"), 2584 | backgroundRepeat: $el.css("background-repeat"), 2585 | backgroundSize: $el.css("background-size") 2586 | }; 2587 | } 2588 | function revert($input) { 2589 | var www, $wrapper; 2590 | www = $input.data(keys.www); 2591 | $wrapper = $input.parent().filter(www.selectors.wrapper); 2592 | _.each($input.data(keys.attrs), function(val, key) { 2593 | _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); 2594 | }); 2595 | $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input); 2596 | if ($wrapper.length) { 2597 | $input.detach().insertAfter($wrapper); 2598 | $wrapper.remove(); 2599 | } 2600 | } 2601 | function $elOrNull(obj) { 2602 | var isValid, $el; 2603 | isValid = _.isJQuery(obj) || _.isElement(obj); 2604 | $el = isValid ? $(obj).first() : []; 2605 | return $el.length ? $el : null; 2606 | } 2607 | })(); 2608 | }); --------------------------------------------------------------------------------