angelakuo/citydogshare

View on GitHub
public/assets/semantic-ui/search-edf600c5e5e5544d678503d4f6dd6be00e03e76f2a77166da81da306cc851ea7.js

Summary

Maintainability
F
1 wk
Test Coverage
/*
 * # Semantic - Search
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Copyright 2014 Contributor
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */


;(function ($, window, document, undefined) {

"use strict";

$.fn.search = function(parameters) {
  var
    $allModules     = $(this),
    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),
    returnedValue
  ;
  $(this)
    .each(function() {
      var
        settings        = $.extend(true, {}, $.fn.search.settings, parameters),

        className       = settings.className,
        metadata        = settings.metadata,
        regExp          = settings.regExp,
        selector        = settings.selector,
        error           = settings.error,
        namespace       = settings.namespace,

        eventNamespace  = '.' + namespace,
        moduleNamespace = namespace + '-module',

        $module         = $(this),
        $prompt         = $module.find(selector.prompt),
        $searchButton   = $module.find(selector.searchButton),
        $results        = $module.find(selector.results),
        $result         = $module.find(selector.result),
        $category       = $module.find(selector.category),

        element         = this,
        instance        = $module.data(moduleNamespace),

        module
      ;
      module = {

        initialize: function() {
          module.verbose('Initializing module');
          var
            prompt = $prompt[0],
            inputEvent   = (prompt !== undefined && prompt.oninput !== undefined)
              ? 'input'
              : (prompt !== undefined && prompt.onpropertychange !== undefined)
                ? 'propertychange'
                : 'keyup'
          ;
          if(settings.automatic) {
            $prompt
              .on(inputEvent + eventNamespace, module.throttle)
            ;
          }
          $prompt
            .on('focus' + eventNamespace, module.event.focus)
            .on('blur' + eventNamespace, module.event.blur)
            .on('keydown' + eventNamespace, module.handleKeyboard)
          ;
          $searchButton
            .on('click' + eventNamespace, module.query)
          ;
          $results
            .on('mousedown' + eventNamespace, module.event.result.mousedown)
            .on('mouseup' + eventNamespace, module.event.result.mouseup)
            .on('click' + eventNamespace, selector.result, module.event.result.click)
          ;
          module.instantiate();
        },
        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },
        destroy: function() {
          module.verbose('Destroying instance');
          $module
            .removeData(moduleNamespace)
          ;
          $prompt
            .off(eventNamespace)
          ;
          $searchButton
            .off(eventNamespace)
          ;
          $results
            .off(eventNamespace)
          ;
        },
        event: {
          focus: function() {
            module.set.focus();
            clearTimeout(module.timer);
            module.throttle();
            if( module.has.minimumCharacters() ) {
              module.showResults();
            }
          },
          blur: function(event) {
            var
              pageLostFocus = (document.activeElement === this)
            ;
            if(!pageLostFocus && !module.resultsClicked) {
              module.cancel.query();
              module.remove.focus();
              module.timer = setTimeout(module.hideResults, settings.hideDelay);
            }
          },
          result: {
            mousedown: function() {
              module.resultsClicked = true;
            },
            mouseup: function() {
              module.resultsClicked = false;
            },
            click: function(event) {
              module.debug('Search result selected');
              var
                $result = $(this),
                $title  = $result.find(selector.title).eq(0),
                $link   = $result.find('a[href]').eq(0),
                href    = $link.attr('href')   || false,
                target  = $link.attr('target') || false,
                title   = $title.html(),
                name    = ($title.length > 0)
                  ? $title.text()
                  : false,
                results = module.get.results(),
                result  = module.get.result(name, results),
                returnedValue
              ;
              if( $.isFunction(settings.onSelect) ) {
                if(settings.onSelect.call(element, result, results) === false) {
                  module.debug('Custom onSelect callback cancelled default select action');
                  return;
                }
              }
              module.hideResults();
              if(name) {
                module.set.value(name);
              }
              if(href) {
                module.verbose('Opening search link found in result', $link);
                if(target == '_blank' || event.ctrlKey) {
                  window.open(href);
                }
                else {
                  window.location.href = (href);
                }
              }
            }
          }
        },
        handleKeyboard: function(event) {
          var
            // force selector refresh
            $result      = $module.find(selector.result),
            $category    = $module.find(selector.category),
            currentIndex = $result.index( $result.filter('.' + className.active) ),
            resultSize   = $result.length,

            keyCode      = event.which,
            keys         = {
              backspace : 8,
              enter     : 13,
              escape    : 27,
              upArrow   : 38,
              downArrow : 40
            },
            newIndex
          ;
          // search shortcuts
          if(keyCode == keys.escape) {
            module.verbose('Escape key pressed, blurring search field');
            $prompt
              .trigger('blur')
            ;
          }
          if( module.is.visible() ) {
            if(keyCode == keys.enter) {
              module.verbose('Enter key pressed, selecting active result');
              if( $result.filter('.' + className.active).length > 0 ) {
                module.event.result.click.call($result.filter('.' + className.active), event);
                event.preventDefault();
                return false;
              }
            }
            else if(keyCode == keys.upArrow) {
              module.verbose('Up key pressed, changing active result');
              newIndex = (currentIndex - 1 < 0)
                ? currentIndex
                : currentIndex - 1
              ;
              $category
                .removeClass(className.active)
              ;
              $result
                .removeClass(className.active)
                .eq(newIndex)
                  .addClass(className.active)
                  .closest($category)
                    .addClass(className.active)
              ;
              event.preventDefault();
            }
            else if(keyCode == keys.downArrow) {
              module.verbose('Down key pressed, changing active result');
              newIndex = (currentIndex + 1 >= resultSize)
                ? currentIndex
                : currentIndex + 1
              ;
              $category
                .removeClass(className.active)
              ;
              $result
                .removeClass(className.active)
                .eq(newIndex)
                  .addClass(className.active)
                  .closest($category)
                    .addClass(className.active)
              ;
              event.preventDefault();
            }
          }
          else {
            // query shortcuts
            if(keyCode == keys.enter) {
              module.verbose('Enter key pressed, executing query');
              module.query();
              module.set.buttonPressed();
              $prompt.one('keyup', module.remove.buttonFocus);
            }
          }
        },

        setup: {
          api: function() {
            var
              apiSettings = {
                on        : false,
                action    : 'search',
                onFailure : module.error
              },
              searchHTML
            ;
            module.verbose('First request, initializing API');
            $module.api(apiSettings);
          }
        },

        can: {
          useAPI: function() {
            return $.fn.api !== undefined;
          },
          transition: function() {
            return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
          }
        },

        is: {
          empty: function() {
            return ($results.html() === '');
          },
          visible: function() {
            return ($results.filter(':visible').length > 0);
          },
          focused: function() {
            return ($prompt.filter(':focus').length > 0);
          }
        },

        get: {
          value: function() {
            return $prompt.val();
          },
          results: function() {
            var
              results = $module.data(metadata.results)
            ;
            return results;
          },
          result: function(value, results) {
            var
              result = false
            ;
            value = value || module.get.value();
            results = results || module.get.results();
            if(settings.type === 'category') {
              module.debug('Finding result from category results', value);
              $.each(results, function(index, category) {
                if(category.results !== undefined) {
                  result = module.search.object(value, category.results)[0];
                  if(result.length > 0) {
                    return true;
                  }
                }
              });
            }
            else {
              module.debug('Finding result in results object', value);
              result = module.search.object(value, results)[0];
            }
            return result;
          },
        },

        set: {
          focus: function() {
            $module.addClass(className.focus);
          },
          loading: function() {
            $module.addClass(className.loading);
          },
          value: function(value) {
            module.verbose('Setting search input value', value);
            $prompt.val(value);
          },
          buttonPressed: function() {
            $searchButton.addClass(className.pressed);
          }
        },

        remove: {
          loading: function() {
            $module.removeClass(className.loading);
          },
          focus: function() {
            $module.removeClass(className.focus);
          },
          buttonPressed: function() {
            $searchButton.removeClass(className.pressed);
          }
        },

        query: function() {
          var
            searchTerm = module.get.value(),
            cachedHTML = module.read.cachedHTML(searchTerm)
          ;
          if(cachedHTML) {
            module.debug('Reading result for ' + searchTerm + ' from cache');
            module.addResults(cachedHTML);
          }
          else {
            module.debug('Querying for ' + searchTerm);
            if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
              module.search.local(searchTerm);
            }
            else if( module.can.useAPI() ) {
              if(settings.apiSettings) {
                module.debug('Searching with specified API settings', settings.apiSettings);
                module.search.remote(searchTerm);
              }
              else if($.api.settings.api.search !== undefined) {
                module.debug('Searching with default search API endpoint');
                module.search.remote(searchTerm);
              }
            }
            else {
              module.error(error.source);
            }
            settings.onSearchQuery.call(element, searchTerm);
          }
        },

        search: {
          local: function(searchTerm) {
            var
              searchResults = module.search.object(searchTerm, settings.content),
              searchHTML
            ;
            module.set.loading();
            module.save.results(searchResults);
            module.debug('Returned local search results', searchResults);

            searchHTML = module.generateResults({
              results: searchResults
            });
            module.remove.loading();
            module.write.cachedHTML(searchTerm, searchHTML);
            module.addResults(searchHTML);
          },
          remote: function(searchTerm) {
            var
              apiSettings = {
                onSuccess : function(response) {
                  module.parse.response.call(element, response, searchTerm);
                },
                urlData: {
                  query: searchTerm
                }
              }
            ;
            if( !$module.api('get request') ) {
              module.setup.api();
            }
            $.extend(true, apiSettings, settings.apiSettings);
            module.debug('Executing search', apiSettings);
            module.cancel.query();
            $module
              .api('setting', apiSettings)
              .api('query')
            ;
          },
          object: function(searchTerm, source) {
            var
              results         = [],
              fullTextResults = [],
              searchFields    = $.isArray(settings.searchFields)
                ? settings.searchFields
                : [settings.searchFields],
              searchRegExp    = new RegExp(regExp.exact + searchTerm, 'i'),
              fullTextRegExp  = new RegExp(searchTerm, 'i')
            ;

            source = source || settings.source;

            // exit conditions on no source
            if(source === undefined) {
              module.error(error.source);
              return [];
            }

            // iterate through search fields in array order
            $.each(searchFields, function(index, field) {
              $.each(source, function(label, content) {
                var
                  fieldExists = (typeof content[field] == 'string'),
                  notAlreadyResult = ($.inArray(content, results) == -1 && $.inArray(content, fullTextResults) == -1)
                ;
                if(fieldExists && notAlreadyResult) {
                  if( content[field].match(searchRegExp) ) {
                    results.push(content);
                  }
                  else if( settings.searchFullText && content[field].match(fullTextRegExp) ) {
                    fullTextResults.push(content);
                  }
                }
              });
            });
            return $.merge(results, fullTextResults);
          }
        },

        parse: {
          response: function(response, searchTerm) {
            var
              searchHTML = module.generateResults(response)
            ;
            module.verbose('Parsing server response', response);
            if(response !== undefined) {
              if(searchTerm) {
                module.write.cachedHTML(searchTerm, searchHTML);
                if(response.results !== undefined) {
                  module.save.results(response.results);
                }
              }
              module.addResults(searchHTML);
            }
          }
        },

        throttle: function() {
          clearTimeout(module.timer);
          if(module.has.minimumCharacters())  {
            module.timer = setTimeout(module.query, settings.searchDelay);
          }
          else {
            module.hideResults();
          }
        },

        cancel: {
          query: function() {
            if( module.can.useAPI() ) {
              $module.api('abort');
            }
          }
        },

        has: {
          minimumCharacters: function() {
            var
              searchTerm    = module.get.value(),
              numCharacters = searchTerm.length
            ;
            return (numCharacters >= settings.minCharacters);
          }
        },

        read: {
          cachedHTML: function(name) {
            var
              cache = $module.data(metadata.cache)
            ;
            if(settings.cache) {
              module.verbose('Checking cache for generated html for query', name);
              return (typeof cache == 'object') && (cache[name] !== undefined)
                ? cache[name]
                : false
              ;
            }
            return false;
          }
        },

        save: {
          results: function(results) {
            module.verbose('Saving current search results to metadata', results);
            $module.data(metadata.results, results);
          }
        },

        write: {
          cachedHTML: function(name, value) {
            var
              cache = ($module.data(metadata.cache) !== undefined)
                ? $module.data(metadata.cache)
                : {}
            ;
            if(settings.cache) {
              module.verbose('Writing generated html to cache', name, value);
              cache[name] = value;
              $module
                .data(metadata.cache, cache)
              ;
            }
          }
        },

        addResults: function(html) {
          if( $.isFunction(settings.onResultsAdd) ) {
            if( settings.onResultsAdd.call($results, html) === false ) {
              module.debug('onResultsAdd callback cancelled default action');
              return false;
            }
          }
          $results
            .html(html)
          ;
          module.showResults();
        },

        showResults: function() {
          if( !module.is.visible() && module.is.focused() && !module.is.empty() ) {
            if( module.can.transition() ) {
              module.debug('Showing results with css animations');
              $results
                .transition({
                  animation  : settings.transition + ' in',
                  duration   : settings.duration,
                  queue      : true
                })
              ;
            }
            else {
              module.debug('Showing results with javascript');
              $results
                .stop()
                .fadeIn(settings.duration, settings.easing)
              ;
            }
            settings.onResultsOpen.call($results);
          }
        },
        hideResults: function() {
          if( module.is.visible() ) {
            if( module.can.transition() ) {
              module.debug('Hiding results with css animations');
              $results
                .transition({
                  animation  : settings.transition + ' out',
                  duration   : settings.duration,
                  queue      : true
                })
              ;
            }
            else {
              module.debug('Hiding results with javascript');
              $results
                .stop()
                .fadeOut(settings.duration, settings.easing)
              ;
            }
            settings.onResultsClose.call($results);
          }
        },

        generateResults: function(response) {
          module.debug('Generating html from response', response);
          var
            template       = settings.templates[settings.type],
            isProperObject = ($.isPlainObject(response.results) && !$.isEmptyObject(response.results)),
            isProperArray  = ($.isArray(response.results) && response.results.length > 0),
            html           = ''
          ;
          if(isProperObject || isProperArray ) {
            if(settings.maxResults > 0) {
              if(isProperObject) {
                module.error(error.maxResults);
              }
              else {
                response.results = response.results.slice(0, settings.maxResults);
              }
            }
            if($.isFunction(template)) {
              html = template(response);
            }
            else {
              module.error(error.noTemplate, false);
            }
          }
          else {
            html = module.displayMessage(error.noResults, 'empty');
          }
          settings.onResults.call(element, response);
          return html;
        },

        displayMessage: function(text, type) {
          type = type || 'standard';
          module.debug('Displaying message', text, type);
          module.addResults( settings.templates.message(text, type) );
          return settings.templates.message(text, type);
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
          module.error.apply(console, arguments);
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 100);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.length > 1) {
              title += ' ' + '(' + $allModules.length + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };
      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          module.destroy();
        }
        module.initialize();
      }

    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.search.settings = {

  name           : 'Search Module',
  namespace      : 'search',

  debug          : false,
  verbose        : true,
  performance    : true,

  type           : 'standard',
  minCharacters  : 1,

  // api config
  apiSettings    : false,

  source         : false,
  searchFields   : [
    'title',
    'description'
  ],
  searchFullText : true,

  automatic      : 'true',
  hideDelay      : 0,
  searchDelay    : 100,
  maxResults     : 7,
  cache          : true,

  transition     : 'scale',
  duration       : 300,
  easing         : 'easeOutExpo',

  onSelect       : false,
  onResultsAdd   : false,

  onSearchQuery  : function(){},
  onResults      : function(response){},

  onResultsOpen  : function(){},
  onResultsClose : function(){},

  className: {
    active  : 'active',
    empty   : 'empty',
    focus   : 'focus',
    loading : 'loading',
    pressed : 'down'
  },

  error : {
    source      : 'Cannot search. No source used, and Semantic API module was not included',
    noResults   : 'Your search returned no results',
    logging     : 'Error in debug logging, exiting.',
    noTemplate  : 'A valid template name was not specified.',
    serverError : 'There was an issue with querying the server.',
    maxResults  : 'Results must be an array to use maxResults setting',
    method      : 'The method you called is not defined.'
  },

  metadata: {
    cache   : 'cache',
    results : 'results'
  },

  regExp: {
    exact: '(?:\s|^)'
  },

  selector : {
    prompt       : '.prompt',
    searchButton : '.search.button',
    results      : '.results',
    category     : '.category',
    result       : '.result',
    title        : '.title, .name'
  },

  templates: {
    escape: function(string) {
      var
        badChars     = /[&<>"'`]/g,
        shouldEscape = /[&<>"'`]/,
        escape       = {
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#x27;",
          "`": "&#x60;"
        },
        escapedChar  = function(chr) {
          return escape[chr];
        }
      ;
      if(shouldEscape.test(string)) {
        return string.replace(badChars, escapedChar);
      }
      return string;
    },
    message: function(message, type) {
      var
        html = ''
      ;
      if(message !== undefined && type !== undefined) {
        html +=  ''
          + '<div class="message ' + type + '">'
        ;
        // message type
        if(type == 'empty') {
          html += ''
            + '<div class="header">No Results</div class="header">'
            + '<div class="description">' + message + '</div class="description">'
          ;
        }
        else {
          html += ' <div class="description">' + message + '</div>';
        }
        html += '</div>';
      }
      return html;
    },
    category: function(response) {
      var
        html = '',
        escape = $.fn.search.settings.templates.escape
      ;
      if(response.results !== undefined) {
        // each category
        $.each(response.results, function(index, category) {
          if(category.results !== undefined && category.results.length > 0) {
            html  += ''
              + '<div class="category">'
              + '<div class="name">' + category.name + '</div>'
            ;
            // each item inside category
            $.each(category.results, function(index, result) {
              html  += '<div class="result">';
              if(result.url) {
                html  += '<a href="' + result.url + '"></a>';
              }
              if(result.image !== undefined) {
                result.image = escape(result.image);
                html += ''
                  + '<div class="image">'
                  + ' <img src="' + result.image + '" alt="">'
                  + '</div>'
                ;
              }
              html += '<div class="content">';
              if(result.price !== undefined) {
                result.price = escape(result.price);
                html += '<div class="price">' + result.price + '</div>';
              }
              if(result.title !== undefined) {
                result.title = escape(result.title);
                html += '<div class="title">' + result.title + '</div>';
              }
              if(result.description !== undefined) {
                html += '<div class="description">' + result.description + '</div>';
              }
              html  += ''
                + '</div>'
                + '</div>'
              ;
            });
            html  += ''
              + '</div>'
            ;
          }
        });
        if(response.action) {
          html += ''
          + '<a href="' + response.action.url + '" class="action">'
          +   response.action.text
          + '</a>';
        }
        return html;
      }
      return false;
    },
    standard: function(response) {
      var
        html = ''
      ;
      if(response.results !== undefined) {

        // each result
        $.each(response.results, function(index, result) {
          if(result.url) {
            html  += '<a class="result" href="' + result.url + '">';
          }
          else {
            html  += '<a class="result">';
          }
          if(result.image !== undefined) {
            html += ''
              + '<div class="image">'
              + ' <img src="' + result.image + '">'
              + '</div>'
            ;
          }
          html += '<div class="content">';
          if(result.price !== undefined) {
            html += '<div class="price">' + result.price + '</div>';
          }
          if(result.title !== undefined) {
            html += '<div class="title">' + result.title + '</div>';
          }
          if(result.description !== undefined) {
            html += '<div class="description">' + result.description + '</div>';
          }
          html  += ''
            + '</div>'
          ;
          html += '</a>';
        });

        if(response.action) {
          html += ''
          + '<a href="' + response.action.url + '" class="action">'
          +   response.action.text
          + '</a>';
        }
        return html;
      }
      return false;
    }
  }
};

})( jQuery, window , document );