all files / src/app/components/common/ Search.js

100% Statements 35/35
93.75% Branches 15/16
100% Functions 8/8
100% Lines 35/35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                                      15× 15× 15× 15× 15× 15× 15×                                                                    
import {NO_QUERY, GITHUB_ONLY, BAD_QUERY} from '../../utils/error.constants';
 
const ALLOWED_HOST = 'github.com';
const REPO_PATH = /[^/]+\/([^/]+$)/;
const TRAILING_SLASH = /\/$/;
const RE_URL = new RegExp([
  '^(https?:)//', // protocol
  '(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
  '(/{0,1}[^?#]*)' // pathname
].join(''));
 
function getURL(href) {
  const match = href.match(RE_URL);
  return match && {
    protocol: match[1],
    host: match[2],
    hostname: match[3],
    port: match[4],
    pathname: match[5]
  };
}
 
class SearchController {
  /** @ngInject */
  constructor($window, $timeout, $state) {
    this.$window = $window;
    this.$timeout = $timeout;
    this.$state = $state;
    this.query = this.query || '';
    this.error = this.error || {};
    this.example = 'https://github.com/angular/angular';
    this.placeholder = 'angular/angular';
  }
 
  $onInit() {
    this.focus();
  }
 
  focus() {
    this.$timeout(() => {
      const element = this.$window.document.querySelector('.searchbar input');
      return element && element.focus();
    }, 0);
  }
 
  tryExample() {
    this.query = this.example;
    this.focus();
  }
 
  throwError(message) {
    this.error = {message};
  }
 
  search(query) {
    if (query) {
      this.error = {};
      const url = getURL(query);
 
      if (url) {
        if (url.host === ALLOWED_HOST) {
          query = url.pathname;
        } else {
          return this.throwError(GITHUB_ONLY);
        }
      }
 
      let repo = query.replace(TRAILING_SLASH, '').match(REPO_PATH);
 
      if (repo) {
        // Replacing the forward-slash to avoid ugly reformatting in the url
        const prettyPath = repo[0].replace('/', '::');
        repo = prettyPath;
        this.$state.go('repos', {repo});
      } else {
        return this.throwError(BAD_QUERY);
      }
    } else {
      return this.throwError(NO_QUERY);
    }
  }
}
 
export const Search = {
  template: require('./Search.html'),
  controller: SearchController
};