-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
338 lines (284 loc) · 10.4 KB
/
script.js
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
// Edits your digraphs
function normalizeDigraphs(text) {
const digraphs = {
sh: "š",
ch: "č",
zh: "ž",
};
Object.entries(digraphs).forEach(([digraph, replacement]) => {
text = text.replace(new RegExp(digraph, "g"), replacement);
});
return text;
}
let wordsData;
// Color scheme handling
function changeColorScheme() {
const selectedScheme = document.getElementById("color-scheme").value;
document.body.className = selectedScheme + "-scheme";
localStorage.setItem("colorScheme", selectedScheme);
}
function loadColorScheme() {
const savedScheme = localStorage.getItem("colorScheme");
if (savedScheme) {
document.body.className = savedScheme + "-scheme";
document.getElementById("color-scheme").value = savedScheme;
}
}
// Category handling
function populateCategoryDropdown() {
const categorySet = new Set();
const categoryCheckboxes = document.getElementById("category-checkboxes");
fetch("words.json")
.then((response) => response.json())
.then((data) => {
wordsData = data;
data.forEach((item) => {
const categories = Object.values(item)[0].category;
categories.forEach((category) => categorySet.add(category));
});
Array.from(categorySet)
.sort()
.forEach((category) => {
const checkboxWrapper = document.createElement("div");
checkboxWrapper.className = "checkbox-wrapper";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = `category-${category}`;
checkbox.value = category;
checkbox.checked = true;
checkbox.addEventListener("change", applyFilters);
const label = document.createElement("label");
label.htmlFor = `category-${category}`;
label.textContent = category;
checkboxWrapper.appendChild(checkbox);
checkboxWrapper.appendChild(label);
categoryCheckboxes.appendChild(checkboxWrapper);
});
populateWordList(data);
});
}
function checkAllCategories() {
const checkboxes = document.querySelectorAll('#category-checkboxes input[type="checkbox"]');
checkboxes.forEach((checkbox) => {
checkbox.checked = true;
});
applyFilters();
}
function uncheckAllCategories() {
const checkboxes = document.querySelectorAll('#category-checkboxes input[type="checkbox"]');
checkboxes.forEach((checkbox) => {
checkbox.checked = false;
});
applyFilters();
}
// Search and filter functionality
function applyFilters() {
const selectedCategories = Array.from(
document.querySelectorAll("#category-checkboxes input:checked")
).map((cb) => cb.value);
const fuzzySearch = document.getElementById("fuzzy-search-toggle").checked;
const searchDescription = document.getElementById("search-description").checked;
const fuzzyStrength = parseInt(document.getElementById("fuzzy-strength").value);
const searchTerm = document.getElementById("search").value.toLowerCase();
// Create array of buttons with their scores
const buttonArray = Array.from(document.getElementsByClassName("word-button"));
buttonArray.forEach(button => {
const word = button.textContent;
const wordData = wordsData.find((item) => Object.keys(item)[0] === word);
const categories = wordData[word].category;
button.relevanceScore = calculateRelevanceScore(word, searchDescription ? wordData[word].definition : "", searchTerm);
const categoryMatch = selectedCategories.length === 0 ||
categories.some((cat) => selectedCategories.includes(cat));
const searchMatch = fuzzySearch
? button.relevanceScore > 10 / fuzzyStrength
: word.toLowerCase().startsWith(searchTerm);
button.style.display = categoryMatch && (searchMatch || searchTerm === "") ? "block" : "none";
});
// Sort visible buttons by relevance score
if (searchTerm) {
buttonArray
.sort((a, b) => b.relevanceScore - a.relevanceScore)
.forEach(button => button.parentNode.appendChild(button));
}
}
// Word display and population
function populateWordList(data) {
const wordsContainer = document.getElementById("wordList");
wordsContainer.innerHTML = "";
const sortedWords = data
.map((item) => ({
word: Object.keys(item)[0],
data: Object.values(item)[0],
}))
.sort((a, b) => a.word.localeCompare(b.word));
sortedWords.forEach((item) => {
const button = document.createElement("button");
button.className = "word-button";
button.textContent = item.word;
button.addEventListener("click", () => displayWordDetails(item));
wordsContainer.appendChild(button);
});
}
// Initialize everything when DOM is loaded
document.addEventListener("DOMContentLoaded", function () {
loadColorScheme();
populateCategoryDropdown();
checkUrlAndSearch();
// Event listeners
document.getElementById("search").addEventListener("input", applyFilters);
document.getElementById("category-filter-button").addEventListener("click", () => {
document.getElementById("category-popup").style.display = "block";
});
document.getElementById("apply-filters").addEventListener("click", () => {
document.getElementById("category-popup").style.display = "none";
applyFilters();
});
document.getElementById("fuzzy-search-toggle").addEventListener("change", applyFilters);
document.getElementById("fuzzy-strength").addEventListener("input", applyFilters);
document.getElementById("search-description").addEventListener("change", applyFilters);
document.getElementById("check-all").addEventListener("click", checkAllCategories);
document.getElementById("uncheck-all").addEventListener("click", uncheckAllCategories);
});
// Utility functions
function calculateRelevanceScore(word, definition, searchTerm) {
let score = 0;
const wordLower = word.toLowerCase();
const definitionLower = definition.toLowerCase();
const normalizedWord = normalizeDigraphs(wordLower);
const normalizedSearchTerm = normalizeDigraphs(searchTerm);
const fuzzyStrength = parseInt(document.getElementById("fuzzy-strength").value);
if (normalizedWord == normalizedSearchTerm) {
score += 15 * fuzzyStrength;
}
if (normalizedWord.startsWith(normalizedSearchTerm)) {
score += 10 * fuzzyStrength;
}
if (normalizedWord.includes(normalizedSearchTerm)) {
score += 5 * fuzzyStrength;
}
if (normalizeDigraphs(definitionLower).includes(normalizedSearchTerm)) {
score += 3 * fuzzyStrength;
}
const distance = levenshteinDistance(normalizedWord, normalizedSearchTerm);
score += Math.max(0, fuzzyStrength * (5 - distance));
return score;
}
function levenshteinDistance(a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j] + 1
);
}
}
}
return matrix[b.length][a.length];
}
// Word details and URL handling
function displayWordDetails(item) {
const definitionsElement = document.getElementById("wordDetails");
const titleElement = document.getElementById("wordName");
definitionsElement.innerHTML = `
<h4>Category: ${item.data.category.join(", ")}</h4>
<p>${item.data.definition}</p>
${item.data.image ? `<h4>Images:</h4>` : ""}
${item.data.image ? `<img src="${item.data.image}" height=200 width=auto>` : ""}
${item.data.image2 ? `<img src="${item.data.image2}" height=200 width=auto>` : ""}
`;
titleElement.innerHTML = item.word;
}
function checkUrlAndSearch() {
const currentUrl = new URL(window.location.href);
const searchParams = currentUrl.searchParams;
if (searchParams.has("word")) {
const searchWord = searchParams.get("word");
if (searchWord) {
loadWordDetails(searchWord);
}
}
}
function loadWordDetails(word) {
fetch("words.json")
.then((response) => response.json())
.then((data) => {
const wordObject = data.find(
(item) => Object.keys(item)[0].toLowerCase() === word.toLowerCase()
);
if (wordObject) {
const wordKey = Object.keys(wordObject)[0];
displayWordDetails({
word: wordKey,
data: wordObject[wordKey]
});
} else {
console.log("the word does not exist.");
}
})
.catch((error) => console.error("Error:", error));
}
// Stats and alerts
function showStats() {
if (wordsData) {
customAlert(
`there are ${countWords(wordsData)} words<br>there are ${countTotalImages(wordsData)} images`
);
}
}
function countWords(data) {
return data.length;
}
function countTotalImages(data) {
let imageCount = 0;
data.forEach((item) => {
const word = Object.values(item)[0];
if (word.image) imageCount++;
if (word.image2) imageCount++;
});
return imageCount;
}
function customAlert(message) {
const alertBox = document.getElementById("customAlert");
const alertMessage = document.getElementById("alertMessage");
const closeButton = document.getElementById("closeAlert");
alertMessage.innerHTML = message;
alertBox.style.display = "block";
closeButton.onclick = () => alertBox.style.display = "none";
alertBox.onclick = (event) => {
if (event.target === alertBox) {
alertBox.style.display = "none";
}
};
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
alertBox.style.display = "none";
}
});
}
function copyURL() {
const wordName = document.getElementById("wordName").textContent;
const url = new URL(window.location.href);
url.searchParams.set("word", wordName);
const newUrl = url.toString();
navigator.clipboard
.writeText(newUrl)
.then(() => {
window.location.href = newUrl;
})
.catch((err) => {
console.error(err);
});
}