126 lines
2.3 KiB
Vue
126 lines
2.3 KiB
Vue
<template>
|
|
<div class="recipe-search-box" @focusout="onFocusOut">
|
|
<input
|
|
type="text"
|
|
v-model="searchTerm"
|
|
@keyup.enter="search"
|
|
@keyup.esc="clear"
|
|
@focusin="search"
|
|
:placeholder="placeholder"
|
|
/>
|
|
<ul v-if="recipes?.length" class="dropdown">
|
|
<li
|
|
class="recipe"
|
|
v-for="recipe in recipes"
|
|
:key="recipe.id"
|
|
@mousedown="selectRecipe(recipe)"
|
|
>
|
|
<recipe-card :recipe="recipe" />
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</template>
|
|
|
|
<script setup>
|
|
import { ref, watch, onBeforeUnmount } from 'vue'
|
|
import { searchRecipes } from '@/api/recipes'
|
|
import RecipeCard from './RecipeCard.vue'
|
|
|
|
defineProps({
|
|
placeholder: { type: String, default: 'Add a recipe...' },
|
|
})
|
|
|
|
const emit = defineEmits(['select-recipe'])
|
|
|
|
const searchTerm = ref('')
|
|
const recipes = ref([])
|
|
|
|
let debounceId = null
|
|
|
|
watch(
|
|
searchTerm,
|
|
(newVal) => {
|
|
if (!newVal) {
|
|
recipes.value = []
|
|
if (debounceId) clearTimeout(debounceId)
|
|
return
|
|
}
|
|
if (debounceId) clearTimeout(debounceId)
|
|
debounceId = setTimeout(() => {
|
|
if (newVal === searchTerm.value) {
|
|
search()
|
|
}
|
|
}, 200)
|
|
}
|
|
)
|
|
|
|
async function search() {
|
|
const result = await searchRecipes(searchTerm.value)
|
|
recipes.value = result ?? recipes.value
|
|
}
|
|
|
|
function selectRecipe(recipe) {
|
|
emit('select-recipe', recipe)
|
|
searchTerm.value = ''
|
|
recipes.value = []
|
|
}
|
|
|
|
function clear() {
|
|
searchTerm.value = ''
|
|
recipes.value = []
|
|
}
|
|
|
|
function onFocusOut() {
|
|
recipes.value = []
|
|
}
|
|
|
|
onBeforeUnmount(() => {
|
|
if (debounceId) clearTimeout(debounceId)
|
|
})
|
|
</script>
|
|
|
|
<style scoped>
|
|
.recipe-search-box {
|
|
position: relative;
|
|
}
|
|
|
|
.recipe-search-box input {
|
|
width: calc(100% - 2em);
|
|
padding: 8px;
|
|
border: 1px solid #ccc;
|
|
border-radius: 4px;
|
|
font-size: 16px;
|
|
outline: none;
|
|
}
|
|
|
|
.recipe-search-box .dropdown {
|
|
position: absolute;
|
|
top: 100%;
|
|
width: 100%;
|
|
margin: auto;
|
|
background-color: #fff;
|
|
border: 1px solid #ccc;
|
|
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
z-index: 1000;
|
|
|
|
list-style-type: none;
|
|
margin: 0;
|
|
padding: 0;
|
|
max-height: 40vh;
|
|
overflow-y: scroll;
|
|
}
|
|
|
|
.recipe-search-box .dropdown li {
|
|
padding: 8px;
|
|
cursor: pointer;
|
|
border-bottom: 1px solid #ccc;
|
|
}
|
|
|
|
.recipe-search-box .dropdown li:last-child {
|
|
border-bottom: none;
|
|
}
|
|
|
|
.recipe-search-box .dropdown li:hover {
|
|
background-color: #eee;
|
|
}
|
|
</style>
|