-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
algolia-search.component.ts
73 lines (57 loc) · 1.65 KB
/
algolia-search.component.ts
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
import { Component, ChangeDetectorRef, ElementRef, AfterViewInit, Input, HostListener, ViewChild } from '@angular/core';
import * as algolia from 'algoliasearch/lite';
const APP_ID = '05VYZFXKNM';
const API_KEY = 'a0837b31f4379765240c2753fa141aa2';
const client = algolia(APP_ID, API_KEY);
@Component({
templateUrl: './algolia-search.component.html'
})
export class AlgoliaSearchComponent implements AfterViewInit {
constructor(private cd: ChangeDetectorRef, private el: ElementRef) { }
index = client.initIndex('content');
emojiMap = {
lessons: '📺',
courses: '🎒',
tags: '🔖',
contributors: '🤓',
snippets: '✂️',
page: '📃'
};
visible = false;
query: string;
hits: any[];
results: any;
@ViewChild('searchInput') searchInput: ElementRef;
// Public toggles
@Input() show = () => this.toggle(true);
@Input() hide = () => this.toggle(false);
@HostListener('document:keydown', ['$event'])
keyDownHandler(e: KeyboardEvent) {
if (e.ctrlKey && e.shiftKey && e.code === 'KeyP') {
// Ctrl + Shift + P shortcut to open the search box
e.preventDefault();
this.toggle(true);
} else if (e.code === 'Escape') {
// ESC to close the search box
this.toggle(false);
}
}
ngAfterViewInit() {
}
toggle(val) {
this.visible = val;
// Focus the input element
this.searchInput.nativeElement.focus();
this.cd.detectChanges();
}
handleSearch(query) {
this.query = query;
this.index.search({ query }, (err, res) => {
this.results = res;
this.hits = res.hits;
this.cd.detectChanges();
}
);
this.cd.detectChanges();
}
}