File size: 2,338 Bytes
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afdf449
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a281968
 
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Bayan theme system — dark/light with localStorage persistence

const THEME_KEY = 'bayan-theme';

function getPreferredTheme() {
  const stored = localStorage.getItem(THEME_KEY);
  if (stored === 'light' || stored === 'dark') return stored;
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

function updateThemeToggleIcon(theme) {
  const btn = document.getElementById('theme-toggle');
  if (!btn) return;

  const isDark = theme === 'dark';
  btn.setAttribute('aria-pressed', isDark ? 'true' : 'false');
  btn.setAttribute(
    'aria-label',
    isDark ? 'التبديل إلى الوضع الفاتح' : 'التبديل إلى الوضع الداكن'
  );
  // CSS handles the sun/moon icon transitions via [data-theme] selectors
}

function clearThemePaletteOverrides() {
  const root = document.documentElement;
  const themeManaged = [
    '--color-bg', '--color-surface', '--color-surface-elevated', '--color-editor',
    '--color-text-primary', '--color-text-secondary', '--color-text-muted',
    '--background-color', '--surface-color', '--text-color', '--text-secondary'
  ];
  themeManaged.forEach((prop) => root.style.removeProperty(prop));
}

function setTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
  localStorage.setItem(THEME_KEY, theme);
  clearThemePaletteOverrides();
  updateThemeToggleIcon(theme);
  // Notify settings-sync so the change can be persisted to cloud
  window.dispatchEvent(new CustomEvent('bayan:themechange', { detail: { theme } }));
}

function toggleTheme() {
  const current = document.documentElement.getAttribute('data-theme') || 'dark';
  setTheme(current === 'dark' ? 'light' : 'dark');
}

function initTheme() {
  setTheme(getPreferredTheme());

  const btn = document.getElementById('theme-toggle');
  if (btn) {
    btn.addEventListener('click', toggleTheme);
  }
}

// Apply theme before paint to avoid flash
(function applyThemeEarly() {
  try {
    const stored = localStorage.getItem(THEME_KEY);
    const theme = stored === 'light' || stored === 'dark'
      ? stored
      : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
    document.documentElement.setAttribute('data-theme', theme);
  } catch (_) {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
})();