|
10 | 10 | {assigns[:page_title] || "Dashboard"} |
11 | 11 | </.live_title> |
12 | 12 | <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> |
13 | | - <link rel="stylesheet" href={asset_path(@conn, :css)} /> |
14 | | - <script defer src={asset_path(@conn, :js)}> |
15 | | - </script> |
16 | 13 | <script> |
17 | 14 | (() => { |
18 | | - const setTheme = (theme) => { |
19 | | - if (theme === "system") { |
20 | | - localStorage.removeItem("phx:theme"); |
21 | | - document.documentElement.removeAttribute("data-theme"); |
22 | | - } else { |
23 | | - localStorage.setItem("phx:theme", theme); |
24 | | - document.documentElement.setAttribute("data-theme", theme); |
25 | | - } |
26 | | - }; |
27 | | - if (!document.documentElement.hasAttribute("data-theme")) { |
28 | | - setTheme(localStorage.getItem("phx:theme") || "system"); |
| 15 | + let savedTheme = "system"; |
| 16 | + |
| 17 | + try { |
| 18 | + savedTheme = localStorage.getItem("theme") || "system"; |
| 19 | + } catch (_error) { |
| 20 | + // Storage can be unavailable in privacy-restricted browsing contexts. |
29 | 21 | } |
30 | | - window.addEventListener("storage", (e) => e.key === "phx:theme" && setTheme(e.newValue || "system")); |
31 | | - |
32 | | - window.addEventListener("phx:set-theme", (e) => setTheme(e.target.dataset.phxTheme)); |
| 22 | + |
| 23 | + const theme = ["system", "light", "dark"].includes(savedTheme) ? savedTheme : "system"; |
| 24 | + const appliedTheme = theme === "system" |
| 25 | + ? (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light") |
| 26 | + : theme; |
| 27 | +
|
| 28 | + document.documentElement.setAttribute("data-theme", appliedTheme); |
33 | 29 | })(); |
34 | 30 | </script> |
| 31 | + <link rel="stylesheet" href={asset_path(@conn, :css)} /> |
| 32 | + <script defer src={asset_path(@conn, :js)}> |
| 33 | + </script> |
35 | 34 | </head> |
36 | 35 | <body> |
37 | 36 | {@inner_content} |
|
0 commit comments