-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1599 lines (1403 loc) · 60.3 KB
/
Copy pathscript.js
File metadata and controls
1599 lines (1403 loc) · 60.3 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
/**
* PORTFOLIO ARCHITECTURE
* Loads the active language on demand and preloads the rest in the background.
* Auto-detects browser language (navigator.language) with fallback to 'en'.
*/
const SUPPORTED_LANGS = ['en', 'en.cav', 'es', 'es.cav', 'de', 'fr', 'it', 'ja', 'ko', 'pt', 'ru', 'zh', 'cat', 'alien'];
const FALLBACK_LANG = 'en';
const I18N_ASSET_VERSION = '20260531-1';
const TECH_NAMES = {
'html': 'HTML',
'css': 'CSS',
'english': 'English',
'spanish': 'Español',
'csharp': 'C#',
'react-native': 'React Native',
'android-studio': 'Android Studio',
'nodejs': 'Node.js',
'mariadb': 'MariaDB',
'mssql': 'MS SQL',
'postgresql': 'PostgreSQL',
'mysql': 'MySQL',
'mongodb': 'MongoDB',
'sqlite': 'SQLite',
'aws': 'AWS',
'php': 'PHP',
'sql': 'SQL',
'livewire': 'Livewire',
'tailwind': 'Tailwind CSS',
'sass': 'Sass',
'vue': 'Vue.js',
'react': 'React',
'svelte': 'Svelte',
'astro': 'Astro',
'alpine': 'Alpine.js',
'django': 'Django',
'flask': 'Flask',
'express': 'Express.js',
'laravel': 'Laravel',
'firebase': 'Firebase',
'cordova': 'Cordova',
'xcode': 'Xcode',
'docker': 'Docker',
'azure': 'Azure',
'jenkins': 'Jenkins',
'git': 'Git',
'postman': 'Postman',
'linux': 'Linux',
'figma': 'Figma',
'procreate': 'Procreate',
'krita': 'Krita',
'canva': 'Canva',
'photoshop': 'Photoshop',
'illustrator': 'Illustrator',
'coreldraw': 'CorelDRAW',
'blender': 'Blender',
'autograph': 'Autograph',
'premiere-pro': 'Premiere Pro',
'after-effects': 'After Effects',
'unity': 'Unity',
'unreal-engine': 'Unreal Engine',
'pygame': 'Pygame',
'renpy': 'Ren\'Py',
'python': 'Python',
'javascript': 'JavaScript',
'typescript': 'TypeScript',
'swift': 'Swift',
'kotlin': 'Kotlin',
'java': 'Java',
'bash': 'Bash'
};
const TECH_CATEGORIES = [
{ id: 'code', i18n: 'home.skills_section.categories.code', label: 'Programming & Languages', items: ["english", "spanish", "python", "javascript", "html", "css", "typescript", "swift", "kotlin", "java", "php", "csharp", "sql", "bash"] },
{ id: 'frontend', i18n: 'home.skills_section.categories.frontend', label: 'Frontend', items: ["react", "vue", "svelte", "astro", "alpine", "livewire", "tailwind", "sass", "bootstrap"] },
{ id: 'backend', i18n: 'home.skills_section.categories.backend', label: 'Backend', items: ["django", "flask", "nodejs", "express", "laravel", "firebase"] },
{ id: 'mobile', i18n: 'home.skills_section.categories.mobile', label: 'Mobile', items: ["react-native", "cordova", "android-studio", "xcode"] },
{ id: 'databases', i18n: 'home.skills_section.categories.databases', label: 'Databases', items: ["postgresql", "mysql", "mongodb", "sqlite", "mariadb", "mssql"] },
{ id: 'devopsTools', i18n: 'home.skills_section.categories.devopsTools', label: 'DevOps & Tools', items: ["docker", "aws", "azure", "jenkins", "git", "postman", "linux"] },
{ id: 'design', i18n: 'home.skills_section.categories.design', label: 'Design', items: ["figma", "procreate", "krita", "canva", "photoshop", "illustrator", "coreldraw"] },
{ id: 'animationAndVideo', i18n: 'home.skills_section.categories.animationAndVideo', label: 'Animation & Video', items: ["blender", "autograph", "premiere-pro", "after-effects"] },
{ id: 'gaming', i18n: 'home.skills_section.categories.gaming', label: 'Gaming', items: ["unity", "unreal-engine", "pygame", "renpy"] }
];
function formatTechName(key) {
return TECH_NAMES[key] || key.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
}
const EXPERIENCE_START_DATE = { year: 2019, month: 0, day: 1 };
const LANGUAGE_CONTROL_LABELS = {
en: 'Select language',
cat: 'Select cat language',
alien: 'Select alien language',
es: 'Seleccionar idioma',
de: 'Sprache w\u00e4hlen',
fr: 'Choisir la langue',
it: 'Seleziona lingua',
ja: '\u8a00\u8a9e\u3092\u9078\u629e',
ko: '\uc5b8\uc5b4 \uc120\ud0dd',
pt: 'Selecionar idioma',
ru: '\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u044f\u0437\u044b\u043a',
zh: '\u9009\u62e9\u8bed\u8a00'
};
const LANGUAGE_CHANGED_LABELS = {
en: 'Language changed to English',
'en.cav': 'Caveman English active',
cat: 'Cat language active',
alien: 'Alien language active',
es: 'Idioma cambiado a espa\u00f1ol',
'es.cav': 'Espa\u00f1ol cavern\u00edcola activo',
de: 'Sprache auf Deutsch ge\u00e4ndert',
fr: 'Langue chang\u00e9e en fran\u00e7ais',
it: 'Lingua cambiata in italiano',
ja: '\u65e5\u672c\u8a9e\u306b\u5909\u66f4\u3057\u307e\u3057\u305f',
ko: '\ud55c\uad6d\uc5b4\ub85c \ubcc0\uacbd\ub418\uc5c8\uc2b5\ub2c8\ub2e4',
pt: 'Idioma alterado para portugu\u00eas',
ru: '\u042f\u0437\u044b\u043a \u043f\u0435\u0440\u0435\u043a\u043b\u044e\u0447\u0451\u043d \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u0438\u0439',
zh: '\u8bed\u8a00\u5df2\u5207\u6362\u4e3a\u4e2d\u6587'
};
const TOKEN_SAVER_VARIANTS = {
en: {
variant: 'en.cav',
icon: '\ud83e\uddb4',
text: 'Save tokens',
activateLabel: 'Switch to Caveman English',
deactivateLabel: 'Switch back to standard English'
},
es: {
variant: 'es.cav',
icon: '\ud83e\udea8',
text: 'Ahorra tokens',
activateLabel: 'Cambiar a espa\u00f1ol cavern\u00edcola',
deactivateLabel: 'Volver a espa\u00f1ol est\u00e1ndar'
}
};
const CAT_SOUNDS = ['meow', 'miau', 'mrrp', 'nya', 'mew', 'purr'];
const ALIEN_SYMBOLS = [
'⟟', '⌿', '⌇', '⟒', '⍀', '⌰', '⏃', '⍜', '⏁', '⊑', '⍙', '⌖',
'⊕', '⊗', '⊙', '⊚', '⊛', '⊞', '⊟', '⊠', '⊡',
'◉', '◎', '◌', '◍', '◐', '◑', '◒', '◓', '◔', '◕',
'▣', '▤', '▥', '▦', '▧', '▨', '▩',
'╬', '╠', '╣', '╦', '╩', '╔', '╗', '╚', '╝',
'ᚠ', 'ᚢ', 'ᚦ', 'ᚨ', 'ᚱ', 'ᚲ', 'ᚷ', 'ᚹ', 'ᚺ', 'ᛉ', 'ᛊ', 'ᛏ',
'☌', '☍', '☊', '☋', '☿', '⚚', '⚛', '⚝', '⛧', '⛤', '🜁', '🜂', '🜃', '🜄'
];
const SYNTHETIC_LANGUAGE_GENERATORS = {
cat: generateCatLanguageData,
alien: generateAlienLanguageData
};
const UI_GLYPHS = {
themeDark: '\u263e',
themeLight: '\u2600',
menuClosed: '\u2630',
menuOpen: '\u2715',
external: {
type: 'sprite',
id: 'icon-external'
},
arrowRight: '\u2192',
download: '\u2193',
tools: '\ud83d\udee0'
};
let siteData = null;
let currentLang = detectLanguage();
let currentTheme = localStorage.getItem('theme') || 'dark';
let tokenSaverAttentionTimeoutId = null;
const syntheticLanguageCache = {};
const languageDataCache = {};
const languageRequestCache = {};
let hasScheduledLanguagePreload = false;
function getLanguageAssetPath(lang) {
return `assets/i18n/${lang}.json?v=${I18N_ASSET_VERSION}`;
}
function getBaseLanguage(lang = currentLang) {
return lang.split('.')[0];
}
function getDocumentLanguageCode(lang = currentLang) {
const baseLang = getBaseLanguage(lang);
return baseLang === 'cat' || baseLang === 'alien' ? 'en' : baseLang;
}
function getLanguageConfigValue(map, lang = currentLang) {
return map[lang] || map[getBaseLanguage(lang)] || map[FALLBACK_LANG];
}
function detectLanguage() {
const saved = localStorage.getItem('lang');
if (saved && SUPPORTED_LANGS.includes(saved)) return saved;
const nav = (navigator.language || 'en').split('-')[0].toLowerCase();
return SUPPORTED_LANGS.includes(nav) ? nav : FALLBACK_LANG;
}
async function loadLanguage(lang) {
if (SYNTHETIC_LANGUAGE_GENERATORS[lang]) {
return loadSyntheticLanguage(lang);
}
try {
return await fetchConcreteLanguage(lang);
} catch {
const baseLang = getBaseLanguage(lang);
if (lang !== baseLang) {
console.warn(`Failed to load i18n/${lang}.json, falling back to ${baseLang}`);
return loadLanguage(baseLang);
}
if (lang !== FALLBACK_LANG) {
console.warn(`Failed to load i18n/${lang}.json, falling back to ${FALLBACK_LANG}`);
return loadLanguage(FALLBACK_LANG);
}
throw new Error('Failed to load i18n data');
}
}
async function fetchConcreteLanguage(lang) {
if (languageDataCache[lang]) return languageDataCache[lang];
if (languageRequestCache[lang]) return languageRequestCache[lang];
const request = fetch(getLanguageAssetPath(lang))
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(data => {
languageDataCache[lang] = data;
return data;
})
.finally(() => {
delete languageRequestCache[lang];
});
languageRequestCache[lang] = request;
return request;
}
async function loadSyntheticLanguage(lang) {
if (syntheticLanguageCache[lang]) return syntheticLanguageCache[lang];
const baseData = await loadLanguage(FALLBACK_LANG);
const generator = SYNTHETIC_LANGUAGE_GENERATORS[lang];
const generatedData = generator(baseData);
syntheticLanguageCache[lang] = generatedData;
return generatedData;
}
function hashString(value) {
let hash = 2166136261;
for (let index = 0; index < value.length; index += 1) {
hash ^= value.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function createSeededRandom(seedSource) {
let seed = hashString(seedSource);
return () => {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed / 4294967296;
};
}
function transformHtmlText(input, transformer) {
return input
.split(/(<[^>]+>)/g)
.map(fragment => (fragment.startsWith('<') && fragment.endsWith('>') ? fragment : transformer(fragment)))
.join('');
}
function mapVisibleContent(data, stringTransformer) {
return {
home: transformNestedStrings(data.home, stringTransformer),
projects: data.projects.map(project => ({
...project,
title: stringTransformer(project.title),
description: stringTransformer(project.description),
tags: project.tags.map(tag => stringTransformer(tag))
})),
experience: data.experience.map(item => ({
...item,
date: stringTransformer(item.date),
title: stringTransformer(item.title),
desc: stringTransformer(item.desc),
links: (item.links || []).map(link => ({
...link,
label: stringTransformer(link.label)
}))
}))
};
}
function transformNestedStrings(value, stringTransformer) {
if (typeof value === 'string') return stringTransformer(value);
if (Array.isArray(value)) return value.map(item => transformNestedStrings(item, stringTransformer));
if (!value || typeof value !== 'object') return value;
return Object.fromEntries(
Object.entries(value).map(([key, nestedValue]) => [key, transformNestedStrings(nestedValue, stringTransformer)])
);
}
function looksProtectedToken(word) {
return (
!word
|| /^https?:/i.test(word)
|| /^www\./i.test(word)
|| /^[@#]/.test(word)
|| /^[0-9]+([./:-][0-9]+)*$/.test(word)
);
}
function getCatSound(coreWord, trailingPunctuation, rng) {
if (trailingPunctuation.includes('!')) return 'HISSS';
if (trailingPunctuation.includes('?')) return 'mrrp';
if (coreWord.length > 6) return 'meooow';
let sound = CAT_SOUNDS[Math.floor(rng() * CAT_SOUNDS.length)];
if (rng() > 0.6) sound = sound.replace('o', 'oooo').replace('a', 'aaa');
return sound;
}
function transformWordToken(token, transformWord) {
if (!token || /^\s+$/.test(token)) return token;
const leading = token.match(/^[^A-Za-z0-9@#]+/)?.[0] || '';
const trailing = token.match(/[^A-Za-z0-9]+$/)?.[0] || '';
const start = leading.length;
const end = token.length - trailing.length;
const coreWord = token.slice(start, end);
if (!coreWord) return token;
if (looksProtectedToken(coreWord)) return token;
return `${leading}${transformWord(coreWord, trailing)}${trailing}`;
}
function toCatLanguage(input, seedKey) {
return transformHtmlText(input, segment => {
const rng = createSeededRandom(`${seedKey}:${segment}`);
return segment
.split(/(\s+)/)
.map(token => transformWordToken(token, (coreWord, trailing) => getCatSound(coreWord, trailing, rng)))
.join('');
});
}
function randomAlienText(length, rng) {
return Array.from({ length }, () => ALIEN_SYMBOLS[Math.floor(rng() * ALIEN_SYMBOLS.length)]).join('');
}
function toAlienLanguage(input, seedKey) {
return transformHtmlText(input, segment => {
const rng = createSeededRandom(`${seedKey}:${segment}`);
return segment
.split(/(\s+)/)
.map(token => transformWordToken(token, coreWord => randomAlienText(Math.max(2, Math.min(coreWord.length, 12)), rng)))
.join('');
});
}
function generateCatLanguageData(baseData) {
return mapVisibleContent(baseData, value => toCatLanguage(value, 'cat'));
}
function generateAlienLanguageData(baseData) {
return mapVisibleContent(baseData, value => toAlienLanguage(value, 'alien'));
}
function getNestedValue(obj, path) {
return path.split('.').reduce((prev, curr) => prev?.[curr] ?? null, obj);
}
function getLocalizedText(path, fallback = '') {
const value = getNestedValue(siteData, path);
return typeof value === 'string' ? value : fallback;
}
function escapeHtmlAttribute(value) {
return String(value)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function getSamePageHashTarget(link) {
if (!(link instanceof HTMLAnchorElement)) return null;
const url = new URL(link.href, window.location.href);
if (url.origin !== window.location.origin || url.pathname !== window.location.pathname || !url.hash) {
return null;
}
const targetId = decodeURIComponent(url.hash.slice(1));
if (!targetId) return null;
return document.getElementById(targetId);
}
function getInlineIconMarkup(name, className = 'inline-icon') {
const glyph = UI_GLYPHS[name];
if (!glyph) return '';
if (typeof glyph === 'string') {
return `<span class="${className}" aria-hidden="true">${glyph}</span>`;
}
if (glyph.type === 'sprite') {
return `
<span class="${className}" aria-hidden="true">
<svg class="glyph-svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24">
<use href="assets/icons/social-sprite.svg#${glyph.id}"></use>
</svg>
</span>
`;
}
return '';
}
function announceStatus(message) {
const liveRegion = document.getElementById('a11y-status');
if (!liveRegion || !message) return;
liveRegion.textContent = '';
window.setTimeout(() => { liveRegion.textContent = message; }, 30);
}
function getBackgroundPreloadLanguages() {
return SUPPORTED_LANGS.filter(lang => (
!SYNTHETIC_LANGUAGE_GENERATORS[lang]
&& !languageDataCache[lang]
&& !languageRequestCache[lang]
));
}
async function preloadLanguagesInBackground() {
const languagesToPreload = getBackgroundPreloadLanguages();
if (!languagesToPreload.length) return;
const results = await Promise.allSettled(
languagesToPreload.map(lang => fetchConcreteLanguage(lang))
);
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.warn(`Background preload failed for ${getLanguageAssetPath(languagesToPreload[index])}`, result.reason);
}
});
}
function scheduleBackgroundLanguagePreload() {
if (hasScheduledLanguagePreload) return;
hasScheduledLanguagePreload = true;
const startPreload = () => {
void preloadLanguagesInBackground();
};
if ('requestIdleCallback' in window) {
window.requestIdleCallback(startPreload, { timeout: 2500 });
return;
}
window.setTimeout(startPreload, 1200);
}
// Initial Load
document.addEventListener('DOMContentLoaded', () => {
initApp();
hydrateInitialContent();
});
async function hydrateInitialContent() {
try {
siteData = await loadLanguage(currentLang);
if (currentLang === FALLBACK_LANG) {
updatePageText();
renderDynamicContent();
syncAccessibilityUI();
} else {
initLanguage();
renderDynamicContent();
syncAccessibilityUI();
}
scheduleBackgroundLanguagePreload();
} catch (error) {
console.error('Error loading i18n data:', error);
}
}
function initApp() {
initTheme();
initLanguage();
renderDynamicContent();
setupEventListeners();
syncAccessibilityUI();
initTooltipPositioning();
initCursorParticles();
updateExperienceYearsStat();
const yearSpan = document.getElementById('year');
if (yearSpan) yearSpan.textContent = new Date().getFullYear();
}
function getCompletedYearsSince({ year, month, day }) {
const now = new Date();
let years = now.getFullYear() - year;
const hasReachedAnniversary = (
now.getMonth() > month
|| (now.getMonth() === month && now.getDate() >= day)
);
if (!hasReachedAnniversary) years -= 1;
return Math.max(0, years);
}
function updateExperienceYearsStat() {
const experienceYearsStat = document.getElementById('experience-years-stat');
if (!experienceYearsStat) return;
const completedYears = getCompletedYearsSince(EXPERIENCE_START_DATE);
experienceYearsStat.textContent = `+ ${completedYears}`;
}
function initTooltipPositioning() {
function adjustTooltip(el) {
el.classList.remove('tooltip-pos-right', 'tooltip-pos-left');
const rect = el.getBoundingClientRect();
const maxW = Math.min(360, window.innerWidth * 0.82);
const cx = rect.left + rect.width / 2;
if (cx + maxW / 2 > window.innerWidth - 8) {
el.classList.add('tooltip-pos-right');
} else if (cx - maxW / 2 < 8) {
el.classList.add('tooltip-pos-left');
}
}
document.addEventListener('mouseover', e => {
const el = e.target.closest('[data-tooltip]');
if (el) adjustTooltip(el);
});
document.addEventListener('focusin', e => {
const el = e.target.closest('[data-tooltip]');
if (el) adjustTooltip(el);
});
}
function initCursorParticles() {
const supportsFinePointer = window.matchMedia('(hover: hover) and (pointer: fine)');
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
if (!supportsFinePointer.matches || prefersReducedMotion.matches) return;
const particleCanvas = document.createElement('canvas');
particleCanvas.className = 'cursor-particles';
particleCanvas.setAttribute('aria-hidden', 'true');
document.body.appendChild(particleCanvas);
const context = particleCanvas.getContext('2d');
if (!context) {
particleCanvas.remove();
return;
}
const particleLimit = 24;
const maxDevicePixelRatio = 1.25;
const particlePalettes = {
dark: {
warm: [254, 217, 164],
hot: [255, 199, 92],
soft: [255, 255, 255],
glow: [255, 221, 120]
},
light: {
warm: [217, 119, 6],
hot: [180, 83, 9],
soft: [15, 23, 42],
glow: [245, 158, 11]
}
};
let activeTheme = currentTheme;
let particleColors = currentTheme === 'light' ? particlePalettes.light : particlePalettes.dark;
let viewportWidth = window.innerWidth;
let viewportHeight = window.innerHeight;
let devicePixelRatio = Math.min(window.devicePixelRatio || 1, maxDevicePixelRatio);
const particles = [];
let animationFrameId = 0;
let lastFrameTime = 0;
let lastPointerX = 0;
let lastPointerY = 0;
let lastSpawnTime = 0;
let hasPointer = false;
const resizeCanvas = () => {
viewportWidth = window.innerWidth;
viewportHeight = window.innerHeight;
devicePixelRatio = Math.min(window.devicePixelRatio || 1, maxDevicePixelRatio);
particleCanvas.width = Math.round(viewportWidth * devicePixelRatio);
particleCanvas.height = Math.round(viewportHeight * devicePixelRatio);
particleCanvas.style.width = `${viewportWidth}px`;
particleCanvas.style.height = `${viewportHeight}px`;
context.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
};
const requestRender = () => {
if (!animationFrameId && particles.length) {
animationFrameId = window.requestAnimationFrame(renderParticles);
}
};
const syncPalette = () => {
if (activeTheme === currentTheme) return;
activeTheme = currentTheme;
particleColors = currentTheme === 'light' ? particlePalettes.light : particlePalettes.dark;
};
const clearParticles = () => {
particles.length = 0;
hasPointer = false;
lastFrameTime = 0;
context.clearRect(0, 0, viewportWidth, viewportHeight);
if (animationFrameId) {
window.cancelAnimationFrame(animationFrameId);
animationFrameId = 0;
}
};
const rgba = (channels, alpha) => `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${alpha})`;
const spawnParticle = (x, y, dx, dy, energy = 1) => {
if (particles.length >= particleLimit) particles.shift();
const speed = Math.min(2.45, Math.hypot(dx, dy) * 0.05 + 0.4) * energy;
const angle = Math.atan2(-dy, -dx) + (Math.random() - 0.5) * 0.9;
const life = 15 + Math.random() * 10;
const toneRoll = Math.random();
particles.push({
x: x - dx * 0.04,
y: y - dy * 0.04,
prevX: x,
prevY: y,
vx: Math.cos(angle) * speed + (Math.random() - 0.5) * 0.3,
vy: Math.sin(angle) * speed + (Math.random() - 0.5) * 0.3,
life,
ttl: life,
size: 1.35 + Math.random() * 1.9,
tone: toneRoll > 0.82 ? 'soft' : toneRoll > 0.26 ? 'warm' : 'hot'
});
};
function renderParticles(timestamp) {
syncPalette();
if (!lastFrameTime) lastFrameTime = timestamp;
const delta = Math.min(24, timestamp - lastFrameTime);
lastFrameTime = timestamp;
context.clearRect(0, 0, viewportWidth, viewportHeight);
for (let index = particles.length - 1; index >= 0; index -= 1) {
const particle = particles[index];
particle.prevX = particle.x;
particle.prevY = particle.y;
particle.x += particle.vx * delta * 0.06;
particle.y += particle.vy * delta * 0.06;
particle.vx *= 0.985;
particle.vy *= 0.985;
particle.life -= delta * 0.065;
if (particle.life <= 0) {
particles.splice(index, 1);
continue;
}
const progress = particle.life / particle.ttl;
const trailAlpha = (
particle.tone === 'hot' ? 0.44
: particle.tone === 'warm' ? 0.34
: 0.24
) * progress;
const fillAlpha = (
particle.tone === 'hot' ? 0.8
: particle.tone === 'warm' ? 0.66
: 0.48
) * progress;
const glowAlpha = (
particle.tone === 'soft' ? 0.12 : 0.2
) * progress;
const strokeChannels = particle.tone === 'soft'
? particleColors.soft
: particle.tone === 'hot'
? particleColors.hot
: particleColors.warm;
const fillChannels = particle.tone === 'soft'
? particleColors.soft
: particle.tone === 'hot'
? particleColors.hot
: particleColors.warm;
const strokeColor = rgba(strokeChannels, trailAlpha);
const fillColor = rgba(fillChannels, fillAlpha);
const glowColor = rgba(
particle.tone === 'soft' ? fillChannels : particleColors.glow,
glowAlpha
);
context.beginPath();
context.arc(
particle.x,
particle.y,
Math.max(1, particle.size * (0.85 + progress * 0.55)),
0,
Math.PI * 2
);
context.fillStyle = glowColor;
context.fill();
context.beginPath();
context.moveTo(particle.prevX, particle.prevY);
context.lineTo(particle.x, particle.y);
context.strokeStyle = strokeColor;
context.lineWidth = Math.max(1, particle.size * (0.35 + progress * 0.55));
context.lineCap = 'round';
context.stroke();
context.beginPath();
context.arc(
particle.x,
particle.y,
Math.max(0.7, particle.size * (0.38 + progress * 0.72)),
0,
Math.PI * 2
);
context.fillStyle = fillColor;
context.fill();
}
if (!particles.length) {
animationFrameId = 0;
lastFrameTime = 0;
context.clearRect(0, 0, viewportWidth, viewportHeight);
return;
}
animationFrameId = window.requestAnimationFrame(renderParticles);
}
resizeCanvas();
document.addEventListener('pointermove', event => {
if (event.pointerType && event.pointerType !== 'mouse') return;
const pointerX = event.clientX;
const pointerY = event.clientY;
const now = performance.now();
if (!hasPointer) {
hasPointer = true;
lastPointerX = pointerX;
lastPointerY = pointerY;
lastSpawnTime = now;
return;
}
const dx = pointerX - lastPointerX;
const dy = pointerY - lastPointerY;
const distance = Math.hypot(dx, dy);
if (distance < 7 || now - lastSpawnTime < 16) {
lastPointerX = pointerX;
lastPointerY = pointerY;
return;
}
const spawnCount = Math.min(3, 1 + Math.floor(distance / 24));
for (let index = 0; index < spawnCount; index += 1) {
const offset = (index + 1) / (spawnCount + 1);
spawnParticle(
lastPointerX + dx * offset,
lastPointerY + dy * offset,
dx,
dy
);
}
lastPointerX = pointerX;
lastPointerY = pointerY;
lastSpawnTime = now;
requestRender();
}, { passive: true });
document.addEventListener('pointerdown', event => {
if (event.pointerType && event.pointerType !== 'mouse') return;
if (!hasPointer) return;
for (let index = 0; index < 5; index += 1) {
spawnParticle(lastPointerX, lastPointerY, Math.random() - 0.5, Math.random() - 0.5, 1.25);
}
requestRender();
}, { passive: true });
window.addEventListener('resize', resizeCanvas, { passive: true });
document.addEventListener('mouseout', event => {
if (event.relatedTarget) return;
clearParticles();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) clearParticles();
});
window.addEventListener('blur', clearParticles);
}
function initTheme() {
document.documentElement.setAttribute('data-theme', currentTheme);
const themeIcon = document.querySelector('#theme-toggle .toggle-glyph');
if (themeIcon) themeIcon.textContent = currentTheme === 'dark' ? UI_GLYPHS.themeDark : UI_GLYPHS.themeLight;
const themeToggle = document.getElementById('theme-toggle');
if (themeToggle) themeToggle.setAttribute('aria-pressed', String(currentTheme === 'dark'));
}
function getLanguageElements() {
const langToggle = document.getElementById('lang-toggle');
const langDropdown = document.getElementById('lang-dropdown');
const langOptions = langDropdown ? Array.from(langDropdown.querySelectorAll('[data-lang]')) : [];
return { langToggle, langDropdown, langOptions };
}
function getTokenSaverElements() {
const tokenSaverToggles = Array.from(document.querySelectorAll('[data-token-saver-toggle]'));
return { tokenSaverToggles };
}
function triggerTokenSaverAttention() {
const { tokenSaverToggles } = getTokenSaverElements();
if (!tokenSaverToggles.length) return;
tokenSaverToggles.forEach(toggle => {
toggle.classList.remove('is-attention');
});
window.requestAnimationFrame(() => {
window.requestAnimationFrame(() => {
tokenSaverToggles.forEach(toggle => {
toggle.classList.add('is-attention');
});
});
});
if (tokenSaverAttentionTimeoutId) window.clearTimeout(tokenSaverAttentionTimeoutId);
tokenSaverAttentionTimeoutId = window.setTimeout(() => {
tokenSaverToggles.forEach(toggle => {
toggle.classList.remove('is-attention');
});
}, 1800);
}
function getLanguageControlLabel() {
return getLanguageConfigValue(LANGUAGE_CONTROL_LABELS);
}
function setLanguageMenuState(isOpen) {
const { langToggle, langDropdown } = getLanguageElements();
if (!langToggle || !langDropdown) return;
langDropdown.classList.toggle('is-open', isOpen);
langToggle.setAttribute('aria-expanded', String(isOpen));
}
function focusLanguageOption(targetLang = currentLang) {
const { langOptions } = getLanguageElements();
const targetOption = (
langOptions.find(option => option.dataset.lang === targetLang)
|| langOptions.find(option => option.dataset.lang === getBaseLanguage(targetLang))
|| langOptions[0]
);
targetOption?.focus();
}
function updateTokenSaverUI() {
const { tokenSaverToggles } = getTokenSaverElements();
if (!tokenSaverToggles.length) return;
const baseLang = getBaseLanguage(currentLang);
const tokenSaverConfig = TOKEN_SAVER_VARIANTS[baseLang];
if (!tokenSaverConfig) {
tokenSaverToggles.forEach(toggle => {
toggle.hidden = true;
toggle.classList.remove('is-visible', 'is-active', 'is-attention');
toggle.removeAttribute('aria-label');
toggle.removeAttribute('aria-pressed');
toggle.removeAttribute('data-tooltip');
toggle.removeAttribute('data-state');
toggle.innerHTML = '';
});
return;
}
const isActive = currentLang === tokenSaverConfig.variant;
const actionLabel = isActive ? tokenSaverConfig.deactivateLabel : tokenSaverConfig.activateLabel;
let shouldTriggerAttention = false;
tokenSaverToggles.forEach(toggle => {
const wasHidden = toggle.hidden || !toggle.classList.contains('is-visible');
const previousPressed = toggle.getAttribute('aria-pressed');
toggle.hidden = false;
toggle.innerHTML = `
<span class="lang-variant-icon" aria-hidden="true">${tokenSaverConfig.icon}</span>
<span class="lang-variant-copy">${tokenSaverConfig.text}</span>
<span class="lang-variant-rail" aria-hidden="true"></span>
`;
toggle.classList.add('is-visible');
toggle.classList.toggle('is-active', isActive);
toggle.setAttribute('aria-label', actionLabel);
toggle.setAttribute('aria-pressed', String(isActive));
toggle.setAttribute('data-tooltip', actionLabel);
toggle.setAttribute('data-state', isActive ? 'active' : 'idle');
if (wasHidden || previousPressed !== String(isActive)) {
shouldTriggerAttention = true;
}
});
if (shouldTriggerAttention) triggerTokenSaverAttention();
}
function updateLanguageUI() {
const { langToggle, langDropdown, langOptions } = getLanguageElements();
if (!langToggle || !langDropdown || !langOptions.length) return;
const selectedOption = (
langOptions.find(option => option.dataset.lang === currentLang)
|| langOptions.find(option => option.dataset.lang === getBaseLanguage(currentLang))
|| langOptions[0]
);
langOptions.forEach((option, index) => {
if (!option.id) option.id = `lang-option-${option.dataset.lang || index}`;
option.tabIndex = -1;
option.setAttribute('aria-selected', String(option === selectedOption));
});
const controlLabel = getLanguageControlLabel();
const buttonLabel = selectedOption.dataset.buttonLabel
|| selectedOption.querySelector('.lang-option-main')?.textContent.trim()
|| selectedOption.textContent.trim();
langToggle.textContent = buttonLabel;
langToggle.setAttribute('aria-label', controlLabel);
langToggle.setAttribute('data-tooltip', controlLabel);
langToggle.setAttribute('aria-expanded', String(langDropdown.classList.contains('is-open')));
langDropdown.setAttribute('aria-label', controlLabel);
langDropdown.setAttribute('aria-activedescendant', selectedOption.id);
updateTokenSaverUI();
}
async function changeLanguage(nextLang) {
const targetLang = SUPPORTED_LANGS.includes(nextLang) ? nextLang : FALLBACK_LANG;
try {
siteData = await loadLanguage(targetLang);
currentLang = targetLang;
} catch {
currentLang = FALLBACK_LANG;
siteData = await loadLanguage(FALLBACK_LANG);
}
localStorage.setItem('lang', currentLang);
initLanguage();
renderDynamicContent();
syncAccessibilityUI();
announceStatus(getLanguageConfigValue(LANGUAGE_CHANGED_LABELS) || 'Language changed');
}
function initLanguage() {
document.documentElement.lang = getDocumentLanguageCode(currentLang);
updatePageText();
updateLanguageUI();
}
function updatePageText() {
if (!siteData) return;
const completedYears = getCompletedYearsSince(EXPERIENCE_START_DATE);
document.querySelectorAll('[data-i18n]').forEach(el => {
const path = el.getAttribute('data-i18n');
let value = getNestedValue(siteData, path);
if (typeof value === 'string') {
value = value.replace(/\{\{years\}\}/g, completedYears);
el.innerHTML = value;
}
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const path = el.getAttribute('data-i18n-placeholder');
let value = getNestedValue(siteData, path);
if (typeof value === 'string') {
value = value.replace(/\{\{years\}\}/g, completedYears);
el.placeholder = value;
}
});
document.querySelectorAll('[data-i18n-tooltip]').forEach(el => {