| 48 | } |
| 49 | |
| 50 | pub fn set_theme(dark_mode: bool) { |
| 51 | let theme = if dark_mode { "dark" } else { "light" }; |
| 52 | |
| 53 | _ = document::eval(&format!( |
| 54 | r#" |
| 55 | (function () {{ |
| 56 | const COOKIE_NAME = '{COOKIE_NAME}'; |
| 57 | const CHANNEL_NAME = '{CHANNEL_NAME}'; |
| 58 | |
| 59 | function getCookie(name) {{ |
| 60 | const prefix = name + '='; |
| 61 | const parts = document.cookie.split(';'); |
| 62 | for (let p of parts) {{ |
| 63 | p = p.trim(); |
| 64 | if (p.startsWith(prefix)) return decodeURIComponent(p.slice(prefix.length)); |
| 65 | }} |
| 66 | return null; |
| 67 | }} |
| 68 | |
| 69 | document.documentElement.setAttribute('data-theme', '{theme}'); |
| 70 | if (getCookie(COOKIE_NAME) === '{theme}') return; |
| 71 | |
| 72 | document.cookie = '{COOKIE_NAME}={theme}; path=/; max-age=31536000; samesite=lax'; |
| 73 | |
| 74 | try {{ |
| 75 | const ch = window.__dx_theme_channel; |
| 76 | if (ch && typeof ch.postMessage === 'function') {{ |
| 77 | ch.postMessage({{ theme: '{theme}' }}); |
| 78 | }} else {{ |
| 79 | const tmp = new BroadcastChannel(CHANNEL_NAME); |
| 80 | tmp.postMessage({{ theme: '{theme}' }}); |
| 81 | tmp.close(); |
| 82 | }} |
| 83 | }} catch (_) {{}} |
| 84 | }})(); |
| 85 | "# |
| 86 | )); |
| 87 | } |
| 88 | |
| 89 | #[component] |
| 90 | pub fn DarkModeToggle() -> Element { |