main.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Language selector
  2. (function () {
  3. var btn = document.querySelector('.lang-btn');
  4. var popup = document.querySelector('.lang-popup');
  5. if (!btn || !popup) return;
  6. btn.addEventListener('click', function (e) {
  7. e.stopPropagation();
  8. popup.classList.toggle('open');
  9. });
  10. document.addEventListener('click', function () {
  11. popup.classList.remove('open');
  12. });
  13. popup.addEventListener('click', function (e) {
  14. var link = e.target.closest('[data-lang]');
  15. if (!link) return;
  16. e.preventDefault();
  17. var lang = link.getAttribute('data-lang');
  18. localStorage.setItem('preferred-lang', lang);
  19. var basePath = document.documentElement.getAttribute('data-base-path') || '';
  20. var path = window.location.pathname;
  21. // Strip base path prefix, replace lang, then re-add base path
  22. var pathWithoutBase = path.slice(basePath.length);
  23. var newPath = basePath + pathWithoutBase.replace(/^\/[a-z]{2}\//, '/' + lang + '/');
  24. window.location.href = newPath;
  25. });
  26. })();
  27. // Theme toggle
  28. (function () {
  29. var btn = document.querySelector('.theme-toggle');
  30. if (!btn) return;
  31. function getTheme() {
  32. var stored = localStorage.getItem('preferred-theme');
  33. if (stored) return stored;
  34. return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
  35. }
  36. function applyTheme(theme) {
  37. if (theme === 'light') {
  38. document.documentElement.setAttribute('data-theme', 'light');
  39. } else {
  40. document.documentElement.removeAttribute('data-theme');
  41. }
  42. btn.textContent = theme === 'light' ? '\u2600\uFE0F' : '\uD83C\uDF19';
  43. }
  44. applyTheme(getTheme());
  45. btn.addEventListener('click', function () {
  46. var current = getTheme();
  47. var next = current === 'dark' ? 'light' : 'dark';
  48. localStorage.setItem('preferred-theme', next);
  49. applyTheme(next);
  50. });
  51. })();
  52. // Mobile sidebar toggle
  53. (function () {
  54. var toggle = document.querySelector('.sidebar-toggle');
  55. var sidebar = document.querySelector('.sidebar');
  56. if (!toggle || !sidebar) return;
  57. toggle.addEventListener('click', function () {
  58. sidebar.classList.toggle('open');
  59. });
  60. document.addEventListener('click', function (e) {
  61. if (!sidebar.contains(e.target) && e.target !== toggle) {
  62. sidebar.classList.remove('open');
  63. }
  64. });
  65. })();