add ingredient suggestions during recipe creation

This commit is contained in:
2025-08-10 13:59:40 +01:00
parent 1d2fa1bf02
commit 089d33925b
4 changed files with 424 additions and 4 deletions

View File

@@ -21,6 +21,50 @@ function authenticateToken(req, res, next) {
});
}
// Get ingredient suggestions for autocomplete
router.get('/ingredients/suggestions', async (req, res) => {
try {
const { q } = req.query; // Search query
if (!q || q.length < 2) {
return res.json([]);
}
// Aggregate unique ingredient names from all recipes
const suggestions = await Recipe.aggregate([
{ $unwind: '$ingredients' },
{
$match: {
'ingredients.name': {
$regex: q,
$options: 'i'
}
}
},
{
$group: {
_id: { $toLower: '$ingredients.name' },
name: { $first: '$ingredients.name' },
count: { $sum: 1 }
}
},
{ $sort: { count: -1, name: 1 } },
{ $limit: 10 },
{
$project: {
_id: 0,
name: 1,
count: 1
}
}
]);
res.json(suggestions);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get all recipes
router.get('/', async (req, res) => {
try {

View File

@@ -0,0 +1,200 @@
.ingredient-autocomplete {
position: relative;
width: 100%;
}
.autocomplete-input-container {
position: relative;
width: 100%;
}
.autocomplete-input {
width: 100%;
padding: 0.75rem;
padding-right: 2.5rem;
border: 2px solid #e9ecef;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
background: white;
}
.autocomplete-input:focus {
outline: none;
border-color: #FF6B35;
box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}
.autocomplete-loading {
position: absolute;
right: 0.75rem;
top: 50%;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: center;
}
.loading-spinner-small {
width: 16px;
height: 16px;
border: 2px solid #e9ecef;
border-top: 2px solid #FF6B35;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.autocomplete-suggestions {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid #e9ecef;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 1000;
max-height: 200px;
overflow-y: auto;
margin-top: 4px;
}
.suggestion-item {
padding: 0.75rem;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
transition: background-color 0.2s ease;
border-bottom: 1px solid #f8f9fa;
}
.suggestion-item:last-child {
border-bottom: none;
}
.suggestion-item:hover,
.suggestion-item.selected {
background-color: #f8f9fa;
}
.suggestion-item.selected {
background-color: #e3f2fd;
}
.suggestion-name {
font-weight: 500;
color: #2c3e50;
flex: 1;
}
.suggestion-count {
font-size: 0.8rem;
color: #6c757d;
background: #e9ecef;
padding: 0.25rem 0.5rem;
border-radius: 12px;
white-space: nowrap;
}
/* Custom scrollbar for suggestions */
.autocomplete-suggestions::-webkit-scrollbar {
width: 6px;
}
.autocomplete-suggestions::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 3px;
}
.autocomplete-suggestions::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
.autocomplete-suggestions::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.autocomplete-suggestions {
max-height: 150px;
}
.suggestion-item {
padding: 0.6rem;
}
.suggestion-name {
font-size: 0.9rem;
}
.suggestion-count {
font-size: 0.75rem;
padding: 0.2rem 0.4rem;
}
}
/* Animation for suggestions appearing */
.autocomplete-suggestions {
animation: slideDown 0.2s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Focus states for accessibility */
.suggestion-item:focus {
outline: 2px solid #FF6B35;
outline-offset: -2px;
}
/* High contrast mode support */
@media (prefers-contrast: high) {
.autocomplete-input {
border-color: #000;
}
.autocomplete-input:focus {
border-color: #FF6B35;
box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.3);
}
.suggestion-item.selected {
background-color: #FF6B35;
color: white;
}
.suggestion-item.selected .suggestion-count {
background: rgba(255, 255, 255, 0.2);
color: white;
}
}
/* Reduced motion support */
@media (prefers-reduced-motion: reduce) {
.autocomplete-input,
.suggestion-item,
.loading-spinner-small {
transition: none;
animation: none;
}
.autocomplete-suggestions {
animation: none;
}
}

View File

@@ -0,0 +1,176 @@
import React, { useState, useEffect, useRef } from 'react';
import api from '../services/api';
import './IngredientAutocomplete.css';
interface IngredientSuggestion {
name: string;
count: number;
}
interface IngredientAutocompleteProps {
value: string;
onChange: (value: string) => void;
placeholder?: string;
className?: string;
}
const IngredientAutocomplete: React.FC<IngredientAutocompleteProps> = ({
value,
onChange,
placeholder = "Enter ingredient name",
className = ""
}) => {
const [suggestions, setSuggestions] = useState<IngredientSuggestion[]>([]);
const [showSuggestions, setShowSuggestions] = useState(false);
const [loading, setLoading] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(-1);
const inputRef = useRef<HTMLInputElement>(null);
const suggestionsRef = useRef<HTMLDivElement>(null);
// Debounce function to avoid too many API calls
const debounce = (func: Function, wait: number) => {
let timeout: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(null, args), wait);
};
};
// Fetch suggestions from API
const fetchSuggestions = async (query: string) => {
if (query.length < 2) {
setSuggestions([]);
setShowSuggestions(false);
return;
}
setLoading(true);
try {
const response = await api.get(`/recipes/ingredients/suggestions?q=${encodeURIComponent(query)}`);
const suggestionData = response.data as IngredientSuggestion[];
setSuggestions(suggestionData);
setShowSuggestions(suggestionData.length > 0);
setSelectedIndex(-1);
} catch (error) {
console.error('Error fetching ingredient suggestions:', error);
setSuggestions([]);
setShowSuggestions(false);
} finally {
setLoading(false);
}
};
// Debounced version of fetchSuggestions
const debouncedFetchSuggestions = debounce(fetchSuggestions, 300);
useEffect(() => {
if (value) {
debouncedFetchSuggestions(value);
} else {
setSuggestions([]);
setShowSuggestions(false);
}
}, [value]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
onChange(newValue);
};
const handleSuggestionClick = (suggestion: IngredientSuggestion) => {
onChange(suggestion.name);
setShowSuggestions(false);
setSelectedIndex(-1);
inputRef.current?.focus();
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!showSuggestions || suggestions.length === 0) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setSelectedIndex(prev =>
prev < suggestions.length - 1 ? prev + 1 : prev
);
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex(prev => prev > 0 ? prev - 1 : -1);
break;
case 'Enter':
e.preventDefault();
if (selectedIndex >= 0) {
handleSuggestionClick(suggestions[selectedIndex]);
}
break;
case 'Escape':
setShowSuggestions(false);
setSelectedIndex(-1);
break;
}
};
const handleBlur = (e: React.FocusEvent) => {
// Delay hiding suggestions to allow for clicks
setTimeout(() => {
if (!suggestionsRef.current?.contains(e.relatedTarget as Node)) {
setShowSuggestions(false);
setSelectedIndex(-1);
}
}, 150);
};
const handleFocus = () => {
if (value && suggestions.length > 0) {
setShowSuggestions(true);
}
};
return (
<div className={`ingredient-autocomplete ${className}`}>
<div className="autocomplete-input-container">
<input
ref={inputRef}
type="text"
value={value}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
onFocus={handleFocus}
placeholder={placeholder}
className="autocomplete-input"
autoComplete="off"
/>
{loading && (
<div className="autocomplete-loading">
<div className="loading-spinner-small"></div>
</div>
)}
</div>
{showSuggestions && suggestions.length > 0 && (
<div
ref={suggestionsRef}
className="autocomplete-suggestions"
>
{suggestions.map((suggestion, index) => (
<div
key={suggestion.name}
className={`suggestion-item ${index === selectedIndex ? 'selected' : ''}`}
onClick={() => handleSuggestionClick(suggestion)}
onMouseEnter={() => setSelectedIndex(index)}
>
<span className="suggestion-name">{suggestion.name}</span>
<span className="suggestion-count">
{suggestion.count} recipe{suggestion.count !== 1 ? 's' : ''}
</span>
</div>
))}
</div>
)}
</div>
);
};
export default IngredientAutocomplete;

View File

@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import IngredientAutocomplete from '../components/IngredientAutocomplete';
import './CreateRecipe.css';
interface Ingredient {
@@ -282,11 +283,10 @@ const CreateRecipe: React.FC = () => {
{ingredients.map((ingredient, index) => (
<div key={index} className="ingredient-row">
<div className="form-group">
<input
type="text"
placeholder="Ingredient name"
<IngredientAutocomplete
value={ingredient.name}
onChange={(e) => updateIngredient(index, 'name', e.target.value)}
onChange={(value) => updateIngredient(index, 'name', value)}
placeholder="Ingredient name"
/>
</div>
<div className="form-group">