-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
1670 lines (1498 loc) · 79.5 KB
/
Copy pathscript.js
File metadata and controls
1670 lines (1498 loc) · 79.5 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================================
MAINTENANCE (DedSec Project)
- Theme + language persistence is handled here (localStorage).
- If assets break on sub-pages, check SITE_BASE resolver at the top.
- NAV highlights & mobile menu behaviors are also here.
============================================================================ */
document.addEventListener('DOMContentLoaded', () => {
// --- GLOBAL STATE ---
const academyGreekPath = /\/el\/Smartphone-Academy(?:\/|$)/i.test(window.location.pathname);
const academyHomePath = /(?:\/Smartphone-Academy|\/el\/Smartphone-Academy)\/(?:home|index)\.html$/i.test(window.location.pathname);
const pageLanguage = (/\/el(?:\/|$)/.test(window.location.pathname) || academyGreekPath) ? 'gr' : 'en';
let currentLanguage = pageLanguage;
// --- NAV WORD STACK + MENU OFFSET (keeps navbar compact so logo stays visible) ---
const applyNavbarWordStack = () => {
// Only for the navbar labels (and title). We don't want to affect normal body text.
const targets = document.querySelectorAll(
'.main-nav .nav-title .site-title, .main-nav .nav-action-label, .main-nav .burger-label'
);
const stackTextNodes = (root) => {
try {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: (node) => (node.nodeValue && node.nodeValue.trim().length ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT)
});
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
nodes.forEach(node => {
const raw = (node.nodeValue || '').trim();
if (/\s+/.test(raw)) node.nodeValue = raw.split(/\s+/).join('\n');
});
} catch (_) {
// Fallback: do nothing
}
};
targets.forEach(stackTextNodes);
};
const setViewportUnits = () => {
// iOS Safari (and many in-app browsers) report unstable 100vh.
// We use a JS-driven CSS var for reliable full-height layouts.
const h = (window.visualViewport?.height || window.innerHeight || 0);
if (h) document.documentElement.style.setProperty('--vh', `${h * 0.01}px`);
};
const syncNavMenuOffset = () => {
const nav = document.querySelector('.main-nav');
if (!nav) return;
const h = Math.ceil(nav.getBoundingClientRect().height || 70);
document.documentElement.style.setProperty('--nav-h', `${h}px`);
};
const syncLayoutVars = () => {
setViewportUnits();
// IMPORTANT: do NOT call syncLayoutVars() inside itself (infinite recursion).
// We only need to recompute CSS vars that depend on viewport + navbar height.
syncNavMenuOffset();
};
// --- BRAND ASSETS (Theme-aware) ---
// IMPORTANT (GitHub Pages + subpages):
// Any relative URL like "Assets/..." breaks on pages like /Pages/faq.html
// because it resolves to /Pages/Assets/... (404). We resolve assets from the
// actual location of script.js so it works everywhere (root domain, /repo/, etc.).
const SITE_BASE = (() => {
const scriptEl = document.querySelector('script[src$="script.js"], script[src*="/script.js"], script[src*="script.js?"]');
try {
if (scriptEl?.src) return new URL('./', scriptEl.src).href;
} catch (_) {}
// Fallback: best-effort
return new URL('./', window.location.href).href;
})();
const assetUrl = (path) => {
const clean = (path || '').replace(/^\/+/, '');
return new URL(clean, SITE_BASE).href;
};
// Path of the repository/site root, e.g. "" on ded-sec.space or "/test" on a test copy.
// This keeps language switching inside the same GitHub Pages project instead of
// accidentally sending /Pages/... to /el/Pages/... (404).
const SITE_BASE_PATH = (() => {
try {
const pathname = new URL(SITE_BASE).pathname.replace(/\/+$/, '');
return pathname === '/' ? '' : pathname;
} catch (_) {
return '';
}
})();
const stripSiteBase = (pathname) => {
let relative = pathname || '/';
if (SITE_BASE_PATH && (relative === SITE_BASE_PATH || relative.startsWith(`${SITE_BASE_PATH}/`))) {
relative = relative.slice(SITE_BASE_PATH.length) || '/';
}
return relative.startsWith('/') ? relative : `/${relative}`;
};
const addSiteBase = (relativePath) => {
const clean = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
return `${SITE_BASE_PATH}${clean}` || '/';
};
const getLanguagePath = (pathname, targetLanguage) => {
let relative = stripSiteBase(pathname);
if (targetLanguage === 'gr') {
if (/^\/el(?:\/|$)/i.test(relative)) return addSiteBase(relative);
if (/^\/Smartphone-Academy\/pages\//i.test(relative)) {
relative = relative.replace(/^\/Smartphone-Academy\/pages\//i, '/el/Smartphone-Academy/Pages/');
} else if (/^\/Smartphone-Academy\//i.test(relative)) {
relative = relative.replace(/^\/Smartphone-Academy\//i, '/el/Smartphone-Academy/');
} else if (relative === '/') {
relative = '/el/';
} else {
relative = `/el${relative}`;
}
} else {
if (/^\/el\/Smartphone-Academy\/pages\//i.test(relative)) {
relative = relative.replace(/^\/el\/Smartphone-Academy\/pages\//i, '/Smartphone-Academy/Pages/');
} else if (/^\/el\/Smartphone-Academy\//i.test(relative)) {
relative = relative.replace(/^\/el\/Smartphone-Academy\//i, '/Smartphone-Academy/');
} else if (/^\/el(?:\/|$)/i.test(relative)) {
relative = relative.replace(/^\/el(?=\/|$)/i, '') || '/';
}
}
return addSiteBase(relative);
};
const LOGO_DARK = assetUrl('Assets/Images/Logos/Black%20Purple%20Butterfly%20Logo.jpeg');
const LOGO_LIGHT = assetUrl('Assets/Images/Logos/White%20Purple%20Butterfly%20Logo.jpeg');
const getThemeLogo = () => (document.body.classList.contains('light-theme') ? LOGO_LIGHT : LOGO_DARK);
const applyThemeAssets = () => {
const url = getThemeLogo();
// Navbar logo (injected into title)
document.querySelectorAll('img[data-site-logo="1"]').forEach(img => {
if (img.src !== url) img.src = url;
});
// Favicon fallback (helps when some subpages have broken relative paths)
const icon = document.querySelector('link[rel="icon" i]') || document.querySelector('link[rel="shortcut icon" i]');
if (icon) icon.href = url;
};
const refreshCompactNavButtons = () => {
const themeBtn = document.getElementById('nav-theme-switcher');
const themeLabel = themeBtn?.querySelector('.nav-theme-label');
const isLight = document.body.classList.contains('light-theme');
if (themeLabel) {
themeLabel.textContent = isLight ? (themeLabel.dataset.dark || '☾') : (themeLabel.dataset.light || '☀');
}
if (themeBtn) {
themeBtn.setAttribute('aria-label', currentLanguage === 'gr' ? (isLight ? 'Ενεργοποίηση σκούρου θέματος' : 'Ενεργοποίηση ανοιχτού θέματος') : (isLight ? 'Switch to dark theme' : 'Switch to light theme'));
themeBtn.title = isLight ? 'Dark' : 'Light';
}
const langBtn = document.getElementById('nav-lang-switcher');
const langLabel = langBtn?.querySelector('.nav-lang-label');
if (langLabel) {
langLabel.textContent = currentLanguage === 'en' ? (langLabel.dataset.en || 'ΕΛ') : (langLabel.dataset.gr || 'EN');
}
if (langBtn) {
langBtn.setAttribute('aria-label', currentLanguage === 'en' ? 'Change language to Greek' : 'Αλλαγή γλώσσας στα Αγγλικά');
langBtn.title = currentLanguage === 'en' ? 'ΕΛ' : 'EN';
}
};
function reorderNavigationLinks() {
document.querySelectorAll('.nav-menu').forEach(menu => {
const store = Array.from(menu.querySelectorAll('.nav-link')).find(link => /\/store\.html(?:[?#]|$)/i.test(link.getAttribute('href') || ''));
const assistance = Array.from(menu.querySelectorAll('.nav-link')).find(link => /\/assistance\.html(?:[?#]|$)/i.test(link.getAttribute('href') || ''));
if (store && assistance && store.nextElementSibling !== assistance) menu.insertBefore(store, assistance);
});
}
function normalizeSentencePunctuation(root = document) {
const terminal = /[.!?…:;。!?]$/u;
const closers = /["'”’»)\]}]+$/;
const skipClass = /(?:^|[-_\s])(title|heading|label|tag|badge|eyebrow|price|breadcrumb|nav|button|btn|metric|stat|value|name|source|category|kicker|brand|logo|menu)(?:$|[-_\s])/i;
const isTitleLike = (text) => {
const words = text.match(/[A-Za-zΑ-ΩΆΈΉΊΌΎΏΪΫα-ωάέήίόύώϊϋΐΰ][A-Za-zΑ-ΩΆΈΉΊΌΎΏΪΫα-ωάέήίόύώϊϋΐΰ'’.-]*/gu) || [];
if (!words.length || words.length > 8) return false;
const meaningful = words.filter(word => word.length > 1);
if (!meaningful.length) return false;
const initialCaps = meaningful.filter(word => word[0] === word[0].toUpperCase() && word[0] !== word[0].toLowerCase()).length;
const lowerWords = meaningful.filter(word => word === word.toLowerCase()).length;
return initialCaps / meaningful.length >= 0.75 && lowerWords <= 1;
};
const needsPeriod = (text, element) => {
const clean = (text || '').replace(/\s+/g, ' ').trim();
if (!clean) return false;
const core = clean.replace(closers, '').trim();
if (!core || terminal.test(core)) return false;
const className = typeof element?.className === 'string' ? element.className : '';
if (skipClass.test(className)) return false;
if (element?.closest('nav, h1, h2, h3, h4, h5, h6, button, summary, pre, code, kbd, samp, script, style, textarea, select')) return false;
if (/^(?:https?:\/\/|www\.|mailto:|tel:)\S+$/i.test(clean)) return false;
if (/^[\w.-]+\.(?:com|org|net|io|dev|gr|eu|co|uk|de|fr|app|ai)(?:\/\S*)?$/i.test(clean)) return false;
if (/^\S+\.(?:html?|css|js|json|py|sh|md|txt|pdf|zip|png|jpe?g|webp|svg|xml|yml|yaml)$/i.test(clean)) return false;
if (/^[€$£]?\s*\d+(?:[.,]\d+)?\s*(?:€|\$|£|\/\s*month|\/\s*μήνα)?$/i.test(clean)) return false;
const letters = Array.from(clean).filter(char => /\p{L}/u.test(char));
if (letters.length && letters.every(char => char === char.toUpperCase())) return false;
if (isTitleLike(clean)) return false;
if (clean.split(/\s+/).length <= 2 && !/[,—–-]/.test(clean)) return false;
return true;
};
const withPeriod = (text) => {
const raw = (text || '').trim();
const match = raw.match(/^(.*?)(["'”’»)\]}]+)?$/);
return match ? `${match[1].trim()}.${match[2] || ''}` : `${raw}.`;
};
root.querySelectorAll('p, li, dd, figcaption').forEach(element => {
['data-en', 'data-gr'].forEach(attribute => {
const value = element.getAttribute(attribute);
if (value && needsPeriod(value, element)) element.setAttribute(attribute, withPeriod(value));
});
const text = element.textContent || '';
if (needsPeriod(text, element)) element.appendChild(document.createTextNode('.'));
});
}
// --- NAVIGATION FUNCTIONALITY ---
function initializeNavigation() {
reorderNavigationLinks();
const burgerMenu = document.getElementById('burger-menu');
const navMenu = document.getElementById('nav-menu');
const setBurgerMenuOpen = (open) => {
const isOpen = Boolean(open && burgerMenu && navMenu);
burgerMenu?.classList.toggle('active', isOpen);
navMenu?.classList.toggle('active', isOpen);
document.body.classList.toggle('burger-menu-open', isOpen);
burgerMenu?.setAttribute('aria-expanded', String(isOpen));
navMenu?.setAttribute('aria-hidden', String(!isOpen));
try {
document.dispatchEvent(new CustomEvent('dedsec:burger-menu-state', { detail: { open: isOpen } }));
} catch (_) {}
};
setBurgerMenuOpen(false);
if (burgerMenu && navMenu) {
burgerMenu.addEventListener('click', () => {
setBurgerMenuOpen(!navMenu.classList.contains('active'));
});
}
document.querySelectorAll('.nav-link').forEach(link => {
link.addEventListener('click', () => setBurgerMenuOpen(false));
});
document.addEventListener('click', (e) => {
if (navMenu?.classList.contains('active')) {
const navActions = document.querySelector('.nav-actions');
if (!navMenu.contains(e.target) && !burgerMenu?.contains(e.target) && !navActions?.contains(e.target)) {
setBurgerMenuOpen(false);
}
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && navMenu?.classList.contains('active')) {
setBurgerMenuOpen(false);
burgerMenu?.focus();
}
});
}
// --- THEME SWITCHER ---
function initializeThemeSwitcher() {
const themeBtn = document.getElementById('nav-theme-switcher');
if (!themeBtn) return;
// Restore saved theme
if (localStorage.getItem('theme') === 'light') document.body.classList.add('light-theme');
themeBtn.addEventListener('click', () => {
document.body.classList.toggle('light-theme');
const isLight = document.body.classList.contains('light-theme');
localStorage.setItem('theme', isLight ? 'light' : 'dark');
if (typeof applyThemeAssets === 'function') applyThemeAssets();
refreshCompactNavButtons();
try { window.dispatchEvent(new CustomEvent('dedsec:themechange', { detail: { theme: isLight ? 'light' : 'dark' } })); } catch (_) {}
});
}
// --- LANGUAGE MANAGEMENT ---
window.changeLanguage = (lang) => {
currentLanguage = lang;
document.documentElement.lang = lang === 'gr' ? 'el' : 'en';
localStorage.setItem('language', lang);
document.querySelectorAll('[data-en]').forEach(el => {
const text = el.getAttribute(`data-${lang}`) || el.getAttribute('data-en');
// Update text while preserving icons/children if they exist
if (el.children.length === 0) {
el.textContent = text;
} else {
Array.from(el.childNodes).forEach(node => {
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim().length > 0) {
node.textContent = text;
}
});
}
});
const translatedAttributes = ['aria-label', 'alt', 'title', 'placeholder'];
translatedAttributes.forEach((attribute) => {
const selector = `[data-en-${attribute}], [data-gr-${attribute}]`;
document.querySelectorAll(selector).forEach((el) => {
const translated = el.getAttribute(`data-${lang}-${attribute}`)
|| el.getAttribute(`data-en-${attribute}`);
if (translated !== null) el.setAttribute(attribute, translated);
});
});
document.querySelectorAll('[data-lang-section]').forEach(el => {
const isMatch = el.dataset.langSection === lang;
el.style.display = isMatch ? 'block' : 'none';
el.classList.toggle('hidden-by-default', !isMatch);
});
// Update dynamic links that change by language (downloads, Stripe, etc.)
document.querySelectorAll('[data-en-link], [data-gr-link], .payment-btn').forEach(link => {
const newLink = link.getAttribute(`data-${lang}-link`);
if (newLink) link.href = newLink;
});
// Sync search UI language
if (typeof window.__updateSearchLanguage === 'function') {
window.__updateSearchLanguage();
}
// Sync assistant UI language
if (typeof window.__updateAssistantLanguage === 'function') {
window.__updateAssistantLanguage();
}
try { window.dispatchEvent(new CustomEvent('dedsec:languagechange', { detail: { language: lang } })); } catch (_) {}
refreshCompactNavButtons();
// Keep the navbar compact (so the injected logo doesn't get clipped)
applyNavbarWordStack();
syncLayoutVars();
};
// --- SHARED UTILITIES (COPY, CAROUSEL, ACCORDION) ---
window.copyToClipboard = async (button, targetId) => {
const el = document.getElementById(targetId);
const text = (el?.innerText || el?.textContent || '').trim();
if (!text || !button) return;
const showFeedback = (ok) => {
const original = button.getAttribute(`data-${currentLanguage}`) || button.textContent;
button.textContent = ok
? (currentLanguage === 'gr' ? 'Αντιγράφηκε!' : 'Copied!')
: (currentLanguage === 'gr' ? 'Απέτυχε' : 'Failed');
button.classList.toggle('copy-success', ok);
button.classList.toggle('copy-fail', !ok);
setTimeout(() => {
button.textContent = original;
button.classList.remove('copy-success', 'copy-fail');
}, 1500);
};
// Preferred: modern async clipboard (requires HTTPS + user gesture)
try {
if (navigator.clipboard?.writeText && window.isSecureContext) {
await navigator.clipboard.writeText(text);
showFeedback(true);
return;
}
throw new Error('Clipboard API unavailable');
} catch (_) {
// Fallback for iOS / in-app browsers: execCommand copy
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.top = '-1000px';
ta.style.left = '-1000px';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.focus({ preventScroll: true });
ta.select();
const ok = document.execCommand('copy');
document.body.removeChild(ta);
showFeedback(!!ok);
return;
} catch {
showFeedback(false);
}
}
};
function initializeToolCategories(selector) {
const attachToggle = (header, handler) => {
if (!header || header.dataset.toggleInit === '1') return;
header.dataset.toggleInit = '1';
header.addEventListener('click', handler);
};
// Some sections (like Sponsors-Only on Learn About The Tools) may live
// outside the original container. Bind page-wide and dedupe listeners so
// every category/tool dropdown works reliably.
document.querySelectorAll('.category-header').forEach((header) => {
attachToggle(header, () => {
header.parentElement?.classList.toggle('active');
});
});
document.querySelectorAll('.tool-header').forEach((header) => {
attachToggle(header, (e) => {
e.stopPropagation();
header.parentElement?.classList.toggle('active');
});
});
}
// --- SITE SEARCH (MOBILE-OPTIMIZED STATIC INDEX) ---
function initializeSearch() {
const navActions = document.querySelector('.nav-actions');
if (navActions && !document.getElementById('nav-search')) {
const btn = document.createElement('button');
btn.id = 'nav-search';
btn.className = 'nav-action-btn';
btn.setAttribute('type', 'button');
btn.innerHTML = `
<i class="fas fa-magnifying-glass"></i>
<span data-en="Search" data-gr="Αναζήτηση">Search</span>
`;
navActions.prepend(btn);
}
if (!document.getElementById('search-overlay')) {
const overlay = document.createElement('div');
overlay.id = 'search-overlay';
overlay.className = 'search-overlay';
overlay.innerHTML = `
<div class="search-modal" role="dialog" aria-modal="true" aria-labelledby="search-input">
<div class="search-top">
<input id="search-input" class="search-input" type="search" autocomplete="off" spellcheck="false"
placeholder="Search the site..."
aria-label="Search the site" />
<button id="search-close" class="search-close" type="button" aria-label="Close search">
<i class="fas fa-xmark"></i>
</button>
</div>
<div class="search-results" id="search-results" role="listbox" aria-label="Search results"></div>
</div>
`;
document.body.appendChild(overlay);
}
const overlay = document.getElementById('search-overlay');
const input = document.getElementById('search-input');
const resultsEl = document.getElementById('search-results');
const closeBtn = document.getElementById('search-close');
const openBtn = document.getElementById('nav-search');
if (!overlay || !input || !resultsEl || !closeBtn || !openBtn) return;
const SECRET_PAGE_PATH = 'Pages/unused-template.html';
const SEARCH_INDEX_PATH = 'Assets/search-index.json';
const MAX_RESULTS = 16;
const INPUT_DEBOUNCE_MS = 120;
// Remove legacy crawl-based indexes once. They can be several megabytes on mobile.
try {
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i) || '';
if (key.startsWith('dedsec_search_index_') || key.startsWith('dedsec_search_pages_')) {
localStorage.removeItem(key);
}
}
} catch (_) {}
const escapeHtml = (value) => String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
const normalizeSearchTerm = (value) => String(value || '')
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/['"`]+/g, '')
.replace(/[^a-z0-9\u0370-\u03ff]+/g, ' ')
.trim();
const SEARCH_SYNONYMS = {
'termix': ['termux'], 'tremux': ['termux'], 'trmux': ['termux'], 'termax': ['termux'], 'termuxx': ['termux'], 'temux': ['termux'],
'pyton': ['python'], 'pyhton': ['python'], 'pytohn': ['python'], 'pthon': ['python'], 'pithon': ['python'],
'pip3': ['pip', 'python package'], 'pyp': ['pip'],
'githab': ['github'], 'gitub': ['github'], 'githubb': ['github'], 'gihub': ['github'], 'git hub': ['github'],
'clon': ['clone'], 'clne': ['clone'], 'cloned': ['clone'],
'permision': ['permission'], 'permisson': ['permission'], 'premission': ['permission'], 'permisions': ['permission'],
'denide': ['denied'], 'denyed': ['denied'], 'acess': ['access'], 'acces': ['access'],
'storag': ['storage'], 'storge': ['storage'], 'downlod': ['download'], 'dowload': ['download'], 'downloades': ['downloads'],
'module not found': ['modulenotfounderror', 'missing module', 'install python library'],
'modulenotfound': ['modulenotfounderror', 'missing module'],
'no module named': ['modulenotfounderror', 'missing module'],
'command not found': ['package command not found', 'install package'],
'permission denied': ['chmod executable storage permission'],
'no such file': ['path folder file not found'],
'no space': ['storage cache disk cleanup'],
'localhost': ['local server flask python http server'],
'local host': ['localhost local server'],
'port in use': ['port already in use kill process'],
'address already in use': ['port already in use kill process'],
'ssl': ['certificate curl requests api'],
'certificate': ['ssl certificate curl requests api'],
'apt': ['pkg repository dpkg package'],
'dpkg': ['apt package lock repository'],
'widget': ['termux widget shortcuts launcher'],
'api': ['termux api notifications battery clipboard'],
'crlf': ['line endings windows bad interpreter'],
'bad interpreter': ['shebang env python line endings'],
'github pages': ['site seo sitemap deploy workflow'],
'seo': ['search console sitemap meta title description indexing'],
'backup': ['zip restore downloads project backup'],
'dedsec install': ['install dedsec project android termux'],
'dedsec broken': ['fix dedsec broken install repair']
};
const expandSearchQuery = (normalizedQuery) => {
const variants = new Set([normalizedQuery]);
Object.entries(SEARCH_SYNONYMS).forEach(([wrong, replacements]) => {
const needle = normalizeSearchTerm(wrong);
if (!needle || !normalizedQuery.includes(needle)) return;
replacements.forEach((replacement) => {
const normalizedReplacement = normalizeSearchTerm(replacement);
if (!normalizedReplacement) return;
variants.add(normalizedQuery.replace(needle, normalizedReplacement));
variants.add(`${normalizedQuery} ${normalizedReplacement}`);
});
});
return Array.from(variants).filter(Boolean);
};
const shouldOpenSecretLevel = (value) => {
const normalized = normalizeSearchTerm(value);
return normalized === 'watch dogs'
|| normalized === 'ubisoft'
|| normalized === 'dead space 2'
|| normalized === 'arcade master'
|| normalized.startsWith('arcade master ');
};
const slugify = (str) => (str || '')
.toLowerCase()
.trim()
.replace(/['"`]/g, '')
.replace(/[^a-z0-9\u0370-\u03ff]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 64) || 'section';
const ensureDeterministicIds = (doc) => {
const scope = doc.querySelector('main') || doc.body;
if (!scope) return;
const candidates = scope.querySelectorAll('h1, h2, h3, h4, .feature-title, .tool-title, .category-header');
const used = new Set();
candidates.forEach((el) => {
const raw = (el.getAttribute('data-en') || el.textContent || '').trim();
if (!raw) return;
if (el.id) {
used.add(el.id);
return;
}
const base = slugify(raw);
let unique = base;
let n = 2;
while (used.has(unique) || doc.getElementById(unique)) unique = `${base}-${n++}`;
el.id = unique;
used.add(unique);
});
};
const currentPagePath = () => {
let relative = window.location.pathname;
if (SITE_BASE_PATH && relative.startsWith(`${SITE_BASE_PATH}/`)) relative = relative.slice(SITE_BASE_PATH.length);
relative = relative.replace(/^\/+/, '');
return relative || 'index.html';
};
const currentPageSectionItems = () => {
ensureDeterministicIds(document);
const scope = document.querySelector('main') || document.body;
if (!scope) return [];
const pagePath = currentPagePath();
const pageTitle = (document.querySelector('title')?.textContent || '').trim();
const meta = (document.querySelector('meta[name="description"]')?.getAttribute('content') || pageTitle).trim();
const candidates = scope.querySelectorAll('h1, h2, h3, h4, .feature-title, .tool-title, .category-header, .assistance-card-title');
const items = [];
candidates.forEach((el) => {
const en = (el.getAttribute('data-en') || el.textContent || '').trim();
const gr = (el.getAttribute('data-gr') || en).trim();
if (!en || en.length < 3 || !el.id) return;
items.push({
title_en: en,
title_gr: gr,
meta_en: meta,
meta_gr: meta,
url_en: `${pagePath}#${el.id}`,
url_gr: `${pagePath}#${el.id}`,
keywords_en: en,
keywords_gr: gr,
isPageResult: false
});
});
return items;
};
const resolveUrl = (url) => {
if (!url) return '';
if (url.startsWith('http') || url.startsWith('mailto:') || url.startsWith('tel:')) return url;
if (url.startsWith('#')) return url;
try {
return new URL(url.replace(/^\/+/, ''), SITE_BASE).href;
} catch (_) {
return url;
}
};
const navigate = (url) => {
let target;
try {
if (url && url.startsWith('#')) {
const base = window.location.href.split('#')[0];
target = new URL(base + url);
} else {
target = new URL((url || '').replace(/^\/+/, ''), SITE_BASE);
}
} catch (_) {
window.location.href = url;
return;
}
const current = new URL(window.location.href);
if (target.pathname === current.pathname && target.hash) {
const id = decodeURIComponent(target.hash.replace('#', ''));
const el = document.getElementById(id);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
window.location.hash = target.hash;
} else {
window.location.href = target.href;
}
};
const prepareItem = (raw) => {
const isGr = currentLanguage === 'gr';
const title = String(isGr ? (raw.title_gr || raw.title_en || raw.title || '') : (raw.title_en || raw.title_gr || raw.title || ''));
const meta = String(isGr ? (raw.meta_gr || raw.meta_en || raw.meta || '') : (raw.meta_en || raw.meta_gr || raw.meta || ''));
const url = String(isGr ? (raw.url_gr || raw.url_en || raw.url || '') : (raw.url_en || raw.url_gr || raw.url || ''));
const keywords = String(isGr ? (raw.keywords_gr || raw.keywords_en || raw.keywords || '') : (raw.keywords_en || raw.keywords_gr || raw.keywords || ''));
const titleNorm = normalizeSearchTerm(title);
const metaNorm = normalizeSearchTerm(meta);
const urlNorm = normalizeSearchTerm(url.replace(/[\/_ .-]+/g, ' '));
const keywordNorm = normalizeSearchTerm(keywords);
return {
title,
meta,
url,
isPageResult: raw.isPageResult !== false,
titleNorm,
metaNorm,
urlNorm,
keywordNorm,
titleWords: titleNorm.split(/\s+/).filter(Boolean)
};
};
let rawSearchIndex = null;
let preparedIndex = null;
let indexPromise = null;
const prepareFullIndex = () => {
const raw = Array.isArray(rawSearchIndex) ? rawSearchIndex : [];
const combined = raw.concat(currentPageSectionItems());
const seen = new Set();
preparedIndex = [];
for (const item of combined) {
const prepared = prepareItem(item);
if (!prepared.url || !prepared.title) continue;
const key = prepared.url;
if (seen.has(key)) continue;
seen.add(key);
preparedIndex.push(prepared);
}
return preparedIndex;
};
const loadSearchIndex = () => {
if (preparedIndex) return Promise.resolve(preparedIndex);
if (indexPromise) return indexPromise;
indexPromise = fetch(assetUrl(SEARCH_INDEX_PATH), { cache: 'force-cache' })
.then((response) => {
if (!response.ok) throw new Error(`Search index returned ${response.status}`);
return response.json();
})
.then((data) => {
rawSearchIndex = Array.isArray(data) ? data : (Array.isArray(data?.items) ? data.items : []);
return prepareFullIndex();
})
.catch(() => {
rawSearchIndex = [];
return prepareFullIndex();
});
return indexPromise;
};
const editDistanceWithinTwo = (a, b) => {
if (a === b) return 0;
if (!a || !b || Math.abs(a.length - b.length) > 2) return 3;
const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
const curr = new Array(b.length + 1);
for (let i = 1; i <= a.length; i++) {
curr[0] = i;
let rowMin = curr[0];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
if (curr[j] < rowMin) rowMin = curr[j];
}
if (rowMin > 2) return 3;
for (let j = 0; j <= b.length; j++) prev[j] = curr[j];
}
return prev[b.length] <= 2 ? prev[b.length] : 3;
};
const fuzzyTitleScore = (token, titleWords) => {
if (token.length < 4) return 0;
let best = 0;
for (const word of titleWords) {
if (!word || Math.abs(word.length - token.length) > 2 || word[0] !== token[0]) continue;
const distance = editDistanceWithinTwo(token, word);
if (distance === 1) return 8;
if (distance === 2 && token.length >= 6) best = Math.max(best, 5);
}
return best;
};
const scoreItem = (item, variants) => {
let bestScore = 0;
for (let variantIndex = 0; variantIndex < variants.length; variantIndex++) {
const q = variants[variantIndex];
const tokens = q.split(/\s+/).filter(Boolean);
let score = variantIndex === 0 ? 0 : -4;
if (item.titleNorm === q) score += 140;
else if (item.titleNorm.includes(q)) score += 86;
if (item.urlNorm.includes(q)) score += 48;
if (item.metaNorm.includes(q)) score += 34;
if (item.keywordNorm.includes(q)) score += 30;
if (item.isPageResult) score += 14;
for (const token of tokens) {
let tokenScore = 0;
if (item.titleWords.includes(token)) tokenScore += 54;
else if (item.titleWords.some((word) => word.startsWith(token))) tokenScore += 38;
else tokenScore += fuzzyTitleScore(token, item.titleWords) * 3;
if (item.keywordNorm.includes(token)) tokenScore += 12;
else if (item.metaNorm.includes(token)) tokenScore += 8;
else if (item.urlNorm.includes(token)) tokenScore += 6;
else if (token.length >= 3) tokenScore -= 4;
score += tokenScore;
}
const isAssistance = /(?:^|\/)Assistance\//.test(item.url);
const isHelpQuery = /(?:termux|python|pip|github|git|storage|permission|error|fix|install|clone|server|localhost|api|widget|command|module|package|backup|seo|sitemap)/.test(q);
if (isAssistance && isHelpQuery) score += 24;
if (!item.isPageResult) score -= 8;
if (score > bestScore) bestScore = score;
}
return bestScore;
};
const topMatches = (index, variants) => {
const hits = [];
for (const item of index) {
const score = scoreItem(item, variants);
if (score <= 0) continue;
let insertAt = hits.length;
while (insertAt > 0 && hits[insertAt - 1].score < score) insertAt--;
hits.splice(insertAt, 0, { item, score });
if (hits.length > MAX_RESULTS) hits.pop();
}
return hits.map((hit) => hit.item);
};
let renderSequence = 0;
const renderResults = async (query) => {
const sequence = ++renderSequence;
const q = normalizeSearchTerm(query || '');
if (!q) {
resultsEl.removeAttribute('aria-busy');
resultsEl.innerHTML = `
<a class="search-item" href="${resolveUrl('index.html')}" role="option">
<div class="search-item-title"><i class="fas fa-house"></i><span>${currentLanguage === 'gr' ? 'Αρχική' : 'Home'}</span></div>
<div class="search-item-meta">${currentLanguage === 'gr' ? 'Πληκτρολόγησε για αναζήτηση σε όλο τον ιστότοπο.' : 'Type to search the whole site.'}</div>
</a>
`;
return;
}
resultsEl.setAttribute('aria-busy', 'true');
const index = await loadSearchIndex();
if (sequence !== renderSequence) return;
resultsEl.removeAttribute('aria-busy');
const hits = topMatches(index, expandSearchQuery(q));
if (!hits.length) {
resultsEl.innerHTML = `
<div class="search-item" role="option" tabindex="0">
<div class="search-item-title"><i class="fas fa-circle-info"></i><span>${currentLanguage === 'gr' ? 'Δεν βρέθηκαν αποτελέσματα' : 'No results found'}</span></div>
<div class="search-item-meta">${currentLanguage === 'gr' ? 'Δοκίμασε άλλη λέξη ή λιγότερους όρους.' : 'Try a different word or fewer terms.'}</div>
</div>
`;
return;
}
resultsEl.innerHTML = hits.map((item) => `
<a class="search-item" href="${escapeHtml(resolveUrl(item.url))}" role="option">
<div class="search-item-title"><i class="fas fa-arrow-right"></i><span>${escapeHtml(item.title)}</span></div>
<div class="search-item-meta">${escapeHtml(item.meta)}</div>
</a>
`).join('');
};
let inputTimer = null;
const scheduleRender = (value) => {
clearTimeout(inputTimer);
inputTimer = setTimeout(() => renderResults(value), INPUT_DEBOUNCE_MS);
};
const setOverlayVisible = (visible) => {
overlay.classList.toggle('visible', visible);
document.body.style.overflow = visible ? 'hidden' : '';
if (visible) {
input.focus({ preventScroll: true });
input.select();
renderResults(input.value.trim());
// Warm one small cached JSON file after the modal is visible; never crawl pages.
loadSearchIndex().catch(() => {});
} else {
clearTimeout(inputTimer);
}
};
openBtn.addEventListener('click', () => setOverlayVisible(true));
closeBtn.addEventListener('click', () => setOverlayVisible(false));
overlay.addEventListener('click', (e) => { if (e.target === overlay) setOverlayVisible(false); });
resultsEl.addEventListener('click', (e) => {
const link = e.target.closest('a.search-item[href]');
if (!link || !resultsEl.contains(link)) return;
e.preventDefault();
const href = link.getAttribute('href');
if (!href) return;
setOverlayVisible(false);
navigate(href);
});
input.addEventListener('input', () => scheduleRender(input.value.trim()), { passive: true });
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
setOverlayVisible(false);
return;
}
if (e.key === 'Enter') {
e.preventDefault();
const query = input.value.trim();
if (shouldOpenSecretLevel(query)) {
setOverlayVisible(false);
navigate(resolveUrl(SECRET_PAGE_PATH));
return;
}
const firstLink = resultsEl.querySelector('a.search-item[href]');
if (firstLink) {
setOverlayVisible(false);
navigate(firstLink.getAttribute('href'));
}
}
});
document.addEventListener('keydown', (e) => {
const isMac = navigator.platform.toUpperCase().includes('MAC');
const combo = (isMac ? e.metaKey : e.ctrlKey) && e.key.toLowerCase() === 'k';
const slash = e.key === '/' && !e.ctrlKey && !e.metaKey && !e.altKey;
if (combo) {
e.preventDefault();
setOverlayVisible(true);
return;
}
if (slash) {
const tag = (document.activeElement && document.activeElement.tagName || '').toLowerCase();
if (tag !== 'input' && tag !== 'textarea') {
e.preventDefault();
setOverlayVisible(true);
}
}
if (e.key === 'Escape' && overlay.classList.contains('visible')) {
e.preventDefault();
setOverlayVisible(false);
}
});
window.__updateSearchLanguage = () => {
const isGr = currentLanguage === 'gr';
input.placeholder = isGr ? 'Αναζήτηση στον ιστότοπο...' : 'Search the site...';
input.setAttribute('aria-label', isGr ? 'Αναζήτηση στον ιστότοπο' : 'Search the site');
closeBtn.setAttribute('aria-label', isGr ? 'Κλείσιμο αναζήτησης' : 'Close search');
preparedIndex = null;
if (rawSearchIndex) prepareFullIndex();
if (overlay.classList.contains('visible')) renderResults(input.value.trim());
};
window.__updateSearchLanguage();
try {
const h = decodeURIComponent((window.location.hash || '').replace(/^#/, ''));
if (h.startsWith('search=')) {
const term = h.slice(7);
setOverlayVisible(true);
input.value = term;
renderResults(term);
}
} catch (_) {}
}
// --- ASSISTANT REMOVED ---
// The old JSON chat assistant was replaced by assistance.html and standalone SEO pages.
function initializeBorderSnake() {
let snake = document.getElementById('border-snake');
if (!snake) {
snake = document.createElement('div');
snake.id = 'border-snake';
document.body.appendChild(snake);
}
snake.style.display = 'block';
const inset = 8;
const speed = 320; // px per second
let rafId = null;
let lastTs = null;
let distance = 0;
const animate = (ts) => {
if (!document.body.contains(snake)) return;
if (lastTs == null) lastTs = ts;
const dt = Math.max(0, (ts - lastTs) / 1000);
lastTs = ts;
const w = Math.max(40, window.innerWidth - inset * 2);
const h = Math.max(40, window.innerHeight - inset * 2);
const perimeter = (w * 2) + (h * 2);
distance = (distance + speed * dt) % perimeter;
let x = inset;
let y = inset;
let rotate = 0;
if (distance <= w) {
x = inset + distance;
y = inset;
rotate = 0;
} else if (distance <= w + h) {
x = inset + w;
y = inset + (distance - w);
rotate = 90;
} else if (distance <= (w * 2) + h) {
x = inset + (w - (distance - (w + h)));
y = inset + h;
rotate = 180;
} else {
x = inset;
y = inset + (h - (distance - ((w * 2) + h)));
rotate = 270;
}
snake.style.left = `${x}px`;
snake.style.top = `${y}px`;
snake.style.transform = `translate(-50%, -50%) rotate(${rotate}deg)`;
rafId = requestAnimationFrame(animate);
};
const reset = () => {
lastTs = null;
};