-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
384 lines (357 loc) · 15 KB
/
script.js
File metadata and controls
384 lines (357 loc) · 15 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
document.addEventListener("DOMContentLoaded", () => {
const dict = document.getElementById("dictionary");
const searchInput = document.getElementById("search");
const themeBtns = Array.from(document.querySelectorAll('.theme-toggle'));
const alphabetNav = document.getElementById("alphabet");
const breadcrumbDiv = document.getElementById("breadcrumb");
const backButton = document.getElementById("backButton");
let words = [];
let letterSections = {};
function normalize(text) {
return text.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
function updateDarkMode() {
if (localStorage.theme === "dark") {
document.body.classList.add("dark");
themeBtns.forEach(b => b.textContent = "☀️");
} else {
document.body.classList.remove("dark");
themeBtns.forEach(b => b.textContent = "🌙");
}
}
if (!localStorage.theme) localStorage.theme = "light";
updateDarkMode();
themeBtns.forEach(b => b.addEventListener('click', () => {
localStorage.theme = document.body.classList.contains("dark") ? "light" : "dark";
updateDarkMode();
}));
// Only move the mobile theme toggle under the Manual link when the viewport is very narrow (<=300px).
// For widths above 300px (and up to 768px where the mobile toggle is visible), keep it positioned at the right edge
// and overlap the links instead of expanding page width.
function moveThemeMobile() {
const mobileBtn = document.getElementById('themeToggleMobile');
const topLeft = document.querySelector('.top-left');
const topRight = document.querySelector('.top-right');
if (!mobileBtn || !topLeft || !topRight) return;
if (window.innerWidth <= 300) {
if (!topLeft.contains(mobileBtn)) {
topLeft.appendChild(mobileBtn);
mobileBtn.style.marginTop = '6px';
mobileBtn.style.marginLeft = '0';
mobileBtn.style.position = '';
mobileBtn.style.right = '';
mobileBtn.style.transform = '';
}
} else {
if (!topRight.contains(mobileBtn)) {
topRight.appendChild(mobileBtn);
mobileBtn.style.marginTop = '';
mobileBtn.style.marginLeft = '';
mobileBtn.style.position = '';
mobileBtn.style.right = '';
mobileBtn.style.transform = '';
}
}
}
moveThemeMobile();
let _mvResize;
window.addEventListener('resize', () => {
clearTimeout(_mvResize);
_mvResize = setTimeout(moveThemeMobile, 120);
});
if (backButton) backButton.style.display = "none";
if (breadcrumbDiv) breadcrumbDiv.style.display = "none";
if (backButton) backButton.onclick = () => {
if (searchInput) searchInput.value = "";
if (typeof renderGrouped === 'function') renderGrouped(words);
if (breadcrumbDiv) breadcrumbDiv.style.display = "none";
if (backButton) backButton.style.display = "none";
try {
history.replaceState(null, "", location.pathname + location.search);
} catch (err) {
location.hash = "";
}
// Ensure any open entries are closed
document.querySelectorAll('.entry[open]').forEach(other => other.open = false);
};
const file = new URLSearchParams(location.search).get("file") || "words-pallati-i-endrrave.json";
if (dict) {
fetch(file)
.then(r => r.json())
.then(data => {
if (!Array.isArray(data)) throw new Error("JSON must be an array");
words = data.sort((a,b)=>a.tema.localeCompare(b.tema,"sq",{sensitivity:"base"}));
renderGrouped(words);
buildAlphabet();
openFromHash();
window.addEventListener("scroll", highlightCurrentLetter);
})
.catch(err => {
console.error("Error loading words:", err);
if (dict) dict.textContent = "Fjalët nuk u ngarkuan. Kontrolloni rrugën e JSON-it.";
});
}
function renderGrouped(list) {
dict.innerHTML = "";
letterSections = {};
// derive a safe display title for each entry (fallback to `baza` or `nyje` when `tema` is missing)
const titles = list.map(w => {
const t = (w.tema || w.baza || w.nyje || "").toString();
const n = normalize(t);
return n ? n[0].toUpperCase() : "";
}).filter(Boolean);
const letters = Array.from(new Set(titles)).sort((a,b) => a.localeCompare(b, "sq", {sensitivity: "base"}));
letters.forEach(letter => {
const section = document.createElement("div");
section.id = `letter-${letter}`;
section.className = "letter-section";
const h = document.createElement("h2");
h.textContent = letter;
section.appendChild(h);
list.filter(w => {
const title = (w.tema || w.baza || w.nyje || "").toString();
const first = normalize(title)[0];
return first && first.toUpperCase() === letter;
}).forEach(w => {
const d = document.createElement("details");
d.className = "entry";
const displayTitle = (w.tema || w.baza || w.nyje || "").toString();
d.id = normalize(displayTitle);
d.addEventListener("toggle", () => {
if (d.open) {
// Close other open entries with a fade-out, then close them
document.querySelectorAll('.entry').forEach(other => {
if (other !== d && other.open) {
const content = other.querySelector('.content');
if (content) {
content.classList.add('fade-out');
const onAnim = function() {
content.classList.remove('fade-out');
other.open = false;
content.removeEventListener('animationend', onAnim);
};
content.addEventListener('animationend', onAnim);
} else {
other.open = false;
}
}
});
location.hash = `fjala/${d.id}`;
}
});
let defsHTML = "";
if (Array.isArray(w.përkufizime)) {
w.përkufizime.forEach((def, idx) => {
if (def.kuptim) defsHTML += `<p><strong>${idx+1}.</strong> ${def.kuptim}</p>`;
if (def.shembull) defsHTML += `<p><em>Sh.1:</em> ${def.shembull}</p>`;
if (def.kuptim2) defsHTML += `<p><strong>${idx+2}.</strong> ${def.kuptim2}</p>`;
if (def.shembull2) defsHTML += `<p><em>Sh.2:</em> ${def.shembull2}</p>`;
});
}
let extraHTML = "";
if (w.klasa_morf) extraHTML += `<p><strong>K.M.</strong> ${w.klasa_morf}</p>`;
if (w.fjaleformimi) extraHTML += `<p><strong>F.f.:</strong> ${w.fjaleformimi}</p>`;
d.innerHTML = `<summary class="summary">${w.nyje ? `<span class="word-nyje">${w.nyje}</span> ` : ""}
<span class="word-base">${displayTitle}</span>${w["mbaresa-pashquar"] ? `(<span class="word-pashquar">${w["mbaresa-pashquar"]}</span>)` : ""}${w["mbaresa-pashquar-shumes"] ? `~<span class="word-pashquar-shumes">${w["mbaresa-pashquar-shumes"]}</span>` : ""}${w["mbaresa-shquar"] ? `~<span class="word-shquar">${w["mbaresa-shquar"]}</span>` : ""}${w["mbaresa-shumes"] ? `~<span class="word-shumes">${w["mbaresa-shumes"]}</span>` : ""}</summary><div class="content">${defsHTML}${extraHTML}</div>`;
section.appendChild(d);
});
dict.appendChild(section);
letterSections[letter] = section;
});
}
function buildAlphabet() {
if (!alphabetNav) return;
alphabetNav.innerHTML = "";
Object.keys(letterSections).sort((a,b) => a.localeCompare(b, "sq", {sensitivity: "base"})).forEach(letter => {
const btn = document.createElement("button");
btn.textContent = letter;
btn.onclick = () => {
const target = letterSections[letter];
if (target) target.scrollIntoView({behavior: "smooth"});
};
alphabetNav.appendChild(btn);
});
}
function highlightCurrentLetter() {
const scrollY = window.scrollY;
let current = null;
for (const [letter, section] of Object.entries(letterSections)) {
if (scrollY >= section.offsetTop - 100) current = letter;
}
if (!alphabetNav) return;
alphabetNav.querySelectorAll("button").forEach(btn => {
btn.classList.toggle("active", btn.textContent === current);
});
// Auto-scroll alphabet nav on small screens so the active letter is centered.
// Use horizontal scroll on the nav itself to avoid any vertical/page jump.
const activeBtn = alphabetNav.querySelector("button.active");
if (activeBtn && window.innerWidth <= 768 && alphabetNav.scrollWidth > alphabetNav.clientWidth) {
const navRect = alphabetNav.getBoundingClientRect();
const btnRect = activeBtn.getBoundingClientRect();
const currentScroll = alphabetNav.scrollLeft;
const targetScroll = currentScroll + (btnRect.left - navRect.left) - (alphabetNav.clientWidth / 2) + (btnRect.width / 2);
alphabetNav.scrollTo({ left: Math.max(0, Math.round(targetScroll)), behavior: "smooth" });
}
}
function applySearch() {
const q = normalize(searchInput.value.trim());
if (!q) return renderGrouped(words);
const filtered = words.filter(w => normalize(w.tema).startsWith(q));
renderGrouped(filtered);
}
if (searchInput) searchInput.addEventListener("input", applySearch);
function openFromHash() {
const hash = location.hash.replace("#","");
if (!hash) return;
if (hash.startsWith("fjala/")) {
const id = hash.replace("fjala/","");
const el = document.getElementById(id);
if (el) {
el.open = true;
breadcrumbDiv.style.display = "block";
backButton.style.display = "inline-block";
breadcrumbDiv.innerHTML = `Fjalor / <strong>${el.querySelector("summary")?.textContent}</strong>`;
}
}
}
window.addEventListener("hashchange", openFromHash);
// Back to Top button behavior
const backToTop = document.getElementById("backToTop");
function updateBackToTop() {
if (!backToTop) return;
if (window.scrollY > 20) {
backToTop.classList.add("visible");
} else {
backToTop.classList.remove("visible");
}
}
window.addEventListener("scroll", updateBackToTop, { passive: true });
backToTop?.addEventListener("click", (e) => {
e.preventDefault();
window.scrollTo({ top: 0, behavior: "smooth" });
// Collapse all open entries with fade-out animation
document.querySelectorAll('.entry[open]').forEach(other => {
const content = other.querySelector('.content');
if (content) {
content.classList.add('fade-out');
const handler = function() {
content.classList.remove('fade-out');
other.open = false;
content.removeEventListener('animationend', handler);
};
content.addEventListener('animationend', handler);
} else {
other.open = false;
}
});
if (location.hash && location.hash.startsWith("#fjala/")) {
try {
history.replaceState(null, "", location.pathname + location.search);
} catch (err) {
location.hash = "";
}
if (breadcrumbDiv) breadcrumbDiv.style.display = "none";
if (backButton) backButton.style.display = "none";
}
});
updateBackToTop();
// Manual page loader: look for #manual-content and load manual.json or manual.md
const manualRoot = document.getElementById('manual-content');
function mdToHtml(md) {
if (!md) return '';
// basic block replacements
let html = md
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
// fenced code blocks: ```lang\ncode\n```
html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, function(_, lang, code) {
const esc = code.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const cls = lang ? ` class="language-${lang}"` : '';
return `<pre><code${cls}>${esc}</code></pre>`;
});
// inline code `code`
html = html.replace(/`([^`]+)`/g, function(_, c) {
const esc = c.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return `<code>${esc}</code>`;
});
// headings
html = html.replace(/^###### (.*$)/gim, '<h6>$1</h6>');
html = html.replace(/^##### (.*$)/gim, '<h5>$1</h5>');
html = html.replace(/^#### (.*$)/gim, '<h4>$1</h4>');
html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
// lists
html = html.replace(/(^|\n)- (.*)/gim, '$1<li>$2</li>');
html = html.replace(/(<li>.*<\/li>)/gim, '<ul>$1</ul>');
// bold/italic/underline
html = html.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>');
html = html.replace(/\*(.*?)\*/gim, '<em>$1</em>');
html = html.replace(/__(.*?)__/gim, '<u>$1</u>');
// links [text](url)
html = html.replace(/\[(.*?)\]\((.*?)\)/gim, '<a href="$2">$1</a>');
// paragraphs
html = html.replace(/(^|\n)([^<\n][^\n]*)(\n|$)/gim, function(_, a, b){
if (b.match(/^<h|^<ul|^<li|^<blockquote|^<pre/)) return _;
return '\n<p>' + b.trim() + '</p>\n';
});
// unescape allowed tags inside (including span with attributes)
return html.replace(/<(\/)?(strong|em|u|h[1-6]|a|p|ul|li|span)([^&]*)>/gi, '<$1$2$3>');
}
async function loadManual() {
if (!manualRoot) return;
// simple loader: try manual.json, then manual.md
manualRoot.innerHTML = '<p>Duke ngarkuar manualin...</p>';
try {
let res = await fetch('./manual.json');
if (!res.ok) res = await fetch('manual.json');
if (!res.ok) throw new Error('no json');
const data = await res.json();
const mt = document.getElementById('manual-title');
const ms = document.getElementById('manual-subtitle');
if (mt) mt.textContent = data.title || '';
if (ms) ms.textContent = data.subtitle || '';
manualRoot.innerHTML = '';
const sections = Array.isArray(data.sections) ? data.sections : [];
sections.forEach((s) => {
if (s.title) {
const h = document.createElement('h2');
h.textContent = s.title;
manualRoot.appendChild(h);
}
const fmt = (s.format || '').toLowerCase();
const content = s.content || '';
const wrapper = document.createElement('div');
wrapper.className = 'manual-plain';
if (fmt === 'md') {
wrapper.innerHTML = mdToHtml(content);
} else if (s.contentHtml) {
wrapper.innerHTML = s.contentHtml;
} else {
wrapper.innerHTML = content.replace(/&/g, '&').replace(/</g,'<').replace(/>/g,'>').replace(/\n/g, '<br>');
}
manualRoot.appendChild(wrapper);
});
} catch (err) {
try {
let r2 = await fetch('./manual.md');
if (!r2.ok) r2 = await fetch('manual.md');
if (!r2.ok) throw err;
const md = await r2.text();
manualRoot.innerHTML = mdToHtml(md);
} catch (e) {
manualRoot.innerHTML = `<p style="color:crimson">Manual not found.</p>`;
}
}
}
loadManual();
});
const toggle = document.getElementById("searchToggle");
const search = document.getElementById("search");
if (toggle && search) {
toggle.addEventListener("click", () => {
search.classList.toggle("active");
if (search.classList.contains("active")) {
search.focus();
}
});
}