Debian Codegraph @

docs/assets/js/alpinejs/data/search.js

raw
1 import { LRUCache } from '../../helpers';
2
3 const designMode = false;
4
5 const groupByLvl0 = (array) => {
6 if (!array) return [];
7 return array.reduce((result, currentValue) => {
8 (result[currentValue.hierarchy.lvl0] = result[currentValue.hierarchy.lvl0] || []).push(currentValue);
9 return result;
10 }, {});
11 };
12
13 const adjustHits = (array, isServer) => {
14 if (!array) return [];
15 return array.map((item) => {
16 item.getHeadingHTML = function () {
17 let lvl2 = this._highlightResult.hierarchy.lvl2;
18 let lvl3 = this._highlightResult.hierarchy.lvl3;
19
20 if (!lvl3) {
21 if (lvl2) {
22 return lvl2.value;
23 }
24 return '';
25 }
26
27 if (!lvl2) {
28 return lvl3.value;
29 }
30
31 return `${lvl2.value} <span class="text-gray-500">&nbsp;>&nbsp;</span> ${lvl3.value}`;
32 };
33
34 if (isServer) {
35 // Trim https://gohugo.io from the url to make it work locally.
36 item.url = item.url.replace('https://gohugo.io', '');
37 }
38 return item;
39 });
40 };
41
42 export const search = (Alpine, cfg) => ({
43 query: designMode ? 'apac' : '',
44 open: designMode,
45 result: {},
46 cache: new LRUCache(10), // Small cache, avoids network requests on e.g. backspace.
47 init() {
48 Alpine.bind(this.$root, this.root);
49
50 this.checkOpen();
51 return this.$nextTick(() => {
52 this.$watch('query', () => {
53 this.search();
54 });
55 });
56 },
57 toggleOpen: function () {
58 this.open = !this.open;
59 this.checkOpen();
60 },
61 checkOpen: function () {
62 if (!this.open) {
63 return;
64 }
65 this.search();
66 this.$nextTick(() => {
67 this.$refs.input.focus();
68 });
69 },
70
71 search: function () {
72 if (!this.query) {
73 this.result = {};
74 return;
75 }
76
77 // Check cache first.
78 const cached = this.cache.get(this.query);
79 if (cached) {
80 this.result = cached;
81 return;
82 }
83 var queries = {
84 requests: [
85 {
86 indexName: cfg.index,
87 params: `query=${encodeURIComponent(this.query)}`,
88 attributesToHighlight: ['hierarchy', 'content'],
89 attributesToRetrieve: ['hierarchy', 'url', 'content'],
90 },
91 ],
92 };
93
94 const host = `https://${cfg.app_id}-dsn.algolia.net`;
95 const url = `${host}/1/indexes/*/queries`;
96
97 fetch(url, {
98 method: 'POST',
99 headers: {
100 'X-Algolia-Application-Id': cfg.app_id,
101 'X-Algolia-API-Key': cfg.api_key,
102 },
103 body: JSON.stringify(queries),
104 })
105 .then((response) => response.json())
106 .then((data) => {
107 this.result = groupByLvl0(adjustHits(data.results[0].hits, cfg.params.isServer));
108 this.cache.put(this.query, this.result);
109 });
110 },
111 root: {
112 ['@click']() {
113 if (!this.open) {
114 this.toggleOpen();
115 }
116 },
117 ['@search-toggle.window']() {
118 this.toggleOpen();
119 },
120 ['@keydown.slash.window.prevent']() {
121 this.toggleOpen();
122 },
123 },
124 });