Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion installer/templates/phx_web/components/layouts.ex.eex
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ defmodule <%= @web_namespace %>.Layouts do
def theme_toggle(assigns) do
~H"""
<div class="card relative flex flex-row items-center border-2 border-base-300 bg-base-300 rounded-full">
<div class="absolute w-1/3 h-full rounded-full border-1 border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=light]_&]:left-1/3 [[data-theme=dark]_&]:left-2/3 transition-[left]" />
<div class="absolute w-1/3 h-full rounded-full border-1 border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=light]_&]:left-1/3 [[data-theme=dark]_&]:left-2/3 [[data-theme-source=system]_&]:!left-0 transition-[left]" />

<button
class="flex p-2 cursor-pointer w-1/3"<%= if @live do %>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@
</script><%= if @css do %>
<script>
(() => {
const systemTheme = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";

const setTheme = (theme) => {
if (theme === "system") {
localStorage.removeItem("phx:theme");
document.documentElement.removeAttribute("data-theme");
document.documentElement.setAttribute("data-theme", systemTheme());
document.documentElement.setAttribute("data-theme-source", "system");
} else {
localStorage.setItem("phx:theme", theme);
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.setAttribute("data-theme-source", "user");
}
};
if (!document.documentElement.hasAttribute("data-theme")) {
Expand All @@ -35,6 +39,12 @@
})
})<% else %>
window.addEventListener("phx:set-theme", (e) => setTheme(e.target.dataset.phxTheme));<% end %>

matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
if (document.documentElement.getAttribute("data-theme-source") === "system") {
document.documentElement.setAttribute("data-theme", systemTheme());
}
});
})();
</script><% end %>
</head>
Expand Down