-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
265 lines (225 loc) · 7.95 KB
/
script.js
File metadata and controls
265 lines (225 loc) · 7.95 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const suggestionsList = document.getElementById('suggestions');
const resultsGrid = document.getElementById('resultsGrid');
const modal = document.getElementById('detailModal');
const modalBody = document.getElementById('modalBody');
const closeModal = document.querySelector('.close-modal');
const sourceInfoBtn = document.getElementById('sourceInfoBtn');
const sourceModal = document.getElementById('sourceModal');
const closeSourceModal = document.getElementById('closeSourceModal');
let debounceTimer;
let currentFocus = -1;
// Debounce function to limit API calls
const debounce = (func, delay) => {
return (...args) => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(this, args), delay);
};
};
// Fetch ingredients from API
const fetchIngredients = async (query) => {
BaseUrl = "https://kronextech.in/global/ingredients/search?q=";
if (!query) return [];
try {
const response = await fetch(`${BaseUrl}${encodeURIComponent(query)}`);
if (!response.ok) throw new Error('Network response was not ok');
return await response.json();
} catch (error) {
console.error('Error fetching ingredients:', error);
return [];
}
};
// Handle input for suggestions
const handleInput = async (e) => {
const query = e.target.value.trim();
currentFocus = -1; // Reset focus on new input
if (query.length < 2) {
suggestionsList.classList.remove('show');
suggestionsList.innerHTML = '';
return;
}
const results = await fetchIngredients(query);
renderSuggestions(results);
};
// Render suggestions dropdown
const renderSuggestions = (results) => {
suggestionsList.innerHTML = '';
if (results.length === 0) {
suggestionsList.classList.remove('show');
return;
}
results.slice(0, 8).forEach(item => {
const div = document.createElement('div');
div.className = 'suggestion-item';
div.textContent = item.name;
div.addEventListener('click', () => {
searchInput.value = item.name;
suggestionsList.classList.remove('show');
performSearch(item.name);
});
suggestionsList.appendChild(div);
});
suggestionsList.classList.add('show');
};
// Perform full search and render grid
const performSearch = async (query) => {
if (!query) return;
suggestionsList.classList.remove('show');
resultsGrid.innerHTML = '<div class="loading">Loading...</div>'; // Simple loading state
const results = await fetchIngredients(query);
renderGrid(results);
};
// Render Grid Results
const renderGrid = (results) => {
resultsGrid.innerHTML = '';
if (results.length === 0) {
resultsGrid.innerHTML = `
<div class="empty-state">
<p>No ingredients found matching "${searchInput.value}".</p>
</div>
`;
return;
}
results.forEach(item => {
const card = document.createElement('div');
card.className = 'ingredient-card';
const ratingClass = getRatingClass(item.rating);
card.innerHTML = `
<div class="card-header">
<span class="rating-badge ${ratingClass}">${item.rating || 'Unknown'}</span>
<h3>${item.name}</h3>
</div>
<p>${item.description || 'No description available.'}</p>
<button class="read-more-btn">Read More</button>
`;
card.querySelector('.read-more-btn').addEventListener('click', () => openModal(item));
resultsGrid.appendChild(card);
});
};
const getRatingClass = (rating) => {
if (!rating) return '';
const r = rating.toLowerCase();
if (r.includes('best')) return 'rating-best';
if (r.includes('good')) return 'rating-good';
if (r.includes('average')) return 'rating-average';
if (r.includes('poor')) return 'rating-poor';
return '';
};
// Modal Logic
const openModal = (item) => {
// Populate modal content
// We try to find the detailed info from the 'details' array if available
const details = item.details && item.details[0] ? item.details[0] : {};
const glance = details.Glance && details.Glance[0] ? details.Glance[0].details : [];
const descDetails = details.desp_details || [];
let glanceHtml = '';
if (glance.length > 0) {
glanceHtml = `
<div class="modal-section">
<h4>At a Glance</h4>
<ul>
${glance.map(g => `<li>${g}</li>`).join('')}
</ul>
</div>
`;
}
let descHtml = '';
if (descDetails.length > 0) {
descHtml = `
<div class="modal-section">
<h4>Description</h4>
${descDetails.map(d => `<p>${d}</p>`).join('')}
</div>
`;
} else if (item.description) {
descHtml = `
<div class="modal-section">
<h4>Description</h4>
<p>${item.description}</p>
</div>
`;
}
const ratingClass = getRatingClass(item.rating);
modalBody.innerHTML = `
<div class="modal-header">
<span class="modal-rating ${ratingClass}">${item.rating || 'Unknown'}</span>
<h2 class="modal-title">${item.name}</h2>
<p style="color: var(--text-muted);">${details.Categories || ''}</p>
</div>
${glanceHtml}
${descHtml}
${details.Benefits ? `<div class="modal-section"><h4>Benefits</h4><p>${details.Benefits}</p></div>` : ''}
`;
modal.classList.add('visible');
document.body.style.overflow = 'hidden'; // Prevent background scrolling
};
const closeModalFunc = () => {
modal.classList.remove('visible');
document.body.style.overflow = '';
};
const openSourceModalFunc = () => {
sourceModal.classList.add('visible');
document.body.style.overflow = 'hidden';
};
const closeSourceModalFunc = () => {
sourceModal.classList.remove('visible');
document.body.style.overflow = '';
};
// Event Listeners
searchInput.addEventListener('input', debounce(handleInput, 400));
searchInput.addEventListener('keydown', (e) => {
const items = suggestionsList.getElementsByClassName('suggestion-item');
if (e.key === 'ArrowDown') {
e.preventDefault(); // Prevent cursor movement
currentFocus++;
addActive(items);
} else if (e.key === 'ArrowUp') {
e.preventDefault(); // Prevent cursor movement
currentFocus--;
addActive(items);
} else if (e.key === 'Enter') {
e.preventDefault();
if (currentFocus > -1) {
if (items) items[currentFocus].click();
} else {
performSearch(searchInput.value);
}
}
});
const addActive = (items) => {
if (!items) return false;
removeActive(items);
if (currentFocus >= items.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = items.length - 1;
items[currentFocus].classList.add('suggestion-active');
// Scroll to view
items[currentFocus].scrollIntoView({ block: 'nearest' });
};
const removeActive = (items) => {
for (let i = 0; i < items.length; i++) {
items[i].classList.remove('suggestion-active');
}
};
searchBtn.addEventListener('click', () => {
performSearch(searchInput.value);
});
closeModal.addEventListener('click', closeModalFunc);
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModalFunc();
}
});
sourceInfoBtn.addEventListener('click', openSourceModalFunc);
closeSourceModal.addEventListener('click', closeSourceModalFunc);
sourceModal.addEventListener('click', (e) => {
if (e.target === sourceModal) {
closeSourceModalFunc();
}
});
// Close suggestions when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.search-container')) {
suggestionsList.classList.remove('show');
}
});