-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
399 lines (338 loc) · 17.6 KB
/
script.js
File metadata and controls
399 lines (338 loc) · 17.6 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// DOM Elements
const searchInput = document.getElementById('search-input');
const searchBtn = document.getElementById('search-btn');
const suggestionsContainer = document.getElementById('suggestions');
const searchResults = document.getElementById('search-results');
const defaultState = document.getElementById('default-state');
const darkModeToggle = document.getElementById('dark-mode-toggle');
const bookmarkToggle = document.getElementById('bookmark-toggle');
const recentWordsContainer = document.getElementById('recent-words');
// State
let recentWords = JSON.parse(localStorage.getItem('recentWords')) || [];
let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
let isDarkMode = localStorage.getItem('darkMode') === 'true';
// Initialize
document.addEventListener('DOMContentLoaded', function() {
// Set dark mode if enabled
if (isDarkMode) {
document.body.classList.add('dark');
darkModeToggle.innerHTML = '<i class="fas fa-sun text-primary"></i>';
}
// Update recent words list
updateRecentWords();
// Load word of the day
loadWordOfTheDay();
// Set up event listeners
setupEventListeners();
});
// Event Listeners
function setupEventListeners() {
// Search functionality
searchInput.addEventListener('input', handleSearchInput);
searchBtn.addEventListener('click', performSearch);
searchInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
performSearch();
}
});
// Dark mode toggle
darkModeToggle.addEventListener('click', toggleDarkMode);
// Bookmark toggle
bookmarkToggle.addEventListener('click', function() {
// This would toggle bookmark view in a more complete implementation
alert('Bookmark feature will be implemented in the full version');
});
// Close suggestions when clicking outside
document.addEventListener('click', function(e) {
if (!suggestionsContainer.contains(e.target) && e.target !== searchInput) {
suggestionsContainer.classList.add('hidden');
}
});
}
// Search Functions
function handleSearchInput() {
const query = searchInput.value.trim();
if (query.length < 2) {
suggestionsContainer.classList.add('hidden');
return;
}
// In a real implementation, this would fetch from an API
// For demo purposes, we'll use a static list
const mockSuggestions = getMockSuggestions(query);
if (mockSuggestions.length > 0) {
displaySuggestions(mockSuggestions);
} else {
suggestionsContainer.classList.add('hidden');
}
}
function getMockSuggestions(query) {
const wordList = [
"dictionary", "language", "vocabulary", "definition",
"etymology", "pronunciation", "synonym", "antonym",
"lexicon", "grammar", "phonetics", "semantics",
"ephemeral", "ubiquitous", "serendipity", "paradigm",
"eloquent", "resilient", "innovate", "catalyst"
];
return wordList.filter(word =>
word.toLowerCase().includes(query.toLowerCase())
).slice(0, 5);
}
function displaySuggestions(suggestions) {
suggestionsContainer.innerHTML = '';
suggestions.forEach(word => {
const suggestionItem = document.createElement('div');
suggestionItem.className = 'suggestion-item p-3 cursor-pointer border-b border-custom last:border-b-0 text-primary';
suggestionItem.textContent = word;
suggestionItem.addEventListener('click', function() {
searchInput.value = word;
suggestionsContainer.classList.add('hidden');
performSearch();
});
suggestionsContainer.appendChild(suggestionItem);
});
suggestionsContainer.classList.remove('hidden');
}
function performSearch() {
const query = searchInput.value.trim();
if (!query) {
return;
}
// Hide suggestions
suggestionsContainer.classList.add('hidden');
// Show loading state
searchResults.innerHTML = `
<div class="glass rounded-2xl p-8 text-center fade-in border border-custom">
<div class="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
<i class="fas fa-spinner fa-spin text-primary text-xl"></i>
</div>
<h3 class="text-xl font-semibold text-primary">Searching for "${query}"</h3>
</div>
`;
// Call the actual API
fetchWordData(query);
}
async function fetchWordData(word) {
try {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
if (!response.ok) {
throw new Error('Word not found');
}
const data = await response.json();
displayWordData(data[0]);
addToRecentWords(word);
} catch (error) {
console.error('Error fetching word data:', error);
displayError(`No definition found for "${word}"`);
}
}
function displayWordData(data) {
defaultState.classList.add('hidden');
let meaningsHTML = '';
data.meanings.forEach(meaning => {
let definitionsHTML = '';
meaning.definitions.forEach((def, index) => {
definitionsHTML += `
<div class="mb-3 ${index > 0 ? 'ml-4' : ''}">
<p class="text-primary">${def.definition}</p>
${def.example ? `<p class="mt-1 text-secondary italic">"${def.example}"</p>` : ''}
</div>
`;
});
meaningsHTML += `
<div class="mb-6">
<div class="flex items-center mb-3">
<span class="px-3 py-1 bg-gray-100 dark:bg-gray-800 text-primary rounded-full text-sm font-medium">${meaning.partOfSpeech}</span>
</div>
<div class="ml-2">
${definitionsHTML}
</div>
${meaning.synonyms && meaning.synonyms.length > 0 ? `
<div class="flex flex-wrap items-center mt-3">
<span class="font-medium mr-2 text-primary">Synonyms:</span>
${meaning.synonyms.map(syn => `<span class="px-2 py-1 glass rounded-full text-sm mr-2 mb-2 cursor-pointer border border-custom hover:bg-gray-100 dark:hover:bg-gray-800" onclick="searchWord('${syn}')">${syn}</span>`).join('')}
</div>
` : ''}
${meaning.antonyms && meaning.antonyms.length > 0 ? `
<div class="flex flex-wrap items-center mt-2">
<span class="font-medium mr-2 text-primary">Antonyms:</span>
${meaning.antonyms.map(ant => `<span class="px-2 py-1 glass rounded-full text-sm mr-2 mb-2 cursor-pointer border border-custom hover:bg-gray-100 dark:hover:bg-gray-800" onclick="searchWord('${ant}')">${ant}</span>`).join('')}
</div>
` : ''}
</div>
`;
});
// Get phonetic text
const phoneticText = data.phonetic ||
(data.phonetics && data.phonetics.length > 0 ? data.phonetics[0].text : '');
// Get audio URL if available
let audioUrl = null;
if (data.phonetics && data.phonetics.length > 0) {
for (let phonetic of data.phonetics) {
if (phonetic.audio) {
audioUrl = phonetic.audio;
break;
}
}
}
searchResults.innerHTML = `
<div class="card glass rounded-2xl p-6 fade-in border border-custom">
<div class="flex justify-between items-start mb-6">
<div>
<h2 class="text-3xl font-bold text-primary">${data.word}</h2>
${phoneticText ? `<p class="text-secondary mt-1">${phoneticText}</p>` : ''}
</div>
<div class="flex space-x-3">
${audioUrl ? `
<button class="w-10 h-10 rounded-full glass flex items-center justify-center text-primary hover:text-black dark:hover:text-white border border-custom" onclick="playAudio('${audioUrl}')">
<i class="fas fa-volume-up"></i>
</button>
` : ''}
<button class="w-10 h-10 rounded-full glass flex items-center justify-center text-primary hover:text-black dark:hover:text-white border border-custom" onclick="toggleBookmark('${data.word}')">
<i class="far fa-bookmark"></i>
</button>
</div>
</div>
<div class="meanings-container">
${meaningsHTML}
</div>
</div>
`;
}
function playAudio(audioUrl) {
const audio = new Audio(audioUrl);
audio.play().catch(e => console.error('Error playing audio:', e));
}
function toggleBookmark(word) {
if (bookmarks.includes(word)) {
bookmarks = bookmarks.filter(w => w !== word);
} else {
bookmarks.push(word);
}
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
// Update UI to reflect bookmark status
const bookmarkIcon = document.querySelector('.fa-bookmark');
if (bookmarks.includes(word)) {
bookmarkIcon.classList.remove('far');
bookmarkIcon.classList.add('fas');
} else {
bookmarkIcon.classList.remove('fas');
bookmarkIcon.classList.add('far');
}
// Show feedback
const feedback = document.createElement('div');
feedback.className = 'fixed bottom-4 right-4 px-4 py-2 glass rounded-full text-sm fade-in border border-custom text-primary';
feedback.textContent = bookmarks.includes(word) ? 'Word bookmarked!' : 'Bookmark removed!';
document.body.appendChild(feedback);
setTimeout(() => {
feedback.remove();
}, 2000);
}
function displayError(message) {
defaultState.classList.add('hidden');
searchResults.innerHTML = `
<div class="glass rounded-2xl p-8 text-center fade-in border border-custom">
<div class="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
<i class="fas fa-exclamation-triangle text-primary text-xl"></i>
</div>
<h3 class="text-xl font-semibold text-primary">${message}</h3>
<p class="mt-2 text-secondary">Please check your spelling or try another word.</p>
<button class="mt-4 px-4 py-2 glass rounded-full text-primary hover:bg-gray-100 dark:hover:bg-gray-800 border border-custom" onclick="showDefaultState()">
Back to Home
</button>
</div>
`;
}
function showDefaultState() {
defaultState.classList.remove('hidden');
searchResults.innerHTML = '';
}
// Recent Words Functions
function addToRecentWords(word) {
// Remove if already exists
recentWords = recentWords.filter(w => w !== word);
// Add to beginning
recentWords.unshift(word);
// Keep only last 5 words
if (recentWords.length > 5) {
recentWords.pop();
}
// Save to localStorage
localStorage.setItem('recentWords', JSON.stringify(recentWords));
// Update UI
updateRecentWords();
}
function updateRecentWords() {
if (recentWords.length === 0) {
recentWordsContainer.innerHTML = '<p class="text-secondary text-center py-4">No recent searches</p>';
return;
}
let html = '';
recentWords.forEach(word => {
html += `
<div class="flex justify-between items-center py-2 border-b border-custom last:border-b-0">
<span class="font-medium cursor-pointer text-primary hover:text-black dark:hover:text-white" onclick="searchWord('${word}')">${word}</span>
<button class="text-secondary hover:text-primary" onclick="removeRecentWord('${word}')">
<i class="fas fa-times"></i>
</button>
</div>
`;
});
recentWordsContainer.innerHTML = html;
}
function removeRecentWord(word) {
recentWords = recentWords.filter(w => w !== word);
localStorage.setItem('recentWords', JSON.stringify(recentWords));
updateRecentWords();
}
function searchWord(word) {
searchInput.value = word;
performSearch();
}
// Word of the Day
async function loadWordOfTheDay() {
try {
// Use a predefined word or fetch a random one
const wordOfTheDay = "serendipity";
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${wordOfTheDay}`);
if (response.ok) {
const data = await response.json();
const wordData = data[0];
// Update the word of the day section
const wordOfTheDayElement = document.getElementById('word-of-the-day');
const phoneticText = wordData.phonetic ||
(wordData.phonetics && wordData.phonetics.length > 0 ? wordData.phonetics[0].text : '');
wordOfTheDayElement.innerHTML = `
<div class="flex justify-between items-start">
<div>
<h4 class="text-lg font-semibold text-primary">${wordData.word}</h4>
${phoneticText ? `<p class="text-secondary text-sm">${phoneticText}</p>` : ''}
</div>
<button class="text-primary hover:text-black dark:hover:text-white" onclick="searchWord('${wordData.word}')">
<i class="fas fa-search"></i>
</button>
</div>
<div>
<p class="text-primary"><span class="font-medium">${wordData.meanings[0].partOfSpeech}</span> - ${wordData.meanings[0].definitions[0].definition}</p>
${wordData.meanings[0].definitions[0].example ?
`<p class="mt-2 text-secondary italic">"${wordData.meanings[0].definitions[0].example}"</p>` :
''
}
</div>
`;
}
} catch (error) {
console.error('Error loading word of the day:', error);
}
}
// Dark Mode Toggle
function toggleDarkMode() {
isDarkMode = !isDarkMode;
if (isDarkMode) {
document.body.classList.add('dark');
darkModeToggle.innerHTML = '<i class="fas fa-sun text-primary"></i>';
} else {
document.body.classList.remove('dark');
darkModeToggle.innerHTML = '<i class="fas fa-moon text-primary"></i>';
}
localStorage.setItem('darkMode', isDarkMode);
}