import Vue from 'https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.16/vue.esm.browser.min.js';
import axios from 'https://cdnjs.cloudflare.com/ajax/libs/axios/1.8.4/esm/axios.min.js';
import {cleanQueryString, constructIndex, debounce, searchIndex} from 'https://uhk.io/wp-content/plugins/uhk-knowledgebase/js/util.js';
Vue.directive('focus', {
inserted(el){
el.focus();
}});
let allArticles=[];
Vue.component('knowledgebase-search', {
template: '#knowledgebase-search-template',
watch: {
query(newQuery, oldQuery){
debounce(()=> {
if(newQuery.length > 2&&oldQuery.toLowerCase().indexOf(newQuery.toLowerCase())===-1){
const query=this.query.replace(/\s\s+/g, ' ');
if(search.isAdmin){
console.log(`Log "${query}"`);
}else{
axios.get(search.url, {params: {q:query, action:search.action}});
}}
}, 1000);
},
},
async mounted(){
allArticles=(await axios.get('/wp-json/knowledgebase/articles.json')).data;
constructIndex(allArticles);
this.search();
},
data(){
return {
results: [],
query: new URLSearchParams(window.location.search).get('q')||'',
}},
methods: {
search(event){
const query=cleanQueryString(event ? event.target.value:this.query);
if(this.query==='*'){
this.results=allArticles;
}else{
this.results=query ? searchIndex(query):[];
}},
searchAll(){
this.query='*';
this.search();
this.$refs.searchInput.focus();
}}
});
new Vue({el: '#knowledgebase-search-root'});