ki-frontend/src/components/AutoComplete.vue

144 lines
3.4 KiB
Vue

<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<template>
<div>
<label for="searchText" class="form-label fw-bold">{{ label }}</label>
<div class="row mb-2">
<div class="col">
<input
autocomplete="off"
type="text"
class="form-control"
id="searchText"
v-model="searchText"
@keyup="search()"
@keyup.enter="addResult()"
/>
</div>
<div class="col">
<button
v-if="searchText != ''"
type="button"
class="btn btn-outline-success"
aria-label="Hinzufügen"
@click="addResult()"
>
<img
src="/img/bootstrap-icons-1.5.0/plus-lg.svg"
alt="Hinzufügen Icon"
/>
Hinzufügen
</button>
</div>
</div>
<div class="" v-if="searchResults">
<ul class="list-group">
<li
class="list-group-item"
v-for="result in searchResults"
:key="result.id"
@click="addResult(result)"
>
{{ result.name }}
</li>
</ul>
</div>
<profile-list
:values="values"
:type="type"
:editable="true"
@remove-value="removeValue($event)"
@update-values="this.$emit('update-values', this.values)"
>
</profile-list>
</div>
</template>
<script>
import ProfileList from "@/components/ProfileList";
export default {
name: "AutoComplete",
components: {
ProfileList,
},
props: {
type: {
type: String,
},
label: {
type: String,
},
values: {
type: Array,
},
},
data() {
return {
iconUrl: this.apiUrl,
searchText: "",
searchResults: [],
showErrorMessage: false,
};
},
methods: {
async search() {
try {
const request = await this.axios.get(
`${this.apiUrl}/${this.type}s?search=${this.searchText}`,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
if (request.status === 200) {
this.searchResults = request.data[`${this.type}s`];
if (
!this.values
.map((item) => item[this.type].name.toLowerCase())
.includes(this.searchText.toLowerCase())
) {
this.searchResults.unshift({ name: this.searchText });
}
}
} catch (error) {
console.error();
this.showErrorMessage = true;
}
},
addResult(result = false) {
if (!result) result = this.searchResults[0];
if (
this.values.map((item) => item[this.type].name).includes(result.name)
) {
return false;
}
let changeValues = Object.assign(this.values);
let newValue = {
profile_id: localStorage.getItem("user_id"),
};
if (this.type != "contacttype") {
newValue.level = 1;
} else {
newValue.content = "";
}
newValue[this.type] = result;
changeValues.unshift(newValue);
this.searchText = "";
this.searchResults = [];
this.$emit("update-values", changeValues);
},
removeValue(valueName) {
const newValues = this.values.filter((value) => {
if (valueName === value[this.type].name) {
return false;
} else {
return true;
}
});
this.$emit("update-values", newValues);
},
},
};
</script>