analytics/lib/plausible_web/components/layout.ex

43 lines
1.3 KiB
Elixir

defmodule PlausibleWeb.Components.Layout do
@moduledoc false
use Phoenix.Component
def theme_script(assigns) do
~H"""
<script>
(function(){
var themePref = '<%= theme_preference(assigns) %>';
function reapplyTheme() {
var darkMediaPref = window.matchMedia('(prefers-color-scheme: dark)').matches;
var htmlRef = document.querySelector('html');
var hcaptchaRefs = Array.from(document.getElementsByClassName('h-captcha'));
var isDark = themePref === 'dark' || (themePref === 'system' && darkMediaPref);
if (isDark) {
htmlRef.classList.add('dark')
hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "dark"; });
} else {
htmlRef.classList.remove('dark');
hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "light"; });
}
}
reapplyTheme();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', reapplyTheme);
})()
</script>
"""
end
defp theme_preference(%{theme: theme}) when not is_nil(theme), do: theme
defp theme_preference(%{current_user: %Plausible.Auth.User{theme: theme}})
when not is_nil(theme) do
theme
end
defp theme_preference(_assigns), do: "system"
end