{"size": 1921, "ext": "js", "max_stars_repo_path": "packages/search/addon/components/navi-search-bar.js", "max_stars_repo_name": "kevinhinterlong/navi", "max_stars_repo_stars_event_min_datetime": "2021-03-22T21:44:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T15:30:29.000Z", "max_issues_repo_path": "packages/search/addon/components/navi-search-bar.js", "max_issues_repo_name": "kevinhinterlong/navi", "max_issues_repo_issues_event_min_datetime": "2021-03-12T22:05:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:03:19.000Z", "max_forks_repo_path": "packages/search/addon/components/navi-search-bar.js", "max_forks_repo_name": "kevinhinterlong/navi", "max_forks_repo_forks_event_min_datetime": "2021-03-12T22:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T17:58:05.000Z"}
{"max_stars_count": 10, "max_issues_count": 146, "max_forks_count": 5, "avg_line_length": 24.9480519481, "max_line_length": 104, "alphanum_fraction": 0.6553878188}
/**
 * Copyright 2020, Yahoo Holdings Inc.
 * Licensed under the terms of the MIT license. See accompanying LICENSE.md file for terms.
 *
 * Navi Search Bar
 */

import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { task, timeout } from 'ember-concurrency';

/**
 * @constant ENTER_KEY
 */
const ENTER_KEY = 13;

/**
 * @constant ESCAPE_KEY
 */
const ESCAPE_KEY = 27;

/**
 * @constant DEBOUNCE_MS
 */
const DEBOUNCE_MS = 250;

export default class NaviSearchBarComponent extends Component {
  /**
   * @property {Ember.Service} searchProviderService
   */
  @service('navi-search-provider') searchProviderService;

  /**
   * @property {String} searchQuery
   */
  @tracked searchQuery = '';

  /**
   * @method onKeyUp – Perform search based on user query
   * @param {Object} dd
   * @param {Object} event
   */
  @action
  onKeyUp(dd, event) {
    // Close results window if the user deletes the query or presses escape
    if (this.searchQuery.length === 0 || event.keyCode === ESCAPE_KEY) {
      // Empty results if search query is deleted
      if (this.searchQuery.length === 0) {
        this.searchResults = [];
      }

      dd.actions.close(event);
      // Don't perform query if you press escape or delete query
      return;
    }

    // Perform search on enter press or when there's a search query
    if ((event.keyCode === ENTER_KEY && this.searchQuery.length !== 0) || this.searchQuery.length > 0) {
      dd.actions.open(event);
      this.launchQuery.perform(this.searchQuery, dd, event);
    }
  }

  /**
   * @method launchQuery – Launch search task
   * @param {String} query
   * @returns {Array} results
   */
  @task({ restartable: true })
  *launchQuery(query) {
    yield timeout(DEBOUNCE_MS);
    return this.searchProviderService.search(query);
  }
}
