mirror of https://github.com/onweru/compose.git

weru
13.37.2020 02659eaa018774735c428123e9746f5cb8d8c349
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
89
90
91
const idx = [
  {{- range .Site.Pages }}
  {
    "link": "{{ .Permalink }}",
    "title": "{{ .Title }}",
    "body": "{{ .PlainWords }}".toLowerCase(),
  },
  {{- end }}
];
 
const searchKeys = ['title', 'link', 'body', 'id'];
const searchOptions = {
  ignoreLocation: true,
  findAllMatches: true,
  includeScore: true,
  shouldSort: true,
  keys: searchKeys,
  threshold: 0.0
};
 
const index = new Fuse(idx, searchOptions);
 
function searchResults(results=[], query="") {
  let resultsFragment = new DocumentFragment();
  let showResults = elem('.search_results');
  emptyEl(showResults);
  if(results.length) {
    let resultsTitle = createEl('h3');
    resultsTitle.className = 'search_title';
    resultsTitle.innerText = 'Quick Links';
    resultsFragment.appendChild(resultsTitle);
    results.slice(0,4).forEach(function(result){
      let item = createEl('a');
      item.href = `${result.link}?query=${query}`;
      item.className = 'search_result';
      item.textContent = result.title;
      item.style.order = result.score;
      resultsFragment.appendChild(item);
    });
  } else {
    showResults.innerHTML = (query.length >= 3) ? `<span class="search_result">No Results</span>` : "";
  }
  showResults.appendChild(resultsFragment);
}
 
function search(){
  const searchField = elem('.search_field');
 
  if (searchField) {
    searchField.addEventListener('input', function() {
      const searchTerm = this.value.trim().toLowerCase();
      if(searchTerm.length >= 3) {
        let rawResults = index.search(searchTerm);
        // console.log(rawResults);
        rawResults = rawResults.map(function(result){
          const score = result.score;
          const resultItem = result.item;
          resultItem.score = (parseFloat(score) * 50).toFixed(0);
          return resultItem;
        });
        // console.log(rawResults);
        searchResults(rawResults, searchTerm);
      } else {
        searchResults();
      }
    });
  }
}
 
function findQuery(query = 'query') {
  const urlParams = new URLSearchParams(window.location.search);
  if(urlParams.has(query)){
    let c = urlParams.get(query);
    // window.find(c);
    cc = `${c.charAt(0).toUpperCase()}${c.substring(1,c.length)}`;
    // window.find(cc);
    return [c, cc];
  }
  return ["",""];
}
 
let main = elem('main');
if(!main) {
  main = elem('.main');
}
const searchQuery = findQuery();
// console.log(searchQuery);
wrapText(searchQuery[0],main);
wrapText(searchQuery[1],main);
 
window.addEventListener('load', () => search());