MCPcopy Create free account
hub / github.com/DioxusLabs/dioxus-components / set_theme

Function set_theme

preview/src/theme.rs:50–87  ·  view source on GitHub ↗
(dark_mode: bool)

Source from the content-addressed store, hash-verified

48}
49
50pub 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]
90pub fn DarkModeToggle() -> Element {

Callers 1

AppLayoutFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected